  



$(function () {
  $("#searchBlog").submit(function (event) {
    var text = $("#searchBlog input[name=text]").val();
    var site = $("#searchBlog input[name=site]").val();
    var action = $("#searchBlog ").attr("action");
    var searchUrl =
      window.location.protocol +
      "//" +
      window.location.host +
      "/" +
      action +
      "?text=" +
      text +
      "&site=" +
      site;
    window.location.href = searchUrl;
    event.preventDefault();
  });
});

$(document).ready(function () {

  $(".EnlargeButton").click(function (event) {
    event.preventDefault();
    $("#chartModal").modal("show", event);
  });

  $("body").on("click",".EnlargeButton",function (event) {
    event.preventDefault();
    $("#chartModal").modal("show", event);
  });


  $("#chartModal").on("show.bs.modal", function (event) {
    var img = $(event.relatedTarget.target).closest(".blogImage").find(".blogImagePopup")
    if (img.length == 0)
    {
      img = $(event.relatedTarget.currentTarget).parent().parent().find("img")
    }
    // Extract info from img attributes
    var imgSrc = img.attr("src");
    var imgAlt = img.attr("alt");
    var modal = $(this);
    modal.find(".modal-title").text(imgAlt);
    modal.find(".modal-body img").attr("src", imgSrc);
    modal.find(".modal-body img").attr("alt", imgAlt);
  });
});

/*!
Copyright 2016-2024 Kiln Enterprises Ltd

This file may be freely used, and distributed without modification.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
window.FlourishConfig={app_url:"https://app.flourish.studio",public_url:"https://public.flourish.studio/",embeds_url:"https://flo.uri.sh/"},function(){"use strict";var t=!1;function e(e){if(t&&window.top!==window.self){var o=window;"srcdoc"===o.location.pathname&&(o=o.parent);var r,i=(r={},window._Flourish_template_id&&(r.template_id=window._Flourish_template_id),window.Flourish&&window.Flourish.app&&window.Flourish.app.loaded_template_id&&(r.template_id=window.Flourish.app.loaded_template_id),window._Flourish_visualisation_id&&(r.visualisation_id=window._Flourish_visualisation_id),window.Flourish&&window.Flourish.app&&window.Flourish.app.loaded_visualisation&&(r.visualisation_id=window.Flourish.app.loaded_visualisation.id),window.Flourish&&window.Flourish.app&&window.Flourish.app.story&&(r.story_id=window.Flourish.app.story.id,r.slide_count=window.Flourish.app.story.slides.length),window.Flourish&&window.Flourish.app&&window.Flourish.app.current_slide&&(r.slide_index=window.Flourish.app.current_slide.index+1),r),n={sender:"Flourish",method:"customerAnalytics"};for(var a in i)i.hasOwnProperty(a)&&(n[a]=i[a]);for(var a in e)e.hasOwnProperty(a)&&(n[a]=e[a]);o.parent.postMessage(JSON.stringify(n),"*")}}function o(t){if("function"!=typeof t)throw new Error("Analytics callback is not a function");window.Flourish._analytics_listeners.push(t)}function r(t){if("function"!=typeof t)throw new Error("Analytics callback is not a function");window.Flourish._analytics_listeners=window.Flourish._analytics_listeners.filter((function(e){return t!==e}))}function i(){t=!0;[{event_name:"click",action_name:"click",use_capture:!0},{event_name:"keydown",action_name:"key_down",use_capture:!0},{event_name:"mouseenter",action_name:"mouse_enter",use_capture:!1},{event_name:"mouseleave",action_name:"mouse_leave",use_capture:!1}].forEach((function(t){document.body.addEventListener(t.event_name,(function(){e({action:t.action_name})}),t.use_capture)}))}
/*! @license DOMPurify 3.1.4 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.1.4/LICENSE */const{entries:n,setPrototypeOf:a,isFrozen:s,getPrototypeOf:l,getOwnPropertyDescriptor:u}=Object;let{freeze:c,seal:d,create:p}=Object,{apply:h,construct:m}="undefined"!=typeof Reflect&&Reflect;c||(c=function(t){return t}),d||(d=function(t){return t}),h||(h=function(t,e,o){return t.apply(e,o)}),m||(m=function(t,e){return new t(...e)});const f=C(Array.prototype.forEach),g=C(Array.prototype.pop),y=C(Array.prototype.push),w=C(String.prototype.toLowerCase),_=C(String.prototype.toString),b=C(String.prototype.match),v=C(String.prototype.replace),A=C(String.prototype.indexOf),x=C(String.prototype.trim),E=C(Object.prototype.hasOwnProperty),T=C(RegExp.prototype.test),F=(N=TypeError,function(){for(var t=arguments.length,e=new Array(t),o=0;o<t;o++)e[o]=arguments[o];return m(N,e)});var N;function S(t){return"number"==typeof t&&isNaN(t)}function C(t){return function(e){for(var o=arguments.length,r=new Array(o>1?o-1:0),i=1;i<o;i++)r[i-1]=arguments[i];return h(t,e,r)}}function k(t,e){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:w;a&&a(t,null);let r=e.length;for(;r--;){let i=e[r];if("string"==typeof i){const t=o(i);t!==i&&(s(e)||(e[r]=t),i=t)}t[i]=!0}return t}function L(t){for(let e=0;e<t.length;e++){E(t,e)||(t[e]=null)}return t}function R(t){const e=p(null);for(const[o,r]of n(t)){E(t,o)&&(Array.isArray(r)?e[o]=L(r):r&&"object"==typeof r&&r.constructor===Object?e[o]=R(r):e[o]=r)}return e}function O(t,e){for(;null!==t;){const o=u(t,e);if(o){if(o.get)return C(o.get);if("function"==typeof o.value)return C(o.value)}t=l(t)}return function(){return null}}const I=c(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),D=c(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),M=c(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),U=c(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),P=c(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),z=c(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),H=c(["#text"]),B=c(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),W=c(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),G=c(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),q=c(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),j=d(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Y=d(/<%[\w\W]*|[\w\W]*%>/gm),$=d(/\${[\w\W]*}/gm),X=d(/^data-[\-\w.\u00B7-\uFFFF]/),J=d(/^aria-[\-\w]+$/),K=d(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),V=d(/^(?:\w+script|data):/i),Z=d(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Q=d(/^html$/i),tt=d(/^[a-z][.\w]*(-[.\w]+)+$/i);var et=Object.freeze({__proto__:null,MUSTACHE_EXPR:j,ERB_EXPR:Y,TMPLIT_EXPR:$,DATA_ATTR:X,ARIA_ATTR:J,IS_ALLOWED_URI:K,IS_SCRIPT_OR_DATA:V,ATTR_WHITESPACE:Z,DOCTYPE_NAME:Q,CUSTOM_ELEMENT:tt});const ot=1,rt=3,it=7,nt=8,at=9,st=function(){return"undefined"==typeof window?null:window},lt=function(t,e){if("object"!=typeof t||"function"!=typeof t.createPolicy)return null;let o=null;const r="data-tt-policy-suffix";e&&e.hasAttribute(r)&&(o=e.getAttribute(r));const i="dompurify"+(o?"#"+o:"");try{return t.createPolicy(i,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){return console.warn("TrustedTypes policy "+i+" could not be created."),null}};var ut,ct,dt=function t(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:st();const o=e=>t(e);if(o.version="3.1.4",o.removed=[],!e||!e.document||e.document.nodeType!==at)return o.isSupported=!1,o;let{document:r}=e;const i=r,a=i.currentScript,{DocumentFragment:s,HTMLTemplateElement:l,Node:u,Element:d,NodeFilter:h,NamedNodeMap:m=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:N,DOMParser:C,trustedTypes:L}=e,j=d.prototype,Y=O(j,"cloneNode"),$=O(j,"nextSibling"),X=O(j,"childNodes"),J=O(j,"parentNode");if("function"==typeof l){const t=r.createElement("template");t.content&&t.content.ownerDocument&&(r=t.content.ownerDocument)}let V,Z="";const{implementation:tt,createNodeIterator:ut,createDocumentFragment:ct,getElementsByTagName:dt}=r,{importNode:pt}=i;let ht={};o.isSupported="function"==typeof n&&"function"==typeof J&&tt&&void 0!==tt.createHTMLDocument;const{MUSTACHE_EXPR:mt,ERB_EXPR:ft,TMPLIT_EXPR:gt,DATA_ATTR:yt,ARIA_ATTR:wt,IS_SCRIPT_OR_DATA:_t,ATTR_WHITESPACE:bt,CUSTOM_ELEMENT:vt}=et;let{IS_ALLOWED_URI:At}=et,xt=null;const Et=k({},[...I,...D,...M,...P,...H]);let Tt=null;const Ft=k({},[...B,...W,...G,...q]);let Nt=Object.seal(p(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),St=null,Ct=null,kt=!0,Lt=!0,Rt=!1,Ot=!0,It=!1,Dt=!0,Mt=!1,Ut=!1,Pt=!1,zt=!1,Ht=!1,Bt=!1,Wt=!0,Gt=!1;const qt="user-content-";let jt=!0,Yt=!1,$t={},Xt=null;const Jt=k({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Kt=null;const Vt=k({},["audio","video","img","source","image","track"]);let Zt=null;const Qt=k({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),te="http://www.w3.org/1998/Math/MathML",ee="http://www.w3.org/2000/svg",oe="http://www.w3.org/1999/xhtml";let re=oe,ie=!1,ne=null;const ae=k({},[te,ee,oe],_);let se=null;const le=["application/xhtml+xml","text/html"],ue="text/html";let ce=null,de=null;const pe=255,he=r.createElement("form"),me=function(t){return t instanceof RegExp||t instanceof Function},fe=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!de||de!==t){if(t&&"object"==typeof t||(t={}),t=R(t),se=-1===le.indexOf(t.PARSER_MEDIA_TYPE)?ue:t.PARSER_MEDIA_TYPE,ce="application/xhtml+xml"===se?_:w,xt=E(t,"ALLOWED_TAGS")?k({},t.ALLOWED_TAGS,ce):Et,Tt=E(t,"ALLOWED_ATTR")?k({},t.ALLOWED_ATTR,ce):Ft,ne=E(t,"ALLOWED_NAMESPACES")?k({},t.ALLOWED_NAMESPACES,_):ae,Zt=E(t,"ADD_URI_SAFE_ATTR")?k(R(Qt),t.ADD_URI_SAFE_ATTR,ce):Qt,Kt=E(t,"ADD_DATA_URI_TAGS")?k(R(Vt),t.ADD_DATA_URI_TAGS,ce):Vt,Xt=E(t,"FORBID_CONTENTS")?k({},t.FORBID_CONTENTS,ce):Jt,St=E(t,"FORBID_TAGS")?k({},t.FORBID_TAGS,ce):{},Ct=E(t,"FORBID_ATTR")?k({},t.FORBID_ATTR,ce):{},$t=!!E(t,"USE_PROFILES")&&t.USE_PROFILES,kt=!1!==t.ALLOW_ARIA_ATTR,Lt=!1!==t.ALLOW_DATA_ATTR,Rt=t.ALLOW_UNKNOWN_PROTOCOLS||!1,Ot=!1!==t.ALLOW_SELF_CLOSE_IN_ATTR,It=t.SAFE_FOR_TEMPLATES||!1,Dt=!1!==t.SAFE_FOR_XML,Mt=t.WHOLE_DOCUMENT||!1,zt=t.RETURN_DOM||!1,Ht=t.RETURN_DOM_FRAGMENT||!1,Bt=t.RETURN_TRUSTED_TYPE||!1,Pt=t.FORCE_BODY||!1,Wt=!1!==t.SANITIZE_DOM,Gt=t.SANITIZE_NAMED_PROPS||!1,jt=!1!==t.KEEP_CONTENT,Yt=t.IN_PLACE||!1,At=t.ALLOWED_URI_REGEXP||K,re=t.NAMESPACE||oe,Nt=t.CUSTOM_ELEMENT_HANDLING||{},t.CUSTOM_ELEMENT_HANDLING&&me(t.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Nt.tagNameCheck=t.CUSTOM_ELEMENT_HANDLING.tagNameCheck),t.CUSTOM_ELEMENT_HANDLING&&me(t.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Nt.attributeNameCheck=t.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),t.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof t.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Nt.allowCustomizedBuiltInElements=t.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),It&&(Lt=!1),Ht&&(zt=!0),$t&&(xt=k({},H),Tt=[],!0===$t.html&&(k(xt,I),k(Tt,B)),!0===$t.svg&&(k(xt,D),k(Tt,W),k(Tt,q)),!0===$t.svgFilters&&(k(xt,M),k(Tt,W),k(Tt,q)),!0===$t.mathMl&&(k(xt,P),k(Tt,G),k(Tt,q))),t.ADD_TAGS&&(xt===Et&&(xt=R(xt)),k(xt,t.ADD_TAGS,ce)),t.ADD_ATTR&&(Tt===Ft&&(Tt=R(Tt)),k(Tt,t.ADD_ATTR,ce)),t.ADD_URI_SAFE_ATTR&&k(Zt,t.ADD_URI_SAFE_ATTR,ce),t.FORBID_CONTENTS&&(Xt===Jt&&(Xt=R(Xt)),k(Xt,t.FORBID_CONTENTS,ce)),jt&&(xt["#text"]=!0),Mt&&k(xt,["html","head","body"]),xt.table&&(k(xt,["tbody"]),delete St.tbody),t.TRUSTED_TYPES_POLICY){if("function"!=typeof t.TRUSTED_TYPES_POLICY.createHTML)throw F('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof t.TRUSTED_TYPES_POLICY.createScriptURL)throw F('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');V=t.TRUSTED_TYPES_POLICY,Z=V.createHTML("")}else void 0===V&&(V=lt(L,a)),null!==V&&"string"==typeof Z&&(Z=V.createHTML(""));c&&c(t),de=t}},ge=k({},["mi","mo","mn","ms","mtext"]),ye=k({},["foreignobject","annotation-xml"]),we=k({},["title","style","font","a","script"]),_e=k({},[...D,...M,...U]),be=k({},[...P,...z]),ve=function(t){let e=J(t);e&&e.tagName||(e={namespaceURI:re,tagName:"template"});const o=w(t.tagName),r=w(e.tagName);return!!ne[t.namespaceURI]&&(t.namespaceURI===ee?e.namespaceURI===oe?"svg"===o:e.namespaceURI===te?"svg"===o&&("annotation-xml"===r||ge[r]):Boolean(_e[o]):t.namespaceURI===te?e.namespaceURI===oe?"math"===o:e.namespaceURI===ee?"math"===o&&ye[r]:Boolean(be[o]):t.namespaceURI===oe?!(e.namespaceURI===ee&&!ye[r])&&(!(e.namespaceURI===te&&!ge[r])&&(!be[o]&&(we[o]||!_e[o]))):!("application/xhtml+xml"!==se||!ne[t.namespaceURI]))},Ae=function(t){y(o.removed,{element:t});try{t.parentNode.removeChild(t)}catch(e){t.remove()}},xe=function(t,e){try{y(o.removed,{attribute:e.getAttributeNode(t),from:e})}catch(t){y(o.removed,{attribute:null,from:e})}if(e.removeAttribute(t),"is"===t&&!Tt[t])if(zt||Ht)try{Ae(e)}catch(t){}else try{e.setAttribute(t,"")}catch(t){}},Ee=function(t){let e=null,o=null;if(Pt)t="<remove></remove>"+t;else{const e=b(t,/^[\r\n\t ]+/);o=e&&e[0]}"application/xhtml+xml"===se&&re===oe&&(t='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+t+"</body></html>");const i=V?V.createHTML(t):t;if(re===oe)try{e=(new C).parseFromString(i,se)}catch(t){}if(!e||!e.documentElement){e=tt.createDocument(re,"template",null);try{e.documentElement.innerHTML=ie?Z:i}catch(t){}}const n=e.body||e.documentElement;return t&&o&&n.insertBefore(r.createTextNode(o),n.childNodes[0]||null),re===oe?dt.call(e,Mt?"html":"body")[0]:Mt?e.documentElement:n},Te=function(t){return ut.call(t.ownerDocument||t,t,h.SHOW_ELEMENT|h.SHOW_COMMENT|h.SHOW_TEXT|h.SHOW_PROCESSING_INSTRUCTION|h.SHOW_CDATA_SECTION,null)},Fe=function(t){return t instanceof N&&(void 0!==t.__depth&&"number"!=typeof t.__depth||void 0!==t.__removalCount&&"number"!=typeof t.__removalCount||"string"!=typeof t.nodeName||"string"!=typeof t.textContent||"function"!=typeof t.removeChild||!(t.attributes instanceof m)||"function"!=typeof t.removeAttribute||"function"!=typeof t.setAttribute||"string"!=typeof t.namespaceURI||"function"!=typeof t.insertBefore||"function"!=typeof t.hasChildNodes)},Ne=function(t){return"function"==typeof u&&t instanceof u},Se=function(t,e,r){ht[t]&&f(ht[t],(t=>{t.call(o,e,r,de)}))},Ce=function(t){let e=null;if(Se("beforeSanitizeElements",t,null),Fe(t))return Ae(t),!0;const r=ce(t.nodeName);if(Se("uponSanitizeElement",t,{tagName:r,allowedTags:xt}),t.hasChildNodes()&&!Ne(t.firstElementChild)&&T(/<[/\w]/g,t.innerHTML)&&T(/<[/\w]/g,t.textContent))return Ae(t),!0;if(t.nodeType===it)return Ae(t),!0;if(Dt&&t.nodeType===nt&&T(/<[/\w]/g,t.data))return Ae(t),!0;if(!xt[r]||St[r]){if(!St[r]&&Le(r)){if(Nt.tagNameCheck instanceof RegExp&&T(Nt.tagNameCheck,r))return!1;if(Nt.tagNameCheck instanceof Function&&Nt.tagNameCheck(r))return!1}if(jt&&!Xt[r]){const e=J(t)||t.parentNode,o=X(t)||t.childNodes;if(o&&e){for(let r=o.length-1;r>=0;--r){const i=Y(o[r],!0);i.__removalCount=(t.__removalCount||0)+1,e.insertBefore(i,$(t))}}}return Ae(t),!0}return t instanceof d&&!ve(t)?(Ae(t),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!T(/<\/no(script|embed|frames)/i,t.innerHTML)?(It&&t.nodeType===rt&&(e=t.textContent,f([mt,ft,gt],(t=>{e=v(e,t," ")})),t.textContent!==e&&(y(o.removed,{element:t.cloneNode()}),t.textContent=e)),Se("afterSanitizeElements",t,null),!1):(Ae(t),!0)},ke=function(t,e,o){if(Wt&&("id"===e||"name"===e)&&(o in r||o in he||"__depth"===o||"__removalCount"===o))return!1;if(Lt&&!Ct[e]&&T(yt,e));else if(kt&&T(wt,e));else if(!Tt[e]||Ct[e]){if(!(Le(t)&&(Nt.tagNameCheck instanceof RegExp&&T(Nt.tagNameCheck,t)||Nt.tagNameCheck instanceof Function&&Nt.tagNameCheck(t))&&(Nt.attributeNameCheck instanceof RegExp&&T(Nt.attributeNameCheck,e)||Nt.attributeNameCheck instanceof Function&&Nt.attributeNameCheck(e))||"is"===e&&Nt.allowCustomizedBuiltInElements&&(Nt.tagNameCheck instanceof RegExp&&T(Nt.tagNameCheck,o)||Nt.tagNameCheck instanceof Function&&Nt.tagNameCheck(o))))return!1}else if(Zt[e]);else if(T(At,v(o,bt,"")));else if("src"!==e&&"xlink:href"!==e&&"href"!==e||"script"===t||0!==A(o,"data:")||!Kt[t]){if(Rt&&!T(_t,v(o,bt,"")));else if(o)return!1}else;return!0},Le=function(t){return"annotation-xml"!==t&&b(t,vt)},Re=function(t){Se("beforeSanitizeAttributes",t,null);const{attributes:e}=t;if(!e)return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Tt};let i=e.length;for(;i--;){const n=e[i],{name:a,namespaceURI:s,value:l}=n,u=ce(a);let c="value"===a?l:x(l);if(r.attrName=u,r.attrValue=c,r.keepAttr=!0,r.forceKeepAttr=void 0,Se("uponSanitizeAttribute",t,r),c=r.attrValue,r.forceKeepAttr)continue;if(xe(a,t),!r.keepAttr)continue;if(!Ot&&T(/\/>/i,c)){xe(a,t);continue}if(Dt&&T(/((--!?|])>)|<\/(style|title)/i,c)){xe(a,t);continue}It&&f([mt,ft,gt],(t=>{c=v(c,t," ")}));const d=ce(t.nodeName);if(ke(d,u,c)){if(!Gt||"id"!==u&&"name"!==u||(xe(a,t),c=qt+c),V&&"object"==typeof L&&"function"==typeof L.getAttributeType)if(s);else switch(L.getAttributeType(d,u)){case"TrustedHTML":c=V.createHTML(c);break;case"TrustedScriptURL":c=V.createScriptURL(c)}try{s?t.setAttributeNS(s,a,c):t.setAttribute(a,c),Fe(t)?Ae(t):g(o.removed)}catch(t){}}}Se("afterSanitizeAttributes",t,null)},Oe=function t(e){let o=null;const r=Te(e);for(Se("beforeSanitizeShadowDOM",e,null);o=r.nextNode();){if(Se("uponSanitizeShadowNode",o,null),Ce(o))continue;const e=J(o);o.nodeType===ot&&(e&&e.__depth?o.__depth=(o.__removalCount||0)+e.__depth+1:o.__depth=1),(o.__depth>=pe||o.__depth<0||S(o.__depth))&&Ae(o),o.content instanceof s&&(o.content.__depth=o.__depth,t(o.content)),Re(o)}Se("afterSanitizeShadowDOM",e,null)};return o.sanitize=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,n=null,a=null,l=null;if(ie=!t,ie&&(t="\x3c!--\x3e"),"string"!=typeof t&&!Ne(t)){if("function"!=typeof t.toString)throw F("toString is not a function");if("string"!=typeof(t=t.toString()))throw F("dirty is not a string, aborting")}if(!o.isSupported)return t;if(Ut||fe(e),o.removed=[],"string"==typeof t&&(Yt=!1),Yt){if(t.nodeName){const e=ce(t.nodeName);if(!xt[e]||St[e])throw F("root node is forbidden and cannot be sanitized in-place")}}else if(t instanceof u)r=Ee("\x3c!----\x3e"),n=r.ownerDocument.importNode(t,!0),n.nodeType===ot&&"BODY"===n.nodeName||"HTML"===n.nodeName?r=n:r.appendChild(n);else{if(!zt&&!It&&!Mt&&-1===t.indexOf("<"))return V&&Bt?V.createHTML(t):t;if(r=Ee(t),!r)return zt?null:Bt?Z:""}r&&Pt&&Ae(r.firstChild);const c=Te(Yt?t:r);for(;a=c.nextNode();){if(Ce(a))continue;const t=J(a);a.nodeType===ot&&(t&&t.__depth?a.__depth=(a.__removalCount||0)+t.__depth+1:a.__depth=1),(a.__depth>=pe||a.__depth<0||S(a.__depth))&&Ae(a),a.content instanceof s&&(a.content.__depth=a.__depth,Oe(a.content)),Re(a)}if(Yt)return t;if(zt){if(Ht)for(l=ct.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(Tt.shadowroot||Tt.shadowrootmode)&&(l=pt.call(i,l,!0)),l}let d=Mt?r.outerHTML:r.innerHTML;return Mt&&xt["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&T(Q,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),It&&f([mt,ft,gt],(t=>{d=v(d,t," ")})),V&&Bt?V.createHTML(d):d},o.setConfig=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};fe(t),Ut=!0},o.clearConfig=function(){de=null,Ut=!1},o.isValidAttribute=function(t,e,o){de||fe({});const r=ce(t),i=ce(e);return ke(r,i,o)},o.addHook=function(t,e){"function"==typeof e&&(ht[t]=ht[t]||[],y(ht[t],e))},o.removeHook=function(t){if(ht[t])return g(ht[t])},o.removeHooks=function(t){ht[t]&&(ht[t]=[])},o.removeAllHooks=function(){ht={}},o}();function pt(){if(null==ut){var t=function(){var t=window.location;"about:srcdoc"==t.href&&(t=window.parent.location);var e={};return function(t,o,r){for(;r=o.exec(t);)e[decodeURIComponent(r[1])]=decodeURIComponent(r[2])}(t.search.substring(1).replace(/\+/g,"%20"),/([^&=]+)=?([^&]*)/g),e}();ut="referrer"in t?/^https:\/\/medium.com\//.test(t.referrer):!("auto"in t)}return ut}function ht(t){var e=t||window.innerWidth;return e>999?650:e>599?575:400}function mt(t){if(t&&window.top!==window.self){var e=window;"srcdoc"==e.location.pathname&&(e=e.parent);var o={sender:"Flourish",method:"scrolly",captions:t.captions};e.parent.postMessage(JSON.stringify(o),"*")}}function ft(t,e){if(window.top!==window.self){var o=window;if("srcdoc"==o.location.pathname&&(o=o.parent),ct)return t=parseInt(t,10),void o.parent.postMessage({sentinel:"amp",type:"embed-size",height:t},"*");var r={sender:"Flourish",context:"iframe.resize",method:"resize",height:t,src:o.location.toString()};if(e)for(var i in e)r[i]=e[i];o.parent.postMessage(JSON.stringify(r),"*")}}function gt(){return(-1!==navigator.userAgent.indexOf("Safari")||-1!==navigator.userAgent.indexOf("iPhone"))&&-1==navigator.userAgent.indexOf("Chrome")}function yt(t){return"string"==typeof t||t instanceof String}function wt(t){return"warn"!==t.method?(console.warn("BUG: validateWarnMessage called for method"+t.method),!1):!(null!=t.message&&!yt(t.message))&&!(null!=t.explanation&&!yt(t.explanation))}function _t(t){return"resize"!==t.method?(console.warn("BUG: validateResizeMessage called for method"+t.method),!1):!!yt(t.src)&&(!!yt(t.context)&&!!("number"==typeof(e=t.height)?!isNaN(e)&&e>=0:yt(e)&&/\d/.test(e)&&/^[0-9]*(\.[0-9]*)?(cm|mm|Q|in|pc|pt|px|em|ex|ch|rem|lh|vw|vh|vmin|vmax|%)?$/i.test(e)));var e}function bt(t){throw new Error("Validation for setSetting is not implemented yet; see issue #4328")}function vt(t){return"scrolly"!==t.method?(console.warn("BUG: validateScrolly called for method"+t.method),!1):!!Array.isArray(t.captions)}function At(t){return"customerAnalytics"===t.method||(console.warn("BUG: validateCustomerAnalyticsMessage called for method"+t.method),!1)}function xt(t){return"request-upload"!==t.method?(console.warn("BUG: validateResizeMessage called for method"+t.method),!1):!!yt(t.name)&&!(null!=t.accept&&!yt(t.accept))}function Et(t,e,o){var r=function(t){for(var e={warn:wt,resize:_t,setSetting:bt,customerAnalytics:At,"request-upload":xt,scrolly:vt},o={},r=0;r<t.length;r++){var i=t[r];if(!e[i])throw new Error("No validator found for method "+i);o[i]=e[i]}return o}(e);window.addEventListener("message",(function(e){var i=function(){if(e.origin==document.location.origin)return!0;if(o){const t=e.origin.toLowerCase();if(o=o.toLowerCase(),t.endsWith("//"+o))return!0;if(t.endsWith("."+o))return!0}return!!e.origin.match(/\/\/localhost:\d+$|\/\/(?:public|app)\.flourish.devlocal$|\/\/flourish-api\.com$|\.flourish\.(?:local(:\d+)?|net|rocks|studio)$|\.uri\.sh$|\/\/flourish-user-templates\.com$/)}();if(null!=e.source&&i){var n;try{n="object"==typeof e.data?e.data:JSON.parse(e.data)}catch(t){return void console.warn("Unexpected non-JSON message: "+JSON.stringify(e.data))}if("Flourish"===n.sender)if(n.method)if(Object.prototype.hasOwnProperty.call(r,n.method))if(r[n.method](n)){for(var a=document.querySelectorAll("iframe"),s=0;s<a.length;s++)if(a[s].contentWindow==e.source||a[s].contentWindow==e.source.parent)return void t(n,a[s]);console.warn("could not find frame",n)}else console.warn("Validation failed for the message",n);else console.warn("No validator implemented for message",n);else console.warn("The 'method' property was missing from message",n)}})),gt()&&(window.addEventListener("resize",Tt),Tt())}function Tt(){for(var t=document.querySelectorAll(".flourish-embed"),e=0;e<t.length;e++){var o=t[e];if(!o.getAttribute("data-width")){var r=o.querySelector("iframe");if(r){var i=window.getComputedStyle(o),n=o.offsetWidth-parseFloat(i.paddingLeft)-parseFloat(i.paddingRight);r.style.width=n+"px"}}}}function Ft(t,e){var o=t.parentNode;if(o.classList.contains("fl-scrolly-wrapper"))console.warn("createScrolly is being called more than once per story. This should not happen.");else{o.classList.add("fl-scrolly-wrapper"),o.style.position="relative",o.style.paddingBottom="1px",o.style.transform="translate3d(0, 0, 0)",t.style.position="sticky";var r=o.getAttribute("data-height")||null;r||(r="80vh",t.style.height=r),t.style.top="calc(50vh - "+r+"/2)";var i=o.querySelector(".flourish-credit");i&&(i.style.position="sticky",i.style.top="calc(50vh + "+r+"/2)"),e.forEach((function(t,e){var r="string"==typeof t&&""!=t.trim(),i=document.createElement("div");i.setAttribute("data-slide",e),i.classList.add("fl-scrolly-caption"),i.style.position="relative",i.style.transform="translate3d(0,0,0)",i.style.textAlign="center",i.style.maxWidth="500px",i.style.height="auto",i.style.marginTop="0",i.style.marginBottom=r?"100vh":"50vh",i.style.marginLeft="auto",i.style.marginRight="auto";var n=document.createElement("div");n.innerHTML=dt.sanitize(t,{ADD_ATTR:["target"]}),n.style.visibility=r?"":"hidden",n.style.display="inline-block",n.style.paddingTop="1.25em",n.style.paddingRight="1.25em",n.style.paddingBottom="1.25em",n.style.paddingLeft="1.25em",n.style.background="rgba(255,255,255,0.9)",n.style.boxShadow="0px 0px 10px rgba(0,0,0,0.2)",n.style.borderRadius="10px",n.style.textAlign="center",n.style.maxWidth="100%",n.style.margin="0 20px",n.style.overflowX="hidden",i.appendChild(n),o.appendChild(i)})),function(t){for(var e=new IntersectionObserver((function(e){e.forEach((function(e){if(e.isIntersecting){var o=t.querySelector("iframe");o&&(o.src=o.src.replace(/#slide-.*/,"")+"#slide-"+e.target.getAttribute("data-slide"))}}))}),{rootMargin:"0px 0px -0% 0px"}),o=t.querySelectorAll(".fl-scrolly-caption"),r=0;r<o.length;r++)e.observe(o[r]);t.querySelectorAll(".fl-scrolly-caption img").forEach((function(t){t.style.maxWidth="100%"}))}(o)}}function Nt(t,e,o,r,i){var n=document.createElement("iframe");if(n.setAttribute("scrolling","no"),n.setAttribute("frameborder","0"),n.setAttribute("title","Interactive or visual content"),n.setAttribute("sandbox","allow-same-origin allow-forms allow-scripts allow-downloads allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation"),e.appendChild(n),n.offsetParent||"fixed"===getComputedStyle(n).position)St(t,e,n,o,r,i);else{var a={embed_url:t,container:e,iframe:n,width:o,height:r,play_on_load:i};if(window._flourish_poll_items?window._flourish_poll_items.push(a):window._flourish_poll_items=[a],window._flourish_poll_items.length>1)return n;var s=setInterval((function(){window._flourish_poll_items=window._flourish_poll_items.filter((function(t){return!t.iframe.offsetParent||(St(t.embed_url,t.container,t.iframe,t.width,t.height,t.play_on_load),!1)})),window._flourish_poll_items.length||clearInterval(s)}),500)}return n}function St(t,e,o,r,i,n){var a;return r&&"number"==typeof r?(a=r,r+="px"):r&&r.match(/^[ \t\r\n\f]*([+-]?\d+|\d*\.\d+(?:[eE][+-]?\d+)?)(?:\\?[Pp]|\\0{0,4}[57]0(?:\r\n|[ \t\r\n\f])?)(?:\\?[Xx]|\\0{0,4}[57]8(?:\r\n|[ \t\r\n\f])?)[ \t\r\n\f]*$/)&&(a=parseFloat(r)),i&&"number"==typeof i&&(i+="px"),r?o.style.width=r:gt()?o.style.width=e.offsetWidth+"px":o.style.width="100%",!!i||(t.match(/\?/)?t+="&auto=1":t+="?auto=1",i=ht(a||o.offsetWidth)+"px"),i&&("%"===i.charAt(i.length-1)&&(i=parseFloat(i)/100*e.parentNode.offsetHeight+"px"),o.style.height=i),o.setAttribute("src",t+(n?"#play-on-load":"")),o}var Ct={de:{credits:{default:"Erstellt mit Flourish"}},en:{credits:{default:{text:"A Flourish data visualization",url:"https://flourish.studio/"},annotator:{text:"Interactive content by Flourish",url:"https://app.flourish.studio/@flourish/svg-annotator"},"bar-chart-race":{text:"A Flourish bar chart race",url:"https://flourish.studio/visualisations/bar-chart-race/"},"bubble-chart":{text:"A Flourish bubble chart",url:"https://flourish.studio/blog/introducing-bubble-chart-template/"},cards:{text:"Interactive content by Flourish",url:"https://flourish.studio/blog/cards-template/"},chart:{text:"A Flourish chart",url:"https://flourish.studio/visualisations/line-bar-pie-charts/"},chord:{text:"A Flourish chord diagram",url:"https://flourish.studio/blog/how-to-make-a-chord-diagram/"},countdown:{text:"Interactive content by Flourish",url:"https://flourish.studio/blog/number-ticker-countdown-templates/"},"data-explorer":{text:"A Flourish data explorer",url:"https://flourish.studio/blog/data-explorer-template/"},draw:{text:"Interactive content by Flourish",url:"https://flourish.studio/blog/draw-the-line-chart/"},election:{text:"A Flourish election chart",url:"https://app.flourish.studio/@flourish/election-results-chart"},gantt:{text:"A Flourish gantt chart",url:"https://flourish.studio/blog/gantt-chart-template/"},gauge:{text:"A Flourish gauge visualization",url:"https://flourish.studio/visualisations/gauge/"},globe:{text:"A Flourish connections globe",url:"https://flourish.studio/visualisations/maps/"},heatmap:{text:"A Flourish heatmap",url:"https://flourish.studio/visualisations/heatmaps/"},hierarchy:{text:"A Flourish hierarchy chart",url:"https://flourish.studio/visualisations/treemaps/"},map:{text:"A Flourish map",url:"https://flourish.studio/visualisations/maps/"},marimekko:{text:"A Flourish marimekko chart",url:"https://flourish.studio/visualisations/marimekko-charts/"},model:{text:"Interactive content by Flourish",url:"https://app.flourish.studio/@flourish/3d-viewer"},network:{text:"A Flourish network chart",url:"https://flourish.studio/visualisations/network-charts/"},"number-ticker":{text:"Interactive content by Flourish",url:"https://flourish.studio/blog/number-ticker-countdown-templates/"},parliament:{text:"A Flourish election chart",url:"https://flourish.studio/blog/how-to-make-parliament-chart/"},"photo-slider":{text:"Interactive content by Flourish",url:"https://app.flourish.studio/@flourish/photo-slider"},pictogram:{text:"A Flourish pictogram",url:"https://flourish.studio/blog/pictogram-isotype/"},quiz:{text:"A Flourish quiz",url:"https://app.flourish.studio/@flourish/quiz"},radar:{text:"A Flourish radar chart",url:"https://flourish.studio/blog/create-online-radar-spider-charts/"},ranking:{text:"A Flourish line chart race",url:"https://flourish.studio/blog/line-chart-race-updates/"},sankey:{text:"A Flourish sankey chart",url:"https://flourish.studio/visualisations/sankey-charts/"},scatter:{text:"A Flourish scatter chart",url:"https://flourish.studio/visualisations/scatter-charts/"},slope:{text:"A Flourish slope chart",url:"https://flourish.studio/visualisations/slope-charts/"},sports:{text:"A Flourish sports visualization",url:"https://app.flourish.studio/@flourish/sports-race"},survey:{text:"A Flourish survey visualization",url:"https://flourish.studio/visualisations/survey-data/"},table:{text:"A Flourish table",url:"https://flourish.studio/visualisations/create-a-table/"},timeline:{text:"Interactive content by Flourish",url:"https://flourish.studio/blog/responsive-interactive-timeline/"},"text-annotator":{text:"Interactive content by Flourish",url:"https://flourish.studio/blog/text-annotator-template/"},tournament:{text:"Interactive content by Flourish",url:"https://flourish.studio/visualisations/tournament-chart/"},"word-cloud":{text:"A Flourish data visualization",url:"https://flourish.studio/blog/online-wordcloud-custom-fonts/"}}},es:{credits:{default:"Creado con Flourish",bar_race:{text:"Creado con Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"},"bar-chart-race":{text:"Creado con Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"}}},fr:{credits:{default:"Créé avec Flourish",bar_race:{text:"Créé avec Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"},"bar-chart-race":{text:"Créé avec Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"}}},it:{credits:{default:"Creato con Flourish",bar_race:{text:"Creato con Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"},"bar-chart-race":{text:"Creato con Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"}}},mi:{credits:{default:"Hangaia ki te Flourish",bar_race:{text:"Hangaia ki te Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"},"bar-chart-race":{text:"Hangaia ki te Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"}}},nl:{credits:{default:"Gemaakt met Flourish",bar_race:{text:"Gemaakt met Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"},"bar-chart-race":{text:"Gemaakt met Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"}}},pt:{default:"Feito com Flourish",bar_race:{text:"Feito com Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"},"bar-chart-race":{text:"Feito com Flourish",url:"https://flourish.studio/visualisations/bar-chart-race/"}}};!function(){var t=[];function n(){if(!window.FlourishLoaded){window.FlourishLoaded=!0;var r=window.Flourish&&window.Flourish.external,n="en",a=document.querySelector("meta[name='language'],meta[name='LANGUAGE']");a&&a.hasAttribute("content")&&(n=a.getAttribute("content").substr(0,2),Ct[n]||(n="en"));var s,l=Array.prototype.slice.call(document.querySelectorAll(".flourish-embed"));if(!r)for(var u=document.querySelectorAll("script"),c=0;c<u.length;c++){var d=u[c];if(d.src&&d.src.match(/(?:\.flourish\.(?:net|rocks|studio)|(?:localhost|flourish\.local)(?::\d+)?)\//g)&&d.src.match(/\/embed\.js$/)){if(!s){var p=d.getAttribute("src");s=p.substr(0,p.lastIndexOf("/resources"))+"/"}if(d.getAttribute("data-src")){var h=document.createElement("div");h.setAttribute("class","flourish-embed"),h.setAttribute("data-src",d.getAttribute("data-src")),d.getAttribute("data-height")&&h.setAttribute("data-height",d.getAttribute("data-height")),d.getAttribute("data-width")&&h.setAttribute("data-width",d.getAttribute("data-width")),d.parentNode.insertBefore(h,d),l.push(h)}}}var m=(ct="#amp=1"==window.location.hash,{createEmbedIframe:Nt,isFixedHeight:pt,getHeightForBreakpoint:ht,startEventListeners:Et,notifyParentWindow:ft,initScrolly:mt,createScrolly:Ft,isSafari:gt,initCustomerAnalytics:i,addAnalyticsListener:o,sendCustomerAnalyticsMessage:e}),f=function(t){var e,o,i,a=t.getAttribute("data-src");if(a){var l,u=a.split("?"),c=u.length>1||window.Flourish&&window.Flourish.hide;if(a=u[0],r?(l=a,e=window.FlourishConfig.public_url,o="?utm_source=embed&utm_campaign="+a):(l=(i=0===a.indexOf("template/"))?window.FlourishConfig.app_url+"/"+a+"/preview":window.FlourishConfig.embeds_url+a+"/embed",e=s+a+"/",o="?utm_source=showcase&utm_campaign="+a),m.createEmbedIframe(l,t,t.getAttribute("data-width"),t.getAttribute("data-height"),t.hasAttribute("data-play-on-load")),!i&&!c){for(var d="",p=t.className.split(" "),h=0;h<p.length;h++)if("flourish-embed"!=p[h]&&0==p[h].indexOf("flourish-")){d=p[h].substr(9);break}d||(d=0==a.indexOf("story")?"story":"default");var f=function(t,e){var o,r;return e=e||"","object"==typeof(o=Ct[t=t||"en"].credits[e]||Ct.en.credits[e]||Ct.en.credits.default)&&(o.url&&(r=o.url),o=o.text),{credit_text:o,credit_url:r}}(n,d),g=function(t,e,o,r){t=t||"https://flourish.studio",e=e||"?utm_source=api&utm_campaign="+window.location.href,o=o||"https://public.flourish.studio/",r=r||"A Flourish data visualization";var i=document.createElement("div");i.setAttribute("class","flourish-credit"),i.setAttribute("style","width:100%!important;margin:0 0 4px!important;text-align:right!important;font-family:Helvetica,sans-serif!important;color:#888!important;font-size:11px!important;font-weight:bold!important;font-style:normal!important;-webkit-font-smoothing:antialiased!important;box-shadow:none!important;");var n=document.createElement("a");n.setAttribute("href",t+e),n.setAttribute("target","_top"),n.setAttribute("style","display:inline-block!important;text-decoration:none!important;font:inherit!important;color:inherit!important;border:none!important;margin:0 5px!important;box-shadow:none!important;"),i.appendChild(n);var a=document.createElement("img");a.setAttribute("alt","Flourish logo"),a.setAttribute("src",o+"resources/bosh.svg"),a.setAttribute("style","font:inherit!important;width:auto!important;height:12px!important;border:none!important;margin:0 2px 0!important;vertical-align:middle!important;display:inline-block!important;box-shadow:none!important;"),n.appendChild(a);var s=document.createElement("span");return s.setAttribute("style","font:inherit!important;color:#888!important;vertical-align:middle!important;display:inline-block!important;box-shadow:none!important;"),s.appendChild(document.createTextNode(r)),n.appendChild(s),i}(f.credit_url||e,o,window.FlourishConfig.public_url,f.credit_text);t.appendChild(g)}}};if(!window.Flourish||!window.Flourish.disable_autoload)for(c=0;c<l.length;c++)f(l[c]);m.startEventListeners((function(t,e){if("resize"==t.method){var o=t.height,r=typeof o;("number"===r||"string"===r&&!isNaN(o))&&(t.height+="px"),e.style.height=t.height}else"customerAnalytics"===t.method?(delete t.method,delete t.sender,function(t){window.Flourish&&window.Flourish._analytics_listeners.forEach((function(e){e(t)}))}(t)):"scrolly"===t.method&&m.createScrolly(e,t.captions)}),["resize","customerAnalytics","scrolly"],window.Flourish&&window.Flourish.embed_domain);for(c=0;c<t.length;c++)f(t[c]);window.Flourish&&(window.Flourish.loadEmbed=f)}}window.Flourish&&(window.Flourish.loadEmbed=function(e){t.push(e)},window.Flourish.addAnalyticsListener=o,window.Flourish.removeAnalyticsListener=r,window.Flourish._analytics_listeners||(window.Flourish._analytics_listeners=[])),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",n):n()}()}();
//# sourceMappingURL=embed.js.map
/* =========================================================
 * bootstrap-datepicker.js
 * Repo: https://github.com/eternicode/bootstrap-datepicker/
 * Demo: http://eternicode.github.io/bootstrap-datepicker/
 * Docs: http://bootstrap-datepicker.readthedocs.org/
 * Forked from http://www.eyecon.ro/bootstrap-datepicker
 * =========================================================
 * Started by Stefan Petre; improvements by Andrew Rowls + contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

(function($, undefined){

	var $window = $(window);

	function UTCDate(){
		return new Date(Date.UTC.apply(Date, arguments));
	}
	function UTCToday(){
		var today = new Date();
		return UTCDate(today.getFullYear(), today.getMonth(), today.getDate());
	}
	function alias(method){
		return function(){
			return this[method].apply(this, arguments);
		};
	}

	var DateArray = (function(){
		var extras = {
			get: function(i){
				return this.slice(i)[0];
			},
			contains: function(d){
				// Array.indexOf is not cross-browser;
				// $.inArray doesn't work with Dates
				var val = d && d.valueOf();
				for (var i=0, l=this.length; i < l; i++)
					if (this[i].valueOf() === val)
						return i;
				return -1;
			},
			remove: function(i){
				this.splice(i,1);
			},
			replace: function(new_array){
				if (!new_array)
					return;
				if (!$.isArray(new_array))
					new_array = [new_array];
				this.clear();
				this.push.apply(this, new_array);
			},
			clear: function(){
				this.length = 0;
			},
			copy: function(){
				var a = new DateArray();
				a.replace(this);
				return a;
			}
		};

		return function(){
			var a = [];
			a.push.apply(a, arguments);
			$.extend(a, extras);
			return a;
		};
	})();


	// Picker object

	var Datepicker = function(element, options){
		this.dates = new DateArray();
		this.viewDate = UTCToday();
		this.focusDate = null;

		this._process_options(options);

		this.element = $(element);
		this.isInline = false;
		this.isInput = this.element.is('input');
		this.component = this.element.is('.date') ? this.element.find('.add-on, .input-group-addon, .btn') : false;
		this.hasInput = this.component && this.element.find('input').length;
		if (this.component && this.component.length === 0)
			this.component = false;

		this.picker = $(DPGlobal.template);
		this._buildEvents();
		this._attachEvents();

		if (this.isInline){
			this.picker.addClass('datepicker-inline').appendTo(this.element);
		}
		else {
			this.picker.addClass('datepicker-dropdown dropdown-menu');
		}

		if (this.o.rtl){
			this.picker.addClass('datepicker-rtl');
		}

		this.viewMode = this.o.startView;

		if (this.o.calendarWeeks)
			this.picker.find('tfoot th.today')
						.attr('colspan', function(i, val){
							return parseInt(val) + 1;
						});

		this._allow_update = false;

		this.setStartDate(this._o.startDate);
		this.setEndDate(this._o.endDate);
		this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);

		this.fillDow();
		this.fillMonths();

		this._allow_update = true;

		this.update();
		this.showMode();

		if (this.isInline){
			this.show();
		}
	};

	Datepicker.prototype = {
		constructor: Datepicker,

		_process_options: function(opts){
			// Store raw options for reference
			this._o = $.extend({}, this._o, opts);
			// Processed options
			var o = this.o = $.extend({}, this._o);

			// Check if "de-DE" style date is available, if not language should
			// fallback to 2 letter code eg "de"
			var lang = o.language;
			if (!dates[lang]){
				lang = lang.split('-')[0];
				if (!dates[lang])
					lang = defaults.language;
			}
			o.language = lang;

			switch (o.startView){
				case 2:
				case 'decade':
					o.startView = 2;
					break;
				case 1:
				case 'year':
					o.startView = 1;
					break;
				default:
					o.startView = 0;
			}

			switch (o.minViewMode){
				case 1:
				case 'months':
					o.minViewMode = 1;
					break;
				case 2:
				case 'years':
					o.minViewMode = 2;
					break;
				default:
					o.minViewMode = 0;
			}

			o.startView = Math.max(o.startView, o.minViewMode);

			// true, false, or Number > 0
			if (o.multidate !== true){
				o.multidate = Number(o.multidate) || false;
				if (o.multidate !== false)
					o.multidate = Math.max(0, o.multidate);
				else
					o.multidate = 1;
			}
			o.multidateSeparator = String(o.multidateSeparator);

			o.weekStart %= 7;
			o.weekEnd = ((o.weekStart + 6) % 7);

			var format = DPGlobal.parseFormat(o.format);
			if (o.startDate !== -Infinity){
				if (!!o.startDate){
					if (o.startDate instanceof Date)
						o.startDate = this._local_to_utc(this._zero_time(o.startDate));
					else
						o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
				}
				else {
					o.startDate = -Infinity;
				}
			}
			if (o.endDate !== Infinity){
				if (!!o.endDate){
					if (o.endDate instanceof Date)
						o.endDate = this._local_to_utc(this._zero_time(o.endDate));
					else
						o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
				}
				else {
					o.endDate = Infinity;
				}
			}

			o.daysOfWeekDisabled = o.daysOfWeekDisabled||[];
			if (!$.isArray(o.daysOfWeekDisabled))
				o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
			o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function(d){
				return parseInt(d, 10);
			});

			var plc = String(o.orientation).toLowerCase().split(/\s+/g),
				_plc = o.orientation.toLowerCase();
			plc = $.grep(plc, function(word){
				return (/^auto|left|right|top|bottom$/).test(word);
			});
			o.orientation = {x: 'auto', y: 'auto'};
			if (!_plc || _plc === 'auto')
				; // no action
			else if (plc.length === 1){
				switch (plc[0]){
					case 'top':
					case 'bottom':
						o.orientation.y = plc[0];
						break;
					case 'left':
					case 'right':
						o.orientation.x = plc[0];
						break;
				}
			}
			else {
				_plc = $.grep(plc, function(word){
					return (/^left|right$/).test(word);
				});
				o.orientation.x = _plc[0] || 'auto';

				_plc = $.grep(plc, function(word){
					return (/^top|bottom$/).test(word);
				});
				o.orientation.y = _plc[0] || 'auto';
			}
		},
		_events: [],
		_secondaryEvents: [],
		_applyEvents: function(evs){
			for (var i=0, el, ch, ev; i < evs.length; i++){
				el = evs[i][0];
				if (evs[i].length === 2){
					ch = undefined;
					ev = evs[i][1];
				}
				else if (evs[i].length === 3){
					ch = evs[i][1];
					ev = evs[i][2];
				}
				el.on(ev, ch);
			}
		},
		_unapplyEvents: function(evs){
			for (var i=0, el, ev, ch; i < evs.length; i++){
				el = evs[i][0];
				if (evs[i].length === 2){
					ch = undefined;
					ev = evs[i][1];
				}
				else if (evs[i].length === 3){
					ch = evs[i][1];
					ev = evs[i][2];
				}
				el.off(ev, ch);
			}
		},
		_buildEvents: function(){
			if (this.isInput){ // single input
				this._events = [
					[this.element, {
						focus: $.proxy(this.show, this),
						keyup: $.proxy(function(e){
							if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
								this.update();
						}, this),
						keydown: $.proxy(this.keydown, this)
					}]
				];
			}
			else if (this.component && this.hasInput){ // component: input + button
				this._events = [
					// For components that are not readonly, allow keyboard nav
					[this.element.find('input'), {
						focus: $.proxy(this.show, this),
						keyup: $.proxy(function(e){
							if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
								this.update();
						}, this),
						keydown: $.proxy(this.keydown, this)
					}],
					[this.component, {
						click: $.proxy(this.show, this)
					}]
				];
			}
			else if (this.element.is('div')){  // inline datepicker
				this.isInline = true;
			}
			else {
				this._events = [
					[this.element, {
						click: $.proxy(this.show, this)
					}]
				];
			}
			this._events.push(
				// Component: listen for blur on element descendants
				[this.element, '*', {
					blur: $.proxy(function(e){
						this._focused_from = e.target;
					}, this)
				}],
				// Input: listen for blur on element
				[this.element, {
					blur: $.proxy(function(e){
						this._focused_from = e.target;
					}, this)
				}]
			);

			this._secondaryEvents = [
				[this.picker, {
					click: $.proxy(this.click, this)
				}],
				[$(window), {
					resize: $.proxy(this.place, this)
				}],
				[$(document), {
					'mousedown touchstart': $.proxy(function(e){
						// Clicked outside the datepicker, hide it
						if (!(
							this.element.is(e.target) ||
							this.element.find(e.target).length ||
							this.picker.is(e.target) ||
							this.picker.find(e.target).length
						)){
							this.hide();
						}
					}, this)
				}]
			];
		},
		_attachEvents: function(){
			this._detachEvents();
			this._applyEvents(this._events);
		},
		_detachEvents: function(){
			this._unapplyEvents(this._events);
		},
		_attachSecondaryEvents: function(){
			this._detachSecondaryEvents();
			this._applyEvents(this._secondaryEvents);
		},
		_detachSecondaryEvents: function(){
			this._unapplyEvents(this._secondaryEvents);
		},
		_trigger: function(event, altdate){
			var date = altdate || this.dates.get(-1),
				local_date = this._utc_to_local(date);

			this.element.trigger({
				type: event,
				date: local_date,
				dates: $.map(this.dates, this._utc_to_local),
				format: $.proxy(function(ix, format){
					if (arguments.length === 0){
						ix = this.dates.length - 1;
						format = this.o.format;
					}
					else if (typeof ix === 'string'){
						format = ix;
						ix = this.dates.length - 1;
					}
					format = format || this.o.format;
					var date = this.dates.get(ix);
					return DPGlobal.formatDate(date, format, this.o.language);
				}, this)
			});
		},

		show: function(){
			if (!this.isInline)
				this.picker.appendTo('body');
			this.picker.show();
			this.place();
			this._attachSecondaryEvents();
			this._trigger('show');
		},

		hide: function(){
			if (this.isInline)
				return;
			if (!this.picker.is(':visible'))
				return;
			this.focusDate = null;
			this.picker.hide().detach();
			this._detachSecondaryEvents();
			this.viewMode = this.o.startView;
			this.showMode();

			if (
				this.o.forceParse &&
				(
					this.isInput && this.element.val() ||
					this.hasInput && this.element.find('input').val()
				)
			)
				this.setValue();
			this._trigger('hide');
		},

		remove: function(){
			this.hide();
			this._detachEvents();
			this._detachSecondaryEvents();
			this.picker.remove();
			delete this.element.data().datepicker;
			if (!this.isInput){
				delete this.element.data().date;
			}
		},

		_utc_to_local: function(utc){
			return utc && new Date(utc.getTime() + (utc.getTimezoneOffset()*60000));
		},
		_local_to_utc: function(local){
			return local && new Date(local.getTime() - (local.getTimezoneOffset()*60000));
		},
		_zero_time: function(local){
			return local && new Date(local.getFullYear(), local.getMonth(), local.getDate());
		},
		_zero_utc_time: function(utc){
			return utc && new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate()));
		},

		getDates: function(){
			return $.map(this.dates, this._utc_to_local);
		},

		getUTCDates: function(){
			return $.map(this.dates, function(d){
				return new Date(d);
			});
		},

		getDate: function(){
			return this._utc_to_local(this.getUTCDate());
		},

		getUTCDate: function(){
			return new Date(this.dates.get(-1));
		},

		setDates: function(){
			var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
			this.update.apply(this, args);
			this._trigger('changeDate');
			this.setValue();
		},

		setUTCDates: function(){
			var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
			this.update.apply(this, $.map(args, this._utc_to_local));
			this._trigger('changeDate');
			this.setValue();
		},

		setDate: alias('setDates'),
		setUTCDate: alias('setUTCDates'),

		setValue: function(){
			var formatted = this.getFormattedDate();
			if (!this.isInput){
				if (this.component){
					this.element.find('input').val(formatted).change();
				}
			}
			else {
				this.element.val(formatted).change();
			}
		},

		getFormattedDate: function(format){
			if (format === undefined)
				format = this.o.format;

			var lang = this.o.language;
			return $.map(this.dates, function(d){
				return DPGlobal.formatDate(d, format, lang);
			}).join(this.o.multidateSeparator);
		},

		setStartDate: function(startDate){
			this._process_options({startDate: startDate});
			this.update();
			this.updateNavArrows();
		},

		setEndDate: function(endDate){
			this._process_options({endDate: endDate});
			this.update();
			this.updateNavArrows();
		},

		setDaysOfWeekDisabled: function(daysOfWeekDisabled){
			this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
			this.update();
			this.updateNavArrows();
		},

		place: function(){
			if (this.isInline)
				return;
			var calendarWidth = this.picker.outerWidth(),
				calendarHeight = this.picker.outerHeight(),
				visualPadding = 10,
				windowWidth = $window.width(),
				windowHeight = $window.height(),
				scrollTop = $window.scrollTop();

			var zIndex = parseInt(this.element.parents().filter(function(){
					return $(this).css('z-index') !== 'auto';
				}).first().css('z-index'))+10;
			var offset = this.component ? this.component.parent().offset() : this.element.offset();
			var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
			var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
			var left = offset.left,
				top = offset.top;

			this.picker.removeClass(
				'datepicker-orient-top datepicker-orient-bottom '+
				'datepicker-orient-right datepicker-orient-left'
			);

			if (this.o.orientation.x !== 'auto'){
				this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
				if (this.o.orientation.x === 'right')
					left -= calendarWidth - width;
			}
			// auto x orientation is best-placement: if it crosses a window
			// edge, fudge it sideways
			else {
				// Default to left
				this.picker.addClass('datepicker-orient-left');
				if (offset.left < 0)
					left -= offset.left - visualPadding;
				else if (offset.left + calendarWidth > windowWidth)
					left = windowWidth - calendarWidth - visualPadding;
			}

			// auto y orientation is best-situation: top or bottom, no fudging,
			// decision based on which shows more of the calendar
			var yorient = this.o.orientation.y,
				top_overflow, bottom_overflow;
			if (yorient === 'auto'){
				top_overflow = -scrollTop + offset.top - calendarHeight;
				bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight);
				if (Math.max(top_overflow, bottom_overflow) === bottom_overflow)
					yorient = 'top';
				else
					yorient = 'bottom';
			}
			this.picker.addClass('datepicker-orient-' + yorient);
			if (yorient === 'top')
				top += height;
			else
				top -= calendarHeight + parseInt(this.picker.css('padding-top'));

			this.picker.css({
				top: top,
				left: left,
				zIndex: zIndex
			});
		},

		_allow_update: true,
		update: function(){
			if (!this._allow_update)
				return;

			var oldDates = this.dates.copy(),
				dates = [],
				fromArgs = false;
			if (arguments.length){
				$.each(arguments, $.proxy(function(i, date){
					if (date instanceof Date)
						date = this._local_to_utc(date);
					dates.push(date);
				}, this));
				fromArgs = true;
			}
			else {
				dates = this.isInput
						? this.element.val()
						: this.element.data('date') || this.element.find('input').val();
				if (dates && this.o.multidate)
					dates = dates.split(this.o.multidateSeparator);
				else
					dates = [dates];
				delete this.element.data().date;
			}

			dates = $.map(dates, $.proxy(function(date){
				return DPGlobal.parseDate(date, this.o.format, this.o.language);
			}, this));
			dates = $.grep(dates, $.proxy(function(date){
				return (
					date < this.o.startDate ||
					date > this.o.endDate ||
					!date
				);
			}, this), true);
			this.dates.replace(dates);

			if (this.dates.length)
				this.viewDate = new Date(this.dates.get(-1));
			else if (this.viewDate < this.o.startDate)
				this.viewDate = new Date(this.o.startDate);
			else if (this.viewDate > this.o.endDate)
				this.viewDate = new Date(this.o.endDate);

			if (fromArgs){
				// setting date by clicking
				this.setValue();
			}
			else if (dates.length){
				// setting date by typing
				if (String(oldDates) !== String(this.dates))
					this._trigger('changeDate');
			}
			if (!this.dates.length && oldDates.length)
				this._trigger('clearDate');

			this.fill();
		},

		fillDow: function(){
			var dowCnt = this.o.weekStart,
				html = '<tr>';
			if (this.o.calendarWeeks){
				var cell = '<th class="cw">&nbsp;</th>';
				html += cell;
				this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
			}
			while (dowCnt < this.o.weekStart + 7){
				html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
			}
			html += '</tr>';
			this.picker.find('.datepicker-days thead').append(html);
		},

		fillMonths: function(){
			var html = '',
			i = 0;
			while (i < 12){
				html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';
			}
			this.picker.find('.datepicker-months td').html(html);
		},

		setRange: function(range){
			if (!range || !range.length)
				delete this.range;
			else
				this.range = $.map(range, function(d){
					return d.valueOf();
				});
			this.fill();
		},

		getClassNames: function(date){
			var cls = [],
				year = this.viewDate.getUTCFullYear(),
				month = this.viewDate.getUTCMonth(),
				today = new Date();
			if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)){
				cls.push('old');
			}
			else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)){
				cls.push('new');
			}
			if (this.focusDate && date.valueOf() === this.focusDate.valueOf())
				cls.push('focused');
			// Compare internal UTC date with local today, not UTC today
			if (this.o.todayHighlight &&
				date.getUTCFullYear() === today.getFullYear() &&
				date.getUTCMonth() === today.getMonth() &&
				date.getUTCDate() === today.getDate()){
				cls.push('today');
			}
			if (this.dates.contains(date) !== -1)
				cls.push('active');
			if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
				$.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1){
				cls.push('disabled');
			}
			if (this.range){
				if (date > this.range[0] && date < this.range[this.range.length-1]){
					cls.push('range');
				}
				if ($.inArray(date.valueOf(), this.range) !== -1){
					cls.push('selected');
				}
			}
			return cls;
		},

		fill: function(){
			var d = new Date(this.viewDate),
				year = d.getUTCFullYear(),
				month = d.getUTCMonth(),
				startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
				startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
				endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
				endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
				todaytxt = dates[this.o.language].today || dates['en'].today || '',
				cleartxt = dates[this.o.language].clear || dates['en'].clear || '',
				tooltip;
			this.picker.find('.datepicker-days thead th.datepicker-switch')
						.text(dates[this.o.language].months[month]+' '+year);
			this.picker.find('tfoot th.today')
						.text(todaytxt)
						.toggle(this.o.todayBtn !== false);
			this.picker.find('tfoot th.clear')
						.text(cleartxt)
						.toggle(this.o.clearBtn !== false);
			this.updateNavArrows();
			this.fillMonths();
			var prevMonth = UTCDate(year, month-1, 28),
				day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
			prevMonth.setUTCDate(day);
			prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
			var nextMonth = new Date(prevMonth);
			nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
			nextMonth = nextMonth.valueOf();
			var html = [];
			var clsName;
			while (prevMonth.valueOf() < nextMonth){
				if (prevMonth.getUTCDay() === this.o.weekStart){
					html.push('<tr>');
					if (this.o.calendarWeeks){
						// ISO 8601: First week contains first thursday.
						// ISO also states week starts on Monday, but we can be more abstract here.
						var
							// Start of current week: based on weekstart/current date
							ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
							// Thursday of this week
							th = new Date(Number(ws) + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
							// First Thursday of year, year from thursday
							yth = new Date(Number(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
							// Calendar week: ms between thursdays, div ms per day, div 7 days
							calWeek =  (th - yth) / 864e5 / 7 + 1;
						html.push('<td class="cw">'+ calWeek +'</td>');

					}
				}
				clsName = this.getClassNames(prevMonth);
				clsName.push('day');

				if (this.o.beforeShowDay !== $.noop){
					var before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
					if (before === undefined)
						before = {};
					else if (typeof(before) === 'boolean')
						before = {enabled: before};
					else if (typeof(before) === 'string')
						before = {classes: before};
					if (before.enabled === false)
						clsName.push('disabled');
					if (before.classes)
						clsName = clsName.concat(before.classes.split(/\s+/));
					if (before.tooltip)
						tooltip = before.tooltip;
				}

				clsName = $.unique(clsName);
				html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>');
				if (prevMonth.getUTCDay() === this.o.weekEnd){
					html.push('</tr>');
				}
				prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
			}
			this.picker.find('.datepicker-days tbody').empty().append(html.join(''));

			var months = this.picker.find('.datepicker-months')
						.find('th:eq(1)')
							.text(year)
							.end()
						.find('span').removeClass('active');

			$.each(this.dates, function(i, d){
				if (d.getUTCFullYear() === year)
					months.eq(d.getUTCMonth()).addClass('active');
			});

			if (year < startYear || year > endYear){
				months.addClass('disabled');
			}
			if (year === startYear){
				months.slice(0, startMonth).addClass('disabled');
			}
			if (year === endYear){
				months.slice(endMonth+1).addClass('disabled');
			}

			html = '';
			year = parseInt(year/10, 10) * 10;
			var yearCont = this.picker.find('.datepicker-years')
								.find('th:eq(1)')
									.text(year + '-' + (year + 9))
									.end()
								.find('td');
			year -= 1;
			var years = $.map(this.dates, function(d){
					return d.getUTCFullYear();
				}),
				classes;
			for (var i = -1; i < 11; i++){
				classes = ['year'];
				if (i === -1)
					classes.push('old');
				else if (i === 10)
					classes.push('new');
				if ($.inArray(year, years) !== -1)
					classes.push('active');
				if (year < startYear || year > endYear)
					classes.push('disabled');
				html += '<span class="' + classes.join(' ') + '">'+year+'</span>';
				year += 1;
			}
			yearCont.html(html);
		},

		updateNavArrows: function(){
			if (!this._allow_update)
				return;

			var d = new Date(this.viewDate),
				year = d.getUTCFullYear(),
				month = d.getUTCMonth();
			switch (this.viewMode){
				case 0:
					if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()){
						this.picker.find('.prev').css({visibility: 'hidden'});
					}
					else {
						this.picker.find('.prev').css({visibility: 'visible'});
					}
					if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()){
						this.picker.find('.next').css({visibility: 'hidden'});
					}
					else {
						this.picker.find('.next').css({visibility: 'visible'});
					}
					break;
				case 1:
				case 2:
					if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()){
						this.picker.find('.prev').css({visibility: 'hidden'});
					}
					else {
						this.picker.find('.prev').css({visibility: 'visible'});
					}
					if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()){
						this.picker.find('.next').css({visibility: 'hidden'});
					}
					else {
						this.picker.find('.next').css({visibility: 'visible'});
					}
					break;
			}
		},

		click: function(e){
			e.preventDefault();
			var target = $(e.target).closest('span, td, th'),
				year, month, day;
			if (target.length === 1){
				switch (target[0].nodeName.toLowerCase()){
					case 'th':
						switch (target[0].className){
							case 'datepicker-switch':
								this.showMode(1);
								break;
							case 'prev':
							case 'next':
								var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1);
								switch (this.viewMode){
									case 0:
										this.viewDate = this.moveMonth(this.viewDate, dir);
										this._trigger('changeMonth', this.viewDate);
										break;
									case 1:
									case 2:
										this.viewDate = this.moveYear(this.viewDate, dir);
										if (this.viewMode === 1)
											this._trigger('changeYear', this.viewDate);
										break;
								}
								this.fill();
								break;
							case 'today':
								var date = new Date();
								date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);

								this.showMode(-2);
								var which = this.o.todayBtn === 'linked' ? null : 'view';
								this._setDate(date, which);
								break;
							case 'clear':
								var element;
								if (this.isInput)
									element = this.element;
								else if (this.component)
									element = this.element.find('input');
								if (element)
									element.val("").change();
								this.update();
								this._trigger('changeDate');
								if (this.o.autoclose)
									this.hide();
								break;
						}
						break;
					case 'span':
						if (!target.is('.disabled')){
							this.viewDate.setUTCDate(1);
							if (target.is('.month')){
								day = 1;
								month = target.parent().find('span').index(target);
								year = this.viewDate.getUTCFullYear();
								this.viewDate.setUTCMonth(month);
								this._trigger('changeMonth', this.viewDate);
								if (this.o.minViewMode === 1){
									this._setDate(UTCDate(year, month, day));
								}
							}
							else {
								day = 1;
								month = 0;
								year = parseInt(target.text(), 10)||0;
								this.viewDate.setUTCFullYear(year);
								this._trigger('changeYear', this.viewDate);
								if (this.o.minViewMode === 2){
									this._setDate(UTCDate(year, month, day));
								}
							}
							this.showMode(-1);
							this.fill();
						}
						break;
					case 'td':
						if (target.is('.day') && !target.is('.disabled')){
							day = parseInt(target.text(), 10)||1;
							year = this.viewDate.getUTCFullYear();
							month = this.viewDate.getUTCMonth();
							if (target.is('.old')){
								if (month === 0){
									month = 11;
									year -= 1;
								}
								else {
									month -= 1;
								}
							}
							else if (target.is('.new')){
								if (month === 11){
									month = 0;
									year += 1;
								}
								else {
									month += 1;
								}
							}
							this._setDate(UTCDate(year, month, day));
						}
						break;
				}
			}
			if (this.picker.is(':visible') && this._focused_from){
				$(this._focused_from).focus();
			}
			delete this._focused_from;
		},

		_toggle_multidate: function(date){
			var ix = this.dates.contains(date);
			if (!date){
				this.dates.clear();
			}
			else if (ix !== -1){
				this.dates.remove(ix);
			}
			else {
				this.dates.push(date);
			}
			if (typeof this.o.multidate === 'number')
				while (this.dates.length > this.o.multidate)
					this.dates.remove(0);
		},

		_setDate: function(date, which){
			if (!which || which === 'date')
				this._toggle_multidate(date && new Date(date));
			if (!which || which  === 'view')
				this.viewDate = date && new Date(date);

			this.fill();
			this.setValue();
			this._trigger('changeDate');
			var element;
			if (this.isInput){
				element = this.element;
			}
			else if (this.component){
				element = this.element.find('input');
			}
			if (element){
				element.change();
			}
			if (this.o.autoclose && (!which || which === 'date')){
				this.hide();
			}
		},

		moveMonth: function(date, dir){
			if (!date)
				return undefined;
			if (!dir)
				return date;
			var new_date = new Date(date.valueOf()),
				day = new_date.getUTCDate(),
				month = new_date.getUTCMonth(),
				mag = Math.abs(dir),
				new_month, test;
			dir = dir > 0 ? 1 : -1;
			if (mag === 1){
				test = dir === -1
					// If going back one month, make sure month is not current month
					// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
					? function(){
						return new_date.getUTCMonth() === month;
					}
					// If going forward one month, make sure month is as expected
					// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
					: function(){
						return new_date.getUTCMonth() !== new_month;
					};
				new_month = month + dir;
				new_date.setUTCMonth(new_month);
				// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
				if (new_month < 0 || new_month > 11)
					new_month = (new_month + 12) % 12;
			}
			else {
				// For magnitudes >1, move one month at a time...
				for (var i=0; i < mag; i++)
					// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
					new_date = this.moveMonth(new_date, dir);
				// ...then reset the day, keeping it in the new month
				new_month = new_date.getUTCMonth();
				new_date.setUTCDate(day);
				test = function(){
					return new_month !== new_date.getUTCMonth();
				};
			}
			// Common date-resetting loop -- if date is beyond end of month, make it
			// end of month
			while (test()){
				new_date.setUTCDate(--day);
				new_date.setUTCMonth(new_month);
			}
			return new_date;
		},

		moveYear: function(date, dir){
			return this.moveMonth(date, dir*12);
		},

		dateWithinRange: function(date){
			return date >= this.o.startDate && date <= this.o.endDate;
		},

		keydown: function(e){
			if (this.picker.is(':not(:visible)')){
				if (e.keyCode === 27) // allow escape to hide and re-show picker
					this.show();
				return;
			}
			var dateChanged = false,
				dir, newDate, newViewDate,
				focusDate = this.focusDate || this.viewDate;
			switch (e.keyCode){
				case 27: // escape
					if (this.focusDate){
						this.focusDate = null;
						this.viewDate = this.dates.get(-1) || this.viewDate;
						this.fill();
					}
					else
						this.hide();
					e.preventDefault();
					break;
				case 37: // left
				case 39: // right
					if (!this.o.keyboardNavigation)
						break;
					dir = e.keyCode === 37 ? -1 : 1;
					if (e.ctrlKey){
						newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
						newViewDate = this.moveYear(focusDate, dir);
						this._trigger('changeYear', this.viewDate);
					}
					else if (e.shiftKey){
						newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
						newViewDate = this.moveMonth(focusDate, dir);
						this._trigger('changeMonth', this.viewDate);
					}
					else {
						newDate = new Date(this.dates.get(-1) || UTCToday());
						newDate.setUTCDate(newDate.getUTCDate() + dir);
						newViewDate = new Date(focusDate);
						newViewDate.setUTCDate(focusDate.getUTCDate() + dir);
					}
					if (this.dateWithinRange(newDate)){
						this.focusDate = this.viewDate = newViewDate;
						this.setValue();
						this.fill();
						e.preventDefault();
					}
					break;
				case 38: // up
				case 40: // down
					if (!this.o.keyboardNavigation)
						break;
					dir = e.keyCode === 38 ? -1 : 1;
					if (e.ctrlKey){
						newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
						newViewDate = this.moveYear(focusDate, dir);
						this._trigger('changeYear', this.viewDate);
					}
					else if (e.shiftKey){
						newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
						newViewDate = this.moveMonth(focusDate, dir);
						this._trigger('changeMonth', this.viewDate);
					}
					else {
						newDate = new Date(this.dates.get(-1) || UTCToday());
						newDate.setUTCDate(newDate.getUTCDate() + dir * 7);
						newViewDate = new Date(focusDate);
						newViewDate.setUTCDate(focusDate.getUTCDate() + dir * 7);
					}
					if (this.dateWithinRange(newDate)){
						this.focusDate = this.viewDate = newViewDate;
						this.setValue();
						this.fill();
						e.preventDefault();
					}
					break;
				case 32: // spacebar
					// Spacebar is used in manually typing dates in some formats.
					// As such, its behavior should not be hijacked.
					break;
				case 13: // enter
					focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
					this._toggle_multidate(focusDate);
					dateChanged = true;
					this.focusDate = null;
					this.viewDate = this.dates.get(-1) || this.viewDate;
					this.setValue();
					this.fill();
					if (this.picker.is(':visible')){
						e.preventDefault();
						if (this.o.autoclose)
							this.hide();
					}
					break;
				case 9: // tab
					this.focusDate = null;
					this.viewDate = this.dates.get(-1) || this.viewDate;
					this.fill();
					this.hide();
					break;
			}
			if (dateChanged){
				if (this.dates.length)
					this._trigger('changeDate');
				else
					this._trigger('clearDate');
				var element;
				if (this.isInput){
					element = this.element;
				}
				else if (this.component){
					element = this.element.find('input');
				}
				if (element){
					element.change();
				}
			}
		},

		showMode: function(dir){
			if (dir){
				this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
			}
			this.picker
				.find('>div')
				.hide()
				.filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName)
					.css('display', 'block');
			this.updateNavArrows();
		}
	};

	var DateRangePicker = function(element, options){
		this.element = $(element);
		this.inputs = $.map(options.inputs, function(i){
			return i.jquery ? i[0] : i;
		});
		delete options.inputs;

		$(this.inputs)
			.datepicker(options)
			.bind('changeDate', $.proxy(this.dateUpdated, this));

		this.pickers = $.map(this.inputs, function(i){
			return $(i).data('datepicker');
		});
		this.updateDates();
	};
	DateRangePicker.prototype = {
		updateDates: function(){
			this.dates = $.map(this.pickers, function(i){
				return i.getUTCDate();
			});
			this.updateRanges();
		},
		updateRanges: function(){
			var range = $.map(this.dates, function(d){
				return d.valueOf();
			});
			$.each(this.pickers, function(i, p){
				p.setRange(range);
			});
		},
		dateUpdated: function(e){
			// `this.updating` is a workaround for preventing infinite recursion
			// between `changeDate` triggering and `setUTCDate` calling.  Until
			// there is a better mechanism.
			if (this.updating)
				return;
			this.updating = true;

			var dp = $(e.target).data('datepicker'),
				new_date = dp.getUTCDate(),
				i = $.inArray(e.target, this.inputs),
				l = this.inputs.length;
			if (i === -1)
				return;

			$.each(this.pickers, function(i, p){
				if (!p.getUTCDate())
					p.setUTCDate(new_date);
			});

			if (new_date < this.dates[i]){
				// Date being moved earlier/left
				while (i >= 0 && new_date < this.dates[i]){
					this.pickers[i--].setUTCDate(new_date);
				}
			}
			else if (new_date > this.dates[i]){
				// Date being moved later/right
				while (i < l && new_date > this.dates[i]){
					this.pickers[i++].setUTCDate(new_date);
				}
			}
			this.updateDates();

			delete this.updating;
		},
		remove: function(){
			$.map(this.pickers, function(p){ p.remove(); });
			delete this.element.data().datepicker;
		}
	};

	function opts_from_el(el, prefix){
		// Derive options from element data-attrs
		var data = $(el).data(),
			out = {}, inkey,
			replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
		prefix = new RegExp('^' + prefix.toLowerCase());
		function re_lower(_,a){
			return a.toLowerCase();
		}
		for (var key in data)
			if (prefix.test(key)){
				inkey = key.replace(replace, re_lower);
				out[inkey] = data[key];
			}
		return out;
	}

	function opts_from_locale(lang){
		// Derive options from locale plugins
		var out = {};
		// Check if "de-DE" style date is available, if not language should
		// fallback to 2 letter code eg "de"
		if (!dates[lang]){
			lang = lang.split('-')[0];
			if (!dates[lang])
				return;
		}
		var d = dates[lang];
		$.each(locale_opts, function(i,k){
			if (k in d)
				out[k] = d[k];
		});
		return out;
	}

	var old = $.fn.datepicker;
	$.fn.datepicker = function(option){
		var args = Array.apply(null, arguments);
		args.shift();
		var internal_return;
		this.each(function(){
			var $this = $(this),
				data = $this.data('datepicker'),
				options = typeof option === 'object' && option;
			if (!data){
				var elopts = opts_from_el(this, 'date'),
					// Preliminary otions
					xopts = $.extend({}, defaults, elopts, options),
					locopts = opts_from_locale(xopts.language),
					// Options priority: js args, data-attrs, locales, defaults
					opts = $.extend({}, defaults, locopts, elopts, options);
				if ($this.is('.input-daterange') || opts.inputs){
					var ropts = {
						inputs: opts.inputs || $this.find('input').toArray()
					};
					$this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
				}
				else {
					$this.data('datepicker', (data = new Datepicker(this, opts)));
				}
			}
			if (typeof option === 'string' && typeof data[option] === 'function'){
				internal_return = data[option].apply(data, args);
				if (internal_return !== undefined)
					return false;
			}
		});
		if (internal_return !== undefined)
			return internal_return;
		else
			return this;
	};

	var defaults = $.fn.datepicker.defaults = {
		autoclose: false,
		beforeShowDay: $.noop,
		calendarWeeks: false,
		clearBtn: false,
		daysOfWeekDisabled: [],
		endDate: Infinity,
		forceParse: true,
		format: 'mm/dd/yyyy',
		keyboardNavigation: true,
		language: 'en',
		minViewMode: 0,
		multidate: false,
		multidateSeparator: ',',
		orientation: "auto",
		rtl: false,
		startDate: -Infinity,
		startView: 0,
		todayBtn: false,
		todayHighlight: false,
		weekStart: 0
	};
	var locale_opts = $.fn.datepicker.locale_opts = [
		'format',
		'rtl',
		'weekStart'
	];
	$.fn.datepicker.Constructor = Datepicker;
	var dates = $.fn.datepicker.dates = {
		en: {
			days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
			daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
			daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
			months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
			monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
			today: "Today",
			clear: "Clear"
		}
	};

	var DPGlobal = {
		modes: [
			{
				clsName: 'days',
				navFnc: 'Month',
				navStep: 1
			},
			{
				clsName: 'months',
				navFnc: 'FullYear',
				navStep: 1
			},
			{
				clsName: 'years',
				navFnc: 'FullYear',
				navStep: 10
		}],
		isLeapYear: function(year){
			return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
		},
		getDaysInMonth: function(year, month){
			return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
		},
		validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
		nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
		parseFormat: function(format){
			// IE treats \0 as a string end in inputs (truncating the value),
			// so it's a bad format delimiter, anyway
			var separators = format.replace(this.validParts, '\0').split('\0'),
				parts = format.match(this.validParts);
			if (!separators || !separators.length || !parts || parts.length === 0){
				throw new Error("Invalid date format.");
			}
			return {separators: separators, parts: parts};
		},
		parseDate: function(date, format, language){
			if (!date)
				return undefined;
			if (date instanceof Date)
				return date;
			if (typeof format === 'string')
				format = DPGlobal.parseFormat(format);
			var part_re = /([\-+]\d+)([dmwy])/,
				parts = date.match(/([\-+]\d+)([dmwy])/g),
				part, dir, i;
			if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)){
				date = new Date();
				for (i=0; i < parts.length; i++){
					part = part_re.exec(parts[i]);
					dir = parseInt(part[1]);
					switch (part[2]){
						case 'd':
							date.setUTCDate(date.getUTCDate() + dir);
							break;
						case 'm':
							date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
							break;
						case 'w':
							date.setUTCDate(date.getUTCDate() + dir * 7);
							break;
						case 'y':
							date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
							break;
					}
				}
				return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
			}
			parts = date && date.match(this.nonpunctuation) || [];
			date = new Date();
			var parsed = {},
				setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
				setters_map = {
					yyyy: function(d,v){
						return d.setUTCFullYear(v);
					},
					yy: function(d,v){
						return d.setUTCFullYear(2000+v);
					},
					m: function(d,v){
						if (isNaN(d))
							return d;
						v -= 1;
						while (v < 0) v += 12;
						v %= 12;
						d.setUTCMonth(v);
						while (d.getUTCMonth() !== v)
							d.setUTCDate(d.getUTCDate()-1);
						return d;
					},
					d: function(d,v){
						return d.setUTCDate(v);
					}
				},
				val, filtered;
			setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
			setters_map['dd'] = setters_map['d'];
			date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
			var fparts = format.parts.slice();
			// Remove noop parts
			if (parts.length !== fparts.length){
				fparts = $(fparts).filter(function(i,p){
					return $.inArray(p, setters_order) !== -1;
				}).toArray();
			}
			// Process remainder
			function match_part(){
				var m = this.slice(0, parts[i].length),
					p = parts[i].slice(0, m.length);
				return m === p;
			}
			if (parts.length === fparts.length){
				var cnt;
				for (i=0, cnt = fparts.length; i < cnt; i++){
					val = parseInt(parts[i], 10);
					part = fparts[i];
					if (isNaN(val)){
						switch (part){
							case 'MM':
								filtered = $(dates[language].months).filter(match_part);
								val = $.inArray(filtered[0], dates[language].months) + 1;
								break;
							case 'M':
								filtered = $(dates[language].monthsShort).filter(match_part);
								val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
								break;
						}
					}
					parsed[part] = val;
				}
				var _date, s;
				for (i=0; i < setters_order.length; i++){
					s = setters_order[i];
					if (s in parsed && !isNaN(parsed[s])){
						_date = new Date(date);
						setters_map[s](_date, parsed[s]);
						if (!isNaN(_date))
							date = _date;
					}
				}
			}
			return date;
		},
		formatDate: function(date, format, language){
			if (!date)
				return '';
			if (typeof format === 'string')
				format = DPGlobal.parseFormat(format);
			var val = {
				d: date.getUTCDate(),
				D: dates[language].daysShort[date.getUTCDay()],
				DD: dates[language].days[date.getUTCDay()],
				m: date.getUTCMonth() + 1,
				M: dates[language].monthsShort[date.getUTCMonth()],
				MM: dates[language].months[date.getUTCMonth()],
				yy: date.getUTCFullYear().toString().substring(2),
				yyyy: date.getUTCFullYear()
			};
			val.dd = (val.d < 10 ? '0' : '') + val.d;
			val.mm = (val.m < 10 ? '0' : '') + val.m;
			date = [];
			var seps = $.extend([], format.separators);
			for (var i=0, cnt = format.parts.length; i <= cnt; i++){
				if (seps.length)
					date.push(seps.shift());
				date.push(val[format.parts[i]]);
			}
			return date.join('');
		},
		headTemplate: '<thead>'+
							'<tr>'+
								'<th class="prev">&laquo;</th>'+
								'<th colspan="5" class="datepicker-switch"></th>'+
								'<th class="next">&raquo;</th>'+
							'</tr>'+
						'</thead>',
		contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
		footTemplate: '<tfoot>'+
							'<tr>'+
								'<th colspan="7" class="today"></th>'+
							'</tr>'+
							'<tr>'+
								'<th colspan="7" class="clear"></th>'+
							'</tr>'+
						'</tfoot>'
	};
	DPGlobal.template = '<div class="datepicker">'+
							'<div class="datepicker-days">'+
								'<table class=" table-condensed">'+
									DPGlobal.headTemplate+
									'<tbody></tbody>'+
									DPGlobal.footTemplate+
								'</table>'+
							'</div>'+
							'<div class="datepicker-months">'+
								'<table class="table-condensed">'+
									DPGlobal.headTemplate+
									DPGlobal.contTemplate+
									DPGlobal.footTemplate+
								'</table>'+
							'</div>'+
							'<div class="datepicker-years">'+
								'<table class="table-condensed">'+
									DPGlobal.headTemplate+
									DPGlobal.contTemplate+
									DPGlobal.footTemplate+
								'</table>'+
							'</div>'+
						'</div>';

	$.fn.datepicker.DPGlobal = DPGlobal;


	/* DATEPICKER NO CONFLICT
	* =================== */

	$.fn.datepicker.noConflict = function(){
		$.fn.datepicker = old;
		return this;
	};


	/* DATEPICKER DATA-API
	* ================== */

	$(document).on(
		'focus.datepicker.data-api click.datepicker.data-api',
		'[data-provide="datepicker"]',
		function(e){
			var $this = $(this);
			if ($this.data('datepicker'))
				return;
			e.preventDefault();
			// component click requires us to explicitly show it
			$this.datepicker('show');
		}
	);
	$(function(){
		$('[data-provide="datepicker-inline"]').datepicker();
	});

}(window.jQuery));

$(document).ready(function () {
  const formSelector = ".router-filter form";
  $(formSelector).on("change", "input", function()
  {
    UpdateQueryParams();
  });
  $(formSelector).on("change", "select", function()
  {
    UpdateQueryParams();
  });

  $(formSelector + " input[value='Reset']").on("click", function()
  {
    window.location = window.location.origin + window.location.pathname;
  });

  // Check URL for filter form variables
  let searchParams = new URLSearchParams(window.location.search)
  const targetFields = ["FilterTags","DateFilterFrom","DateFilterTo","YearList"];

  if (searchParams.has("FilterTags"))
  {
    let fieldValue = searchParams.get("FilterTags")
    if (fieldValue != "")
    {
      let filterTagIds = fieldValue.split(",");
      filterTagIds.forEach(function (item, index) {
        $(formSelector + " input[name='FilterTags'][value='" + item + "']").prop("checked", true)
      });
    }
  }

  if (searchParams.has("DateFilterFrom"))
  {
    let fieldValue = searchParams.get("DateFilterFrom")
    if (fieldValue != "")
    {
      $(formSelector + " input[name='DateFilterFrom']").val(fieldValue)
    }
  }

  if (searchParams.has("DateFilterTo"))
  {
    let fieldValue = searchParams.get("DateFilterTo")
    if (fieldValue != "")
    {
      $(formSelector + " input[name='DateFilterTo']").val(fieldValue)
    }
  }

  if (searchParams.has("YearList"))
  {
    let fieldValue = searchParams.get("YearList")
    if (fieldValue != "" & fieldValue != "0")
    {
      $(formSelector + " select[name='YearList'] option[value='" + fieldValue + "']").prop('selected','selected');
    }
  }
});

function UpdateQueryParams()
{
  const targetFields = ["FilterTags","DateFilterFrom","DateFilterTo","YearList"];
  let data = {};
  const formData = new FormData( document.querySelector(".router-filter form") );
  const url = new URL(window.location);
  const params = new URLSearchParams(url.search);
  for (const fieldName of targetFields){
    const fieldValue = formData.getAll(fieldName);
    if (fieldValue != "" & fieldValue != 0 )
    {
      params.set(fieldName, fieldValue);
    }
  };
  history.pushState("", "","?" + params.toString());
};

$(function() {
	const isNumericInput = (event) => {
		const key = event.keyCode;
		return ((key >= 48 && key <= 57) || // Allow number line
			(key >= 96 && key <= 105) // Allow number pad
		);
	};

	const isModifierKey = (event) => {
		const key = event.keyCode;
		return (event.shiftKey === true || key === 35 || key === 36) || // Allow Shift, Home, End
			(key === 8 || key === 9 || key === 13 || key === 46) || // Allow Backspace, Tab, Enter, Delete
			(key > 36 && key < 41) || // Allow left, up, right, down
			(
				// Allow Ctrl/Command + A,C,V,X,Z
				(event.ctrlKey === true || event.metaKey === true) &&
				(key === 65 || key === 67 || key === 86 || key === 88 || key === 90)
			)
	};

	const enforceFormat = (event) => {
		// Input must be of a valid number format or a modifier key, and not longer than ten digits
		if(!isNumericInput(event) && !isModifierKey(event)){
			event.preventDefault();
		}
	};

	const formatToPhone = (event) => {
		if(isModifierKey(event)) {return;}

		const target = event.target;
		const input = event.target.value.replace(/\D/g,'').substring(0,10); // First ten digits of input only
		const areaCode = input.substring(0,3);
		const middle = input.substring(3,6);
		const last = input.substring(6,10);

		if(input.length > 6){target.value = `${areaCode}-${middle}-${last}`;}
		else if(input.length > 3){target.value = `${areaCode}-${middle}`;}
		else if(input.length > 0){target.value = `${areaCode}`;}
	};

	let inputElements = document.querySelectorAll('.phone-number-formatting');

	inputElements.forEach((item) => {
		item.addEventListener('keydown',enforceFormat);
		item.addEventListener('keyup',formatToPhone);
	});
});
 