| Current Path : /proc/thread-self/cwd/static/frontend/Magento/indaco/it_IT/js/bundle/ |
| Current File : //proc/thread-self/cwd/static/frontend/Magento/indaco/it_IT/js/bundle/bundle2.js |
require.config({"config": {
"jsbuild":{"chartjs/Chart.min.js":"/*!\n * Chart.js v4.4.0\n * https://www.chartjs.org\n * (c) 2023 Chart.js Contributors\n * Released under the MIT License\n */\n!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){\"use strict\";var t=Object.freeze({__proto__:null,get Colors(){return Go},get Decimation(){return Qo},get Filler(){return ma},get Legend(){return ya},get SubTitle(){return ka},get Title(){return Ma},get Tooltip(){return Ba}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return\"[object\"===e.slice(0,7)&&\"Array]\"===e.slice(-6)}function o(t){return null!==t&&\"[object Object]\"===Object.prototype.toString.call(t)}function a(t){return(\"number\"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>\"string\"==typeof t&&t.endsWith(\"%\")?parseFloat(t)/100:+t/e,c=(t,e)=>\"string\"==typeof t&&t.endsWith(\"%\")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&\"function\"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;a<r;a++)e.call(i,t[a],a);else if(o(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function f(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function g(t){if(n(t))return t.map(g);if(o(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=g(t[i[n]]);return e}return t}function p(t){return-1===[\"__proto__\",\"prototype\",\"constructor\"].indexOf(t)}function m(t,e,i,s){if(!p(t))return;const n=e[t],a=i[t];o(n)&&o(a)?b(n,a,s):e[t]=g(a)}function b(t,e,i){const s=n(e)?e:[e],a=s.length;if(!o(t))return t;const r=(i=i||{}).merger||m;let l;for(let e=0;e<a;++e){if(l=s[e],!o(l))continue;const n=Object.keys(l);for(let e=0,s=n.length;e<s;++e)r(n[e],t,l,i)}return t}function x(t,e){return b(t,e,{merger:_})}function _(t,e,i){if(!p(t))return;const s=e[t],n=i[t];o(s)&&o(n)?x(s,n):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=g(n))}const y={\"\":t=>t,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split(\".\"),i=[];let s=\"\";for(const t of e)s+=t,s.endsWith(\"\\\\\")?s=s.slice(0,-1)+\".\":(i.push(s),s=\"\");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(\"\"===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>\"function\"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return\"mouseup\"===t.type||\"click\"===t.type||\"contextmenu\"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)<i}function B(t){const e=Math.round(t);t=V(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(z(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function W(t){const e=[],i=Math.sqrt(t);let s;for(s=1;s<i;s++)t%s==0&&(e.push(s),e.push(t/s));return i===(0|i)&&e.push(i),e.sort(((t,e)=>t-e)).pop(),e}function N(t){return!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function $(t){return t*(C/180)}function Y(t){return t*(180/C)}function U(t){if(!a(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function X(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*C&&(o+=O),{angle:o,distance:n}}function q(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function K(t,e){return(t-e+A)%O-C}function G(t){return(t%O+O)%O}function Z(t,e,i,s){const n=G(t),o=G(e),a=G(i),r=G(o-n),l=G(a-n),h=G(n-o),c=G(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function J(t,e,i){return Math.max(e,Math.min(i,t))}function Q(t){return J(t,-32768,32767)}function tt(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),st=(t,e,i)=>et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;s<n&&t[s]<e;)s++;for(;n>s&&t[n-1]>i;)n--;return s>0||n<t.length?t.slice(s,n):t}const ot=[\"push\",\"pop\",\"shift\",\"splice\",\"unshift\"];function at(t,e){t._chartjs?t._chartjs.listeners.push(e):(Object.defineProperty(t,\"_chartjs\",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),ot.forEach((e=>{const i=\"_onData\"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{\"function\"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht=\"undefined\"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>\"start\"===t?\"left\":\"end\"===t?\"right\":\"center\",ft=(t,e,i)=>\"start\"===t?e:\"end\"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?\"left\":\"right\")?i:\"center\"===t?(e+i)/2:e;function pt(t,e,i){const s=e.length;let n=0,o=s;if(t._sorted){const{iScale:a,_parsed:r}=t,l=a.axis,{min:h,max:c,minDefined:d,maxDefined:u}=a.getUserBounds();d&&(n=J(Math.min(it(r,l,h).lo,i?s:it(e,l,a.getPixelForValue(h)).lo),0,s-1)),o=u?J(Math.max(it(r,a.axis,c,!0).hi+1,i?0:it(e,l,a.getPixelForValue(c),!0).hi+1),n,s)-n:s-n}return{start:n,count:o}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class bt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,\"progress\")),n.length||(i.running=!1,this._notify(s,i,t,\"complete\"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),\"complete\")}remove(t){return this._charts.delete(t)}}var xt=new bt;\n /*!\n * @kurkle/color v0.3.2\n * https://github.com/kurkle/color#readme\n * (c) 2023 Jukka Kurkela\n * Released under the MIT License\n */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[...\"0123456789ABCDEF\"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?\"#\"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):\"\")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\\(\\s*([-+.e\\d]+)(?:deg)?[\\s,]+([-+.e\\d]+)%[\\s,]+([-+.e\\d]+)%(?:[\\s,]+([-+.e\\d]+)(%)?)?\\s*\\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function zt(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(Mt)}function Ft(t,e,i){return zt(Lt,t,e,i)}function Vt(t){return(t%360+360)%360}function Bt(t){const e=Tt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?vt(+e[5]):Mt(+e[5]));const n=Vt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i=\"hwb\"===e[1]?function(t,e,i){return zt(Rt,t,e,i)}(n,o,a):\"hsv\"===e[1]?function(t,e,i){return zt(Et,t,e,i)}(n,o,a):Ft(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Wt={x:\"dark\",Z:\"light\",Y:\"re\",X:\"blu\",W:\"gr\",V:\"medium\",U:\"slate\",A:\"ee\",T:\"ol\",S:\"or\",B:\"ra\",C:\"lateg\",D:\"ights\",R:\"in\",Q:\"turquois\",E:\"hi\",P:\"ro\",O:\"al\",N:\"le\",M:\"de\",L:\"yello\",F:\"en\",K:\"ch\",G:\"arks\",H:\"ea\",I:\"ightg\",J:\"wh\"},Nt={OiceXe:\"f0f8ff\",antiquewEte:\"faebd7\",aqua:\"ffff\",aquamarRe:\"7fffd4\",azuY:\"f0ffff\",beige:\"f5f5dc\",bisque:\"ffe4c4\",black:\"0\",blanKedOmond:\"ffebcd\",Xe:\"ff\",XeviTet:\"8a2be2\",bPwn:\"a52a2a\",burlywood:\"deb887\",caMtXe:\"5f9ea0\",KartYuse:\"7fff00\",KocTate:\"d2691e\",cSO:\"ff7f50\",cSnflowerXe:\"6495ed\",cSnsilk:\"fff8dc\",crimson:\"dc143c\",cyan:\"ffff\",xXe:\"8b\",xcyan:\"8b8b\",xgTMnPd:\"b8860b\",xWay:\"a9a9a9\",xgYF:\"6400\",xgYy:\"a9a9a9\",xkhaki:\"bdb76b\",xmagFta:\"8b008b\",xTivegYF:\"556b2f\",xSange:\"ff8c00\",xScEd:\"9932cc\",xYd:\"8b0000\",xsOmon:\"e9967a\",xsHgYF:\"8fbc8f\",xUXe:\"483d8b\",xUWay:\"2f4f4f\",xUgYy:\"2f4f4f\",xQe:\"ced1\",xviTet:\"9400d3\",dAppRk:\"ff1493\",dApskyXe:\"bfff\",dimWay:\"696969\",dimgYy:\"696969\",dodgerXe:\"1e90ff\",fiYbrick:\"b22222\",flSOwEte:\"fffaf0\",foYstWAn:\"228b22\",fuKsia:\"ff00ff\",gaRsbSo:\"dcdcdc\",ghostwEte:\"f8f8ff\",gTd:\"ffd700\",gTMnPd:\"daa520\",Way:\"808080\",gYF:\"8000\",gYFLw:\"adff2f\",gYy:\"808080\",honeyMw:\"f0fff0\",hotpRk:\"ff69b4\",RdianYd:\"cd5c5c\",Rdigo:\"4b0082\",ivSy:\"fffff0\",khaki:\"f0e68c\",lavFMr:\"e6e6fa\",lavFMrXsh:\"fff0f5\",lawngYF:\"7cfc00\",NmoncEffon:\"fffacd\",ZXe:\"add8e6\",ZcSO:\"f08080\",Zcyan:\"e0ffff\",ZgTMnPdLw:\"fafad2\",ZWay:\"d3d3d3\",ZgYF:\"90ee90\",ZgYy:\"d3d3d3\",ZpRk:\"ffb6c1\",ZsOmon:\"ffa07a\",ZsHgYF:\"20b2aa\",ZskyXe:\"87cefa\",ZUWay:\"778899\",ZUgYy:\"778899\",ZstAlXe:\"b0c4de\",ZLw:\"ffffe0\",lime:\"ff00\",limegYF:\"32cd32\",lRF:\"faf0e6\",magFta:\"ff00ff\",maPon:\"800000\",VaquamarRe:\"66cdaa\",VXe:\"cd\",VScEd:\"ba55d3\",VpurpN:\"9370db\",VsHgYF:\"3cb371\",VUXe:\"7b68ee\",VsprRggYF:\"fa9a\",VQe:\"48d1cc\",VviTetYd:\"c71585\",midnightXe:\"191970\",mRtcYam:\"f5fffa\",mistyPse:\"ffe4e1\",moccasR:\"ffe4b5\",navajowEte:\"ffdead\",navy:\"80\",Tdlace:\"fdf5e6\",Tive:\"808000\",TivedBb:\"6b8e23\",Sange:\"ffa500\",SangeYd:\"ff4500\",ScEd:\"da70d6\",pOegTMnPd:\"eee8aa\",pOegYF:\"98fb98\",pOeQe:\"afeeee\",pOeviTetYd:\"db7093\",papayawEp:\"ffefd5\",pHKpuff:\"ffdab9\",peru:\"cd853f\",pRk:\"ffc0cb\",plum:\"dda0dd\",powMrXe:\"b0e0e6\",purpN:\"800080\",YbeccapurpN:\"663399\",Yd:\"ff0000\",Psybrown:\"bc8f8f\",PyOXe:\"4169e1\",saddNbPwn:\"8b4513\",sOmon:\"fa8072\",sandybPwn:\"f4a460\",sHgYF:\"2e8b57\",sHshell:\"fff5ee\",siFna:\"a0522d\",silver:\"c0c0c0\",skyXe:\"87ceeb\",UXe:\"6a5acd\",UWay:\"708090\",UgYy:\"708090\",snow:\"fffafa\",sprRggYF:\"ff7f\",stAlXe:\"4682b4\",tan:\"d2b48c\",teO:\"8080\",tEstN:\"d8bfd8\",tomato:\"ff6347\",Qe:\"40e0d0\",viTet:\"ee82ee\",JHt:\"f5deb3\",wEte:\"ffffff\",wEtesmoke:\"f5f5f5\",Lw:\"ffff00\",LwgYF:\"9acd32\"};let Ht;function jt(t){Ht||(Ht=function(){const t={},e=Object.keys(Nt),i=Object.keys(Wt);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Wt[o]);o=parseInt(Nt[a],16),t[r]=[o>>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\\(\\s*([-+.\\d]+)(%)?[\\s,]+([-+.e\\d]+)(%)?[\\s,]+([-+.e\\d]+)(%)?(?:[\\s,/]+([-+.e\\d]+)(%)?)?\\s*\\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return\"r\"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Zt{constructor(t){if(t instanceof Zt)return t;const e=typeof t;let i;var s,n,o;\"object\"===e?i=Kt(t):\"string\"===e&&(o=(s=t).length,\"#\"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Zt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Jt(t){if(t&&\"object\"==typeof t){const e=t.toString();return\"[object CanvasPattern]\"===e||\"[object CanvasGradient]\"===e}return!1}function Qt(t){return Jt(t)?t:new Zt(t)}function te(t){return Jt(t)?t:new Zt(t).saturate(.5).darken(.1).hexString()}const ee=[\"x\",\"y\",\"borderWidth\",\"radius\",\"tension\"],ie=[\"color\",\"borderColor\",\"backgroundColor\"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:\"\"+t,numeric(t,e,i){if(0===t)return\"0\";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n=\"scientific\"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return\"0\";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):\"\"}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(\".\");for(let e=0,s=i.length;e<s;++e){const s=i[e];t=t[s]||(t[s]=Object.create(null))}return t}function ce(t,e,i){return\"string\"==typeof e?b(he(t,e),i):b(he(t,\"\"),e)}class de{constructor(t,e){this.animation=void 0,this.backgroundColor=\"rgba(0,0,0,0.1)\",this.borderColor=\"rgba(0,0,0,0.1)\",this.color=\"#666\",this.datasets={},this.devicePixelRatio=t=>t.chart.platform.getDevicePixelRatio(),this.elements={},this.events=[\"mousemove\",\"mouseout\",\"click\",\"touchstart\",\"touchmove\"],this.font={family:\"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\",size:12,style:\"normal\",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis=\"x\",this.interaction={mode:\"nearest\",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r=\"_\"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith(\"on\"),_indexable:t=>\"events\"!==t,hover:{_fallback:\"interaction\"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set(\"animation\",{delay:void 0,duration:1e3,easing:\"easeOutQuart\",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe(\"animation\",{_fallback:!1,_indexable:!1,_scriptable:t=>\"onProgress\"!==t&&\"onComplete\"!==t&&\"fn\"!==t}),t.set(\"animations\",{colors:{type:\"color\",properties:ie},numbers:{type:\"number\",properties:ee}}),t.describe(\"animations\",{_fallback:\"animation\"}),t.set(\"transitions\",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:\"transparent\"},visible:{type:\"boolean\",duration:0}}},hide:{animations:{colors:{to:\"transparent\"},visible:{type:\"boolean\",easing:\"linear\",fn:t=>0|t}}}})},function(t){t.set(\"layout\",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set(\"scale\",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:\"ticks\",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:\"\",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:\"\",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:\"center\",crossAlign:\"near\",showLabelBackdrop:!1,backdropColor:\"rgba(255, 255, 255, 0.75)\",backdropPadding:2}}),t.route(\"scale.ticks\",\"color\",\"\",\"color\"),t.route(\"scale.grid\",\"color\",\"\",\"borderColor\"),t.route(\"scale.border\",\"color\",\"\",\"borderColor\"),t.route(\"scale.title\",\"color\",\"\",\"color\"),t.describe(\"scale\",{_fallback:!1,_scriptable:t=>!t.startsWith(\"before\")&&!t.startsWith(\"after\")&&\"callback\"!==t&&\"parser\"!==t,_indexable:t=>\"borderDash\"!==t&&\"tickBorderDash\"!==t&&\"dash\"!==t}),t.describe(\"scales\",{_fallback:\"scale\"}),t.describe(\"scale.ticks\",{_scriptable:t=>\"backdropPadding\"!==t&&\"callback\"!==t,_indexable:t=>\"backdropPadding\"!==t})}]);function fe(){return\"undefined\"!=typeof window&&\"undefined\"!=typeof document}function ge(t){let e=t.parentNode;return e&&\"[object ShadowRoot]\"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return\"string\"==typeof t?(s=parseInt(t,10),-1!==t.indexOf(\"%\")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function be(t,e){return me(t).getPropertyValue(e)}const xe=[\"top\",\"right\",\"bottom\",\"left\"];function _e(t,e,i){const s={};i=i?\"-\"+i:\"\";for(let n=0;n<4;n++){const o=xe[n];s[o]=parseFloat(t[e+\"-\"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if(\"native\"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o=\"border-box\"===n.boxSizing,a=_e(n,\"padding\"),r=_e(n,\"border\",\"width\"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,\"margin\"),a=pe(n.maxWidth,t,\"clientWidth\")||T,r=pe(n.maxHeight,t,\"clientHeight\")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,\"border\",\"width\"),l=_e(a,\"padding\");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,\"clientWidth\"),n=pe(a.maxHeight,o,\"clientHeight\")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if(\"content-box\"===n.boxSizing){const t=_e(n,\"border\",\"width\"),e=_e(n,\"padding\");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};window.addEventListener(\"test\",null,e),window.removeEventListener(\"test\",null,e)}catch(t){}return t}();function Pe(t,e){const i=be(t,e),s=i&&i.match(/^(\\d+)(\\.\\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+\" \":\"\")+(t.weight?t.weight+\" \":\"\")+t.size+\"px \"+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;h<l;h++)if(u=i[h],null==u||n(u)){if(n(u))for(c=0,d=u.length;c<d;c++)f=u[c],null==f||n(f)||(r=Ce(t,o,a,r,f))}else r=Ce(t,o,a,r,u);t.restore();const g=a.length/2;if(g>i.length){for(h=0;h<g;h++)delete o[a[h]];a.splice(0,g)}return r}function Ae(t,e,i){const s=t.currentDevicePixelRatio,n=0!==i?Math.max(i/2,.5):0;return Math.round((e-n)*s)/s+n}function Te(t,e){(e=e||t.getContext(\"2d\")).save(),e.resetTransform(),e.clearRect(0,0,t.width,t.height),e.restore()}function Le(t,e,i,s){Ee(t,e,i,s,null)}function Ee(t,e,i,s,n){let o,a,r,l,h,c,d,u;const f=e.pointStyle,g=e.rotation,p=e.radius;let m=(g||0)*L;if(f&&\"object\"==typeof f&&(o=f.toString(),\"[object HTMLImageElement]\"===o||\"[object HTMLCanvasElement]\"===o))return t.save(),t.translate(i,s),t.rotate(m),t.drawImage(f,-f.width/2,-f.height/2,f.width,f.height),void t.restore();if(!(isNaN(p)||p<=0)){switch(t.beginPath(),f){default:n?t.ellipse(i,s,n/2,p,0,0,O):t.arc(i,s,p,0,O),t.closePath();break;case\"triangle\":c=n?n/2:p,t.moveTo(i+Math.sin(m)*c,s-Math.cos(m)*p),m+=I,t.lineTo(i+Math.sin(m)*c,s-Math.cos(m)*p),m+=I,t.lineTo(i+Math.sin(m)*c,s-Math.cos(m)*p),t.closePath();break;case\"rectRounded\":h=.516*p,l=p-h,a=Math.cos(m+R)*l,d=Math.cos(m+R)*(n?n/2-h:l),r=Math.sin(m+R)*l,u=Math.sin(m+R)*(n?n/2-h:l),t.arc(i-d,s-r,h,m-C,m-E),t.arc(i+u,s-a,h,m-E,m),t.arc(i+d,s+r,h,m,m+E),t.arc(i-u,s+a,h,m+E,m+C),t.closePath();break;case\"rect\":if(!g){l=Math.SQRT1_2*p,c=n?n/2:l,t.rect(i-c,s-l,2*c,2*l);break}m+=R;case\"rectRot\":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+u,s-a),t.lineTo(i+d,s+r),t.lineTo(i-u,s+a),t.closePath();break;case\"crossRot\":m+=R;case\"cross\":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a);break;case\"star\":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a),m+=R,d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a);break;case\"line\":a=n?n/2:Math.cos(m)*p,r=Math.sin(m)*p,t.moveTo(i-a,s-r),t.lineTo(i+a,s+r);break;case\"dash\":t.moveTo(i,s),t.lineTo(i+Math.cos(m)*(n?n/2:p),s+Math.sin(m)*p);break;case!1:t.closePath()}t.fill(),e.borderWidth>0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.x<e.right+i&&t.y>e.top-i&&t.y<e.bottom+i}function Ie(t,e){t.save(),t.beginPath(),t.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),t.clip()}function ze(t){t.restore()}function Fe(t,e,i,s,n){if(!e)return t.lineTo(i.x,i.y);if(\"middle\"===n){const s=(e.x+i.x)/2;t.lineTo(s,e.y),t.lineTo(s,i.y)}else\"after\"===n!=!!s?t.lineTo(e.x,i.y):t.lineTo(i.x,e.y);t.lineTo(i.x,i.y)}function Ve(t,e,i,s){if(!e)return t.lineTo(i.x,i.y);t.bezierCurveTo(s?e.cp1x:e.cp2x,s?e.cp1y:e.cp2y,s?i.cp2x:i.cp1x,s?i.cp2y:i.cp1y,i.x,i.y)}function Be(t,e,i,s,n){if(n.strikethrough||n.underline){const o=t.measureText(s),a=e-o.actualBoundingBoxLeft,r=e+o.actualBoundingBoxRight,l=i-o.actualBoundingBoxAscent,h=i+o.actualBoundingBoxDescent,c=n.strikethrough?(l+h)/2:h;t.strokeStyle=t.fillStyle,t.beginPath(),t.lineWidth=n.decorationWidth||2,t.moveTo(a,c),t.lineTo(r,c),t.stroke()}}function We(t,e){const i=t.fillStyle;t.fillStyle=e.color,t.fillRect(e.left,e.top,e.width,e.height),t.fillStyle=i}function Ne(t,e,i,o,a,r={}){const l=n(e)?e:[e],h=r.strokeWidth>0&&\"\"!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;c<l.length;++c)d=l[c],r.backdrop&&We(t,r.backdrop),h&&(r.strokeColor&&(t.strokeStyle=r.strokeColor),s(r.strokeWidth)||(t.lineWidth=r.strokeWidth),t.strokeText(d,i,o,r.maxWidth)),t.fillText(d,i,o,r.maxWidth),Be(t,i,o,d,r),o+=Number(a.lineHeight);t.restore()}function He(t,e){const{x:i,y:s,w:n,h:o,radius:a}=e;t.arc(i+a.topLeft,s+a.topLeft,a.topLeft,1.5*C,C,!0),t.lineTo(i,s+o-a.bottomLeft),t.arc(i+a.bottomLeft,s+o-a.bottomLeft,a.bottomLeft,C,E,!0),t.lineTo(i+n-a.bottomRight,s+o),t.arc(i+n-a.bottomRight,s+o-a.bottomRight,a.bottomRight,E,0,!0),t.lineTo(i+n,s+a.topRight),t.arc(i+n-a.topRight,s+a.topRight,a.topRight,0,-E,!0),t.lineTo(i+a.topLeft,s)}function je(t,e=[\"\"],i,s,n=(()=>t[0])){const o=i||t;void 0===s&&(s=ti(\"_fallback\",t));const a={[Symbol.toStringTag]:\"Object\",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Je(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error(\"Recursion detected: \"+Array.from(r).join(\"->\")+\"->\"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Je(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Je(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&\"adapters\"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:\"string\"==typeof t?M(e,t):void 0;function Ze(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Je(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[\"\"],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Ze(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith(\"_\"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o=\"r\"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;r<l;++r)h=r+i,c=e[h],a[r]={r:n.parse(M(c,o),h)};return a}const si=Number.EPSILON||1e-14,ni=(t,e)=>e<t.length&&!t[e].skip&&t[e],oi=t=>\"x\"===t?\"y\":\"x\";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e=\"x\"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a<s;++a)if(r=l,l=h,h=ni(t,a+1),l){if(h){const t=h[e]-l[e];n[a]=0!==t?(h[i]-l[i])/t:0}o[a]=r?h?F(n[a-1])!==F(n[a])?0:(n[a-1]+n[a])/2:n[a-1]:n[a]}!function(t,e,i){const s=t.length;let n,o,a,r,l,h=ni(t,0);for(let c=0;c<s-1;++c)l=h,h=ni(t,c+1),l&&h&&(V(e[c],0,si)?i[c]=i[c+1]=0:(n=i[c]/e[c],o=i[c+1]/e[c],r=Math.pow(n,2)+Math.pow(o,2),r<=9||(a=3/Math.sqrt(r),i[c]=n*a*e[c],i[c+1]=o*a*e[c])))}(t,n,o),function(t,e,i=\"x\"){const s=oi(i),n=t.length;let o,a,r,l=ni(t,0);for(let h=0;h<n;++h){if(a=r,r=l,l=ni(t,h+1),!r)continue;const n=r[i],c=r[s];a&&(o=(n-a[i])/3,r[`cp1${i}`]=n-o,r[`cp1${s}`]=c-o*e[h]),l&&(o=(l[i]-n)/3,r[`cp2${i}`]=n+o,r[`cp2${s}`]=c+o*e[h])}}(t,o,e)}function li(t,e,i){return Math.max(Math.min(t,i),e)}function hi(t,e,i,s,n){let o,a,r,l;if(e.spanGaps&&(t=t.filter((t=>!t.skip))),\"monotone\"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o<a;++o)r=t[o],l=ai(i,r,t[Math.min(o+1,a-(s?0:1))%a],e.tension),r.cp1x=l.previous.x,r.cp1y=l.previous.y,r.cp2x=l.next.x,r.cp2y=l.next.y,i=r}e.capBezierPoints&&function(t,e){let i,s,n,o,a,r=Re(t[0],e);for(i=0,s=t.length;i<s;++i)a=o,o=r,r=i<s-1&&Re(t[i+1],e),o&&(n=t[i],a&&(n.cp1x=li(n.cp1x,e.left,e.right),n.cp1y=li(n.cp1y,e.top,e.bottom)),r&&(n.cp2x=li(n.cp2x,e.left,e.right),n.cp2y=li(n.cp2y,e.top,e.bottom)))}(t,i)}const ci=t=>0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:\"middle\"===s?i<.5?t.y:e.y:\"after\"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const bi=/^(normal|(\\d+(?:\\.\\d+)?)(px|em|%)?)$/,xi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(\"\"+t).match(bi);if(!i||\"normal\"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case\"px\":return t;case\"%\":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:\"y\",right:\"x\",bottom:\"y\",left:\"x\"})}function wi(t){return vi(t,[\"topLeft\",\"topRight\",\"bottomLeft\",\"bottomRight\"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);\"string\"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(\"\"+s).match(xi)&&(console.warn('Invalid font style specified: \"'+s+'\"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:\"\"};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;o<a;++o)if(r=t[o],void 0!==r&&(void 0!==e&&\"function\"==typeof r&&(r=r(e),l=!1),void 0!==i&&n(r)&&(r=r[i%r.length],l=!1),void 0!==r))return s&&!l&&(s.cacheable=!1),r}function Di(t,e,i){const{min:s,max:n}=t,o=c(e,(n-s)/2),a=(t,e)=>i&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>\"center\"===t?t:\"right\"===t?\"left\":\"right\",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;\"ltr\"!==e&&\"rtl\"!==e||(i=t.canvas.style,s=[i.getPropertyValue(\"direction\"),i.getPropertyPriority(\"direction\")],i.setProperty(\"direction\",e,\"important\"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty(\"direction\",e[0],e[1]))}function Li(t){return\"angle\"===t?{between:Z,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;h<c&&a(r(e[d%l][s]),n,o);++h)d--,u--;d%=l,u%=l}return u<d&&(u+=l),{start:d,end:u,loop:f,style:t.style}}(t,e,i),g=[];let p,m,b,x=!1,_=null;const y=()=>x||l(n,b,p)&&0!==r(n,b),v=()=>!x||0===r(o,p)||l(o,b,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==b&&(x=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,b=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;n<s.length;n++){const o=Ri(s[n],t.points,e);o.length&&i.push(...o)}return i}function zi(t,e){const i=t.points,s=t.options.spanGaps,n=i.length;if(!n)return[];const o=!!t._loop,{start:a,end:r}=function(t,e,i,s){let n=0,o=e-1;if(i&&!s)for(;n<e&&!t[n].skip;)n++;for(;n<e&&t[n].skip;)n++;for(n%=e,i&&(o+=n);o>n&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r<a?r+n:r,!!t._fullLoop&&0===a&&r===n-1),i,e)}function Fi(t,e,i,s){return s&&s.setContext&&i?function(t,e,i,s){const n=t._chart.getContext(),o=Vi(t.options),{_datasetIndex:a,options:{spanGaps:r}}=t,l=i.length,h=[];let c=o,d=e[0].start,u=d;function f(t,e,s,n){const o=r?-1:1;if(t!==e){for(t+=l;i[t%l].skip;)t-=o;for(;i[e%l].skip;)e+=o;t%l!=e%l&&(h.push({start:t%l,end:e%l,loop:s,style:n}),c=n,d=e%l)}}for(const t of e){d=r?d:t.start;let e,o=i[d%l];for(u=d+1;u<=t.end;u++){const r=i[u%l];e=Vi(s.setContext(Ci(n,{type:\"segment\",p0:o,p1:r,p0DataIndex:(u-1)%l,p1DataIndex:u%l,datasetIndex:a}))),Bi(e,c)&&f(d,u-1,t.loop,c),o=r,c=e}d<u-1&&f(d,u-1,t.loop,c)}return h}(t,e,i,s):e}function Vi(t){return{backgroundColor:t.backgroundColor,borderCapStyle:t.borderCapStyle,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderJoinStyle:t.borderJoinStyle,borderWidth:t.borderWidth,borderColor:t.borderColor}}function Bi(t,e){if(!e)return!1;const i=[],s=function(t,e){return Jt(e)?(i.includes(e)||i.push(e),i.indexOf(e)):e};return JSON.stringify(t,s)!==JSON.stringify(e,s)}var Wi=Object.freeze({__proto__:null,HALF_PI:E,INFINITY:T,PI:C,PITAU:A,QUARTER_PI:R,RAD_PER_DEG:L,TAU:O,TWO_THIRDS_PI:I,_addGrace:Di,_alignPixel:Ae,_alignStartEnd:ft,_angleBetween:Z,_angleDiff:K,_arrayUnique:lt,_attachContext:$e,_bezierCurveTo:Ve,_bezierInterpolation:mi,_boundSegment:Ri,_boundSegments:Ii,_capitalize:w,_computeSegments:zi,_createResolver:je,_decimalPlaces:U,_deprecated:function(t,e,i,s){void 0!==e&&console.warn(t+': \"'+i+'\" is deprecated. Please use \"'+s+'\" instead')},_descriptors:Ye,_elementsEqual:f,_factorize:W,_filterBetween:nt,_getParentNode:ge,_getStartAndCountOfVisiblePoints:pt,_int16Range:Q,_isBetween:tt,_isClickEvent:D,_isDomSupported:fe,_isPointInArea:Re,_limitValue:J,_longestText:Oe,_lookup:et,_lookupByKey:it,_measureText:Ce,_merger:m,_mergerIf:_,_normalizeAngle:G,_parseObjectDataRadialScale:ii,_pointInLine:gi,_readValueToProps:vi,_rlookupByKey:st,_scaleRangesChanged:mt,_setMinAndMaxByKey:j,_splitKey:v,_steppedInterpolation:pi,_steppedLineTo:Fe,_textX:gt,_toLeftRightCenter:ut,_updateBezierControlPoints:hi,addRoundedRectPath:He,almostEquals:V,almostWhole:H,callback:d,clearCanvas:Te,clipArea:Ie,clone:g,color:Qt,createContext:Ci,debounce:dt,defined:k,distanceBetweenPoints:q,drawPoint:Le,drawPointLegend:Ee,each:u,easingEffects:fi,finiteOrDefault:r,fontString:function(t,e,i){return e+\" \"+t+\"px \"+i},formatNumber:ne,getAngleFromPoint:X,getHoverColor:te,getMaximumSize:we,getRelativePosition:ve,getRtlAdapter:Oi,getStyle:be,isArray:n,isFinite:a,isFunction:S,isNullOrUndef:s,isNumber:N,isObject:o,isPatternOrGradient:Jt,listenArrayEvents:at,log10:z,merge:b,mergeIf:x,niceNum:B,noop:e,overrideTextDirection:Ai,readUsedSize:Pe,renderText:Ne,requestAnimFrame:ht,resolve:Pi,resolveObjectKey:M,restoreTextDirection:Ti,retinaScale:ke,setsEqual:P,sign:F,splineCurve:ai,splineCurveMonotone:ri,supportsEventListenerOptions:Se,throttled:ct,toDegrees:Y,toDimension:c,toFont:Si,toFontString:De,toLineHeight:_i,toPadding:ki,toPercentage:h,toRadians:$,toTRBL:Mi,toTRBLCorners:wi,uid:i,unclipArea:ze,unlistenArrayEvents:rt,valueOrDefault:l});function Ni(t,e,i,s){const{controller:n,data:o,_sorted:a}=t,r=n._cachedMeta.iScale;if(r&&e===r.axis&&\"r\"!==e&&a&&o.length){const t=r._reversePixels?st:it;if(!s)return t(o,e,i);if(n._sharedOptions){const s=o[0],n=\"function\"==typeof s.getRange&&s.getRange(e);if(n){const s=t(o,e,i-n),a=t(o,e,i+n);return{lo:s.lo,hi:a.hi}}}}return{lo:0,hi:o.length-1}}function Hi(t,e,i,s,n){const o=t.getSortedVisibleDatasetMetas(),a=i[e];for(let t=0,i=o.length;t<i;++t){const{index:i,data:r}=o[t],{lo:l,hi:h}=Ni(o[t],e,a,n);for(let t=l;t<=h;++t){const e=r[t];e.skip||s(e,i,t)}}}function ji(t,e,i,s,n){const o=[];if(!n&&!t.isPointInArea(e))return o;return Hi(t,i,e,(function(i,a,r){(n||Re(i,t.chartArea,0))&&i.inRange(e.x,e.y,s)&&o.push({element:i,datasetIndex:a,index:r})}),!0),o}function $i(t,e,i,s,n,o){let a=[];const r=function(t){const e=-1!==t.indexOf(\"x\"),i=-1!==t.indexOf(\"y\");return function(t,s){const n=e?Math.abs(t.x-s.x):0,o=i?Math.abs(t.y-s.y):0;return Math.sqrt(Math.pow(n,2)+Math.pow(o,2))}}(i);let l=Number.POSITIVE_INFINITY;return Hi(t,i,e,(function(i,h,c){const d=i.inRange(e.x,e.y,n);if(s&&!d)return;const u=i.getCenterPoint(n);if(!(!!o||t.isPointInArea(u))&&!d)return;const f=r(e,u);f<l?(a=[{element:i,datasetIndex:h,index:c}],l=f):f===l&&a.push({element:i,datasetIndex:h,index:c})})),a}function Yi(t,e,i,s,n,o){return o||t.isPointInArea(e)?\"r\"!==i||s?$i(t,e,i,s,n,o):function(t,e,i,s){let n=[];return Hi(t,i,e,(function(t,i,o){const{startAngle:a,endAngle:r}=t.getProps([\"startAngle\",\"endAngle\"],s),{angle:l}=X(t,{x:e.x,y:e.y});Z(l,a,r)&&n.push({element:t,datasetIndex:i,index:o})})),n}(t,e,i,n):[]}function Ui(t,e,i,s,n){const o=[],a=\"x\"===i?\"inXRange\":\"inYRange\";let r=!1;return Hi(t,i,e,((t,s,l)=>{t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Xi={evaluateInteractionItems:Hi,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||\"x\",a=i.includeInvisible||!1,r=i.intersect?ji(t,n,o,s,a):Yi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||\"xy\",a=i.includeInvisible||!1;let r=i.intersect?ji(t,n,o,s,a):Yi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;t<i.length;++t)r.push({element:i[t],datasetIndex:e,index:t})}return r},point:(t,e,i,s)=>ji(t,ve(e,t),i.axis||\"xy\",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||\"xy\",a=i.includeInvisible||!1;return Yi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>Ui(t,ve(e,t),\"x\",i.intersect,s),y:(t,e,i,s)=>Ui(t,ve(e,t),\"y\",i.intersect,s)}};const qi=[\"left\",\"top\",\"right\",\"bottom\"];function Ki(t,e){return t.filter((t=>t.pos===e))}function Gi(t,e){return t.filter((t=>-1===qi.indexOf(t.pos)&&t.box.axis===e))}function Zi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function Ji(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!qi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o<a;++o){r=t[o];const{fullSize:a}=r.box,l=i[r.stack],h=l&&r.stackWeight/l.weight;r.horizontal?(r.width=h?h*s:a&&e.availableWidth,r.height=n):(r.width=s,r.height=h?h*n:a&&e.availableHeight)}return i}function Qi(t,e,i,s){return Math.max(t[i],e[i])+Math.max(t[s],e[s])}function ts(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function es(t,e,i,s){const{pos:n,box:a}=i,r=t.maxPadding;if(!o(n)){i.size&&(t[n]-=i.size);const e=s[i.stack]||{size:0,count:1};e.size=Math.max(e.size,i.horizontal?a.height:a.width),i.size=e.size/e.count,t[n]+=i.size}a.getPadding&&ts(r,a.getPadding());const l=Math.max(0,e.outerWidth-Qi(r,t,\"left\",\"right\")),h=Math.max(0,e.outerHeight-Qi(r,t,\"top\",\"bottom\")),c=l!==t.w,d=h!==t.h;return t.w=l,t.h=h,i.horizontal?{same:c,other:d}:{same:d,other:c}}function is(t,e){const i=e.maxPadding;function s(t){const s={left:0,top:0,right:0,bottom:0};return t.forEach((t=>{s[t]=Math.max(e[t],i[t])})),s}return s(t?[\"left\",\"right\"]:[\"top\",\"bottom\"])}function ss(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;o<a;++o){r=t[o],l=r.box,l.update(r.width||e.w,r.height||e.h,is(r.horizontal,e));const{same:a,other:d}=es(e,i,r,s);h|=a&&n.length,c=c||d,l.fullSize||n.push(r)}return h&&ss(n,e,i,s)||c}function ns(t,e,i,s,n){t.top=i,t.left=e,t.right=e+s,t.bottom=i+n,t.width=s,t.height=n}function os(t,e,i,s){const n=i.padding;let{x:o,y:a}=e;for(const r of t){const t=r.box,l=s[r.stack]||{count:1,placed:0,weight:1},h=r.stackWeight/l.weight||1;if(r.horizontal){const s=e.w*h,o=l.size||t.height;k(l.start)&&(a=l.start),t.fullSize?ns(t,n.left,a,i.outerWidth-n.right-n.left,o):ns(t,e.left+l.placed,a,s,o),l.start=a,l.placed+=s,a=t.bottom}else{const s=e.h*h,a=l.size||t.width;k(l.start)&&(o=l.start),t.fullSize?ns(t,o,n.top,a,i.outerHeight-n.bottom-n.top):ns(t,o,e.top+l.placed,a,s),l.start=o,l.placed+=s,o=t.right}}e.x=o,e.y=a}var as={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||\"top\",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(t){e.draw(t)}}]},t.boxes.push(e)},removeBox(t,e){const i=t.boxes?t.boxes.indexOf(e):-1;-1!==i&&t.boxes.splice(i,1)},configure(t,e,i){e.fullSize=i.fullSize,e.position=i.position,e.weight=i.weight},update(t,e,i,s){if(!t)return;const n=ki(t.options.layout.padding),o=Math.max(e-n.width,0),a=Math.max(i-n.height,0),r=function(t){const e=function(t){const e=[];let i,s,n,o,a,r;for(i=0,s=(t||[]).length;i<s;++i)n=t[i],({position:o,options:{stack:a,stackWeight:r=1}}=n),e.push({index:i,box:n,pos:o,horizontal:n.isHorizontal(),weight:n.weight,stack:a&&o+a,stackWeight:r});return e}(t),i=Zi(e.filter((t=>t.box.fullSize)),!0),s=Zi(Ki(e,\"left\"),!0),n=Zi(Ki(e,\"right\")),o=Zi(Ki(e,\"top\"),!0),a=Zi(Ki(e,\"bottom\")),r=Gi(e,\"x\"),l=Gi(e,\"y\");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Ki(e,\"chartArea\"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{\"function\"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);ts(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=Ji(l.concat(h),d);ss(r.fullSize,g,d,p),ss(l,g,d,p),ss(h,g,d,p)&&ss(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i(\"top\"),t.x+=i(\"left\"),i(\"right\"),i(\"bottom\")}(g),os(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,os(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class rs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class ls extends rs{acquireContext(t){return t&&t.getContext&&t.getContext(\"2d\")||null}updateConfig(t){t.options.animation=!1}}const hs=\"$chartjs\",cs={touchstart:\"mousedown\",touchmove:\"mousemove\",touchend:\"mouseup\",pointerenter:\"mouseenter\",pointerdown:\"mousedown\",pointermove:\"mousemove\",pointerup:\"mouseup\",pointerleave:\"mouseout\",pointerout:\"mouseout\"},ds=t=>null===t||\"\"===t;const us=!!Se&&{passive:!0};function fs(t,e,i){t.canvas.removeEventListener(e,i,us)}function gs(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function ps(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||gs(i.addedNodes,s),e=e&&!gs(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function ms(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||gs(i.removedNodes,s),e=e&&!gs(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const bs=new Map;let xs=0;function _s(){const t=window.devicePixelRatio;t!==xs&&(xs=t,bs.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function ys(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s<n.clientWidth&&i()}),window),a=new ResizeObserver((t=>{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){bs.size||window.addEventListener(\"resize\",_s),bs.set(t,e)}(t,o),a}function vs(t,e,i){i&&i.disconnect(),\"resize\"===e&&function(t){bs.delete(t),bs.size||window.removeEventListener(\"resize\",_s)}(t)}function Ms(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=cs[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t.addEventListener(e,i,us)}(s,e,n),n}class ws extends rs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext(\"2d\");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute(\"height\"),n=t.getAttribute(\"width\");if(t[hs]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||\"block\",i.boxSizing=i.boxSizing||\"border-box\",ds(n)){const e=Pe(t,\"width\");void 0!==e&&(t.width=e)}if(ds(s))if(\"\"===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,\"height\");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[hs])return!1;const i=e[hs].initial;[\"height\",\"width\"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[hs],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:ps,detach:ms,resize:ys}[e]||Ms;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:vs,detach:vs,resize:vs}[e]||fs)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=ge(t);return!(!e||!e.isConnected)}}function ks(t){return!fe()||\"undefined\"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?ls:ws}var Ss=Object.freeze({__proto__:null,BasePlatform:rs,BasicPlatform:ls,DomPlatform:ws,_detectPlatform:ks});const Ps=\"transparent\",Ds={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Ps),n=s.valid&&Qt(e||Ps);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class Cs{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Ds[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e<i),!this._active)return this._target[s]=a,void this._notify(!0);e<0?this._target[s]=n:(r=e/i%2,r=o&&r>1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?\"res\":\"rej\",i=this._promises||[];for(let t=0;t<i.length;t++)i[t][e]()}}class Os{constructor(t,e){this._chart=t,this._properties=new Map,this.configure(e)}configure(t){if(!o(t))return;const e=Object.keys(ue.animation),i=this._properties;Object.getOwnPropertyNames(t).forEach((s=>{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e<s.length;e++){const n=t[s[e]];n&&n.active()&&i.push(n.wait())}return Promise.all(i)}(t.options.$animations,i).then((()=>{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if(\"$\"===l.charAt(0))continue;if(\"options\"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new Cs(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(xt.add(this._chart,i),!0):void 0}}function As(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Ts(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n<o;++n)i.push(s[n].index);return i}function Ls(t,e,i,s={}){const n=t.keys,o=\"single\"===s.mode;let r,l,h,c;if(null!==e){for(r=0,l=n.length;r<l;++r){if(h=+n[r],h===i){if(s.all)continue;break}c=t.values[h],a(c)&&(o||0===e||F(e)===F(c))&&(e+=c)}return e}}function Es(t,e){const i=t&&t.options.stacked;return i||void 0===i&&void 0!==e.stack}function Rs(t,e,i){const s=t[e]||(t[e]={});return s[i]||(s[i]={})}function Is(t,e,i,s){for(const n of e.getMatchingVisibleMetas(s).reverse()){const e=t[n.index];if(i&&e>0||!i&&e<0)return n.index}return null}function zs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;t<d;++t){const i=e[t],{[l]:o,[h]:d}=i;u=(i._stacks||(i._stacks={}))[h]=Rs(n,c,o),u[r]=d,u._top=Is(u,a,!0,s.type),u._bottom=Is(u,a,!1,s.type);(u._visualValues||(u._visualValues={}))[r]=d}}function Fs(t,e){const i=t.scales;return Object.keys(i).filter((t=>i[t].axis===e)).shift()}function Vs(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Bs=t=>\"reset\"===t||\"none\"===t,Ws=(t,e)=>e?t:Object.assign({},t);class Ns{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Es(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled(\"filler\")&&console.warn(\"Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options\")}updateIndex(t){this.index!==t&&Vs(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>\"x\"===t?e:\"r\"===t?s:i,n=e.xAxisID=l(i.xAxisID,Fs(t,\"x\")),o=e.yAxisID=l(i.yAxisID,Fs(t,\"y\")),a=e.rAxisID=l(i.rAxisID,Fs(t,\"r\")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update(\"reset\")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Vs(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e))this._data=function(t){const e=Object.keys(t),i=new Array(e.length);let s,n,o;for(s=0,n=e.length;s<n;++s)o=e[s],i[s]={x:o,y:t[o]};return i}(e);else if(i!==e){if(i){rt(i,this);const t=this._cachedMeta;Vs(t),t._parsed=[]}e&&Object.isExtensible(e)&&at(e,this),this._syncList=[],this._data=e}}addElements(){const t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){const e=this._cachedMeta,i=this.getDataset();let s=!1;this._dataCheck();const n=e._stacked;e._stacked=Es(e.vScale,e),e.stack!==i.stack&&(s=!0,Vs(e),e.stack=i.stack),this._resyncElements(t),(s||n!==e._stacked)&&zs(this,e._parsed)}configure(){const t=this.chart.config,e=t.datasetScopeKeys(this._type),i=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(i,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){const{_cachedMeta:i,_data:s}=this,{iScale:a,_stacked:r}=i,l=a.axis;let h,c,d,u=0===t&&e===s.length||i._sorted,f=t>0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]<f[l];for(h=0;h<e;++h)i._parsed[h+t]=c=d[h],u&&(a()&&(u=!1),f=c);i._sorted=u}r&&zs(this,d)}parsePrimitiveData(t,e,i,s){const{iScale:n,vScale:o}=t,a=n.axis,r=o.axis,l=n.getLabels(),h=n===o,c=new Array(s);let d,u,f;for(d=0,u=s;d<u;++d)f=d+i,c[d]={[a]:h||n.parse(l[f],f),[r]:o.parse(e[f],f)};return c}parseArrayData(t,e,i,s){const{xScale:n,yScale:o}=t,a=new Array(s);let r,l,h,c;for(r=0,l=s;r<l;++r)h=r+i,c=e[h],a[r]={x:n.parse(c[0],h),y:o.parse(c[1],h)};return a}parseObjectData(t,e,i,s){const{xScale:n,yScale:o}=t,{xAxisKey:a=\"x\",yAxisKey:r=\"y\"}=this._parsing,l=new Array(s);let h,c,d,u;for(h=0,c=s;h<c;++h)d=h+i,u=e[d],l[h]={x:n.parse(M(u,a),d),y:o.parse(M(u,r),d)};return l}getParsed(t){return this._cachedMeta._parsed[t]}getDataElement(t){return this._cachedMeta.data[t]}applyStack(t,e,i){const s=this.chart,n=this._cachedMeta,o=e[t.axis];return Ls({keys:Ts(s,!0),values:e._stacks[t.axis]._visualValues},o,n.index,{mode:i})}updateRangeFromParsed(t,e,i,s){const n=i[e.axis];let o=null===n?NaN:n;const a=s&&i._stacks[e.axis];s&&a&&(s.values=a,o=Ls(s,n,this._cachedMeta.index)),t.min=Math.min(t.min,o),t.max=Math.max(t.max,o)}getMinMax(t,e){const i=this._cachedMeta,s=i._parsed,n=i._sorted&&t===i.iScale,o=s.length,r=this._getOtherScale(t),l=((t,e,i)=>t&&!e.hidden&&e._stacked&&{keys:Ts(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d<e}for(u=0;u<o&&(g()||(this.updateRangeFromParsed(h,t,f,l),!n));++u);if(n)for(u=o-1;u>=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s<n;++s)o=e[s][t.axis],a(o)&&i.push(o);return i}getMaxOverflow(){return!1}getLabelAndValue(t){const e=this._cachedMeta,i=e.iScale,s=e.vScale,n=this.getParsed(t);return{label:i?\"\"+i.getLabelForValue(n[i.axis]):\"\",value:s?\"\"+s.getLabelForValue(n[s.axis]):\"\"}}_update(t){const e=this._cachedMeta;this.update(t||\"default\"),e._clip=function(t){let e,i,s,n;return o(t)?(e=t.top,i=t.right,s=t.bottom,n=t.left):e=i=s=n=t,{top:e,right:i,bottom:s,left:n,disabled:!1===t}}(l(this.options.clip,function(t,e,i){if(!1===i)return!1;const s=As(t,i),n=As(e,i);return{top:n.end,right:s.end,bottom:n.start,left:s.start}}(e.xScale,e.yScale,this.getMaxOverflow())))}update(t){}draw(){const t=this._ctx,e=this.chart,i=this._cachedMeta,s=i.data||[],n=e.chartArea,o=[],a=this._drawStart||0,r=this._drawCount||s.length-a,l=this.options.drawActiveElementsOnTop;let h;for(i.dataset&&i.dataset.draw(t,n,a,r),h=a;h<a+r;++h){const e=s[h];e.hidden||(e.active&&l?o.push(e):e.draw(t,n))}for(h=0;h<o.length;++h)o[h].draw(t,n)}getStyle(t,e){const i=e?\"active\":\"default\";return void 0===t&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(i):this.resolveDataElementOptions(t||0,i)}getContext(t,e,i){const s=this.getDataset();let n;if(t>=0&&t<this._cachedMeta.data.length){const e=this._cachedMeta.data[t];n=e.$context||(e.$context=function(t,e,i){return Ci(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:i,index:e,mode:\"default\",type:\"data\"})}(this.getContext(),t,e)),n.parsed=this.getParsed(t),n.raw=s.data[t],n.index=n.dataIndex=t}else n=this.$context||(this.$context=function(t,e){return Ci(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:\"default\",type:\"dataset\"})}(this.chart.getContext(),this.index)),n.dataset=s,n.index=n.datasetIndex=this.index;return n.active=!!e,n.mode=i,n}resolveDatasetElementOptions(t){return this._resolveElementOptions(this.datasetElementType.id,t)}resolveDataElementOptions(t,e){return this._resolveElementOptions(this.dataElementType.id,e,t)}_resolveElementOptions(t,e=\"default\",i){const s=\"active\"===e,n=this._cachedDataOpts,o=t+\"-\"+e,a=n[o],r=this.enableOptionSharing&&k(i);if(a)return Ws(a,r);const l=this.chart.config,h=l.datasetElementScopeKeys(this._type,t),c=s?[`${t}Hover`,\"hover\",t,\"\"]:[t,\"\"],d=l.getOptionScopes(this.getDataset(),h),u=Object.keys(ue.elements[t]),f=l.resolveNamedOptions(d,u,(()=>this.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Ws(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Os(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Bs(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Bs(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Bs(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,\"active\",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,\"active\",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,\"active\",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,\"active\",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n<s&&this._removeElements(n,s-n)}_insertElements(t,e,i=!0){const s=this._cachedMeta,n=s.data,o=t+e;let a;const r=t=>{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a<o;++a)n[a]=new this.dataElementType;this._parsing&&r(s._parsed),this.parse(t,e),i&&this.updateElements(n,t,e,\"reset\")}updateElements(t,e,i,s){}_removeElements(t,e){const i=this._cachedMeta;if(this._parsing){const s=i._parsed.splice(t,e);i._stacked&&Vs(i,s)}i.data.splice(t,e)}_sync(t){if(this._parsing)this._syncList.push(t);else{const[e,i,s]=t;this[e](i,s)}this.chart._dataChanges.push([this.index,...t])}_onDataPush(){const t=arguments.length;this._sync([\"_insertElements\",this.getDataset().data.length-t,t])}_onDataPop(){this._sync([\"_removeElements\",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync([\"_removeElements\",0,1])}_onDataSplice(t,e){e&&this._sync([\"_removeElements\",t,e]);const i=arguments.length-2;i&&this._sync([\"_insertElements\",t,i])}_onDataUnshift(){this._sync([\"_insertElements\",0,arguments.length])}}class Hs{static defaults={};static defaultRoutes=void 0;x;y;active=!1;options;$animations;tooltipPosition(t){const{x:e,y:i}=this.getProps([\"x\",\"y\"],t);return{x:e,y:i}}hasValue(){return N(this.x)&&N(this.y)}getProps(t,e){const i=this.$animations;if(!e||!i)return this;const s={};return t.forEach((t=>{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function js(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;i<s;i++)t[i].major&&e.push(i);return e}(e):[],r=a.length,l=a[0],h=a[r-1],c=[];if(r>o)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;n<t.length;n++)n===a&&(e.push(t[n]),o++,a=i[o*s])}(e,c,a,r/o),c;const d=function(t,e,i){const s=function(t){const e=t.length;let i,s;if(e<2)return!1;for(s=t[0],i=1;i<e;++i)if(t[i]-t[i-1]!==s)return!1;return s}(t),n=e.length/i;if(!s)return Math.max(n,1);const o=W(s);for(let t=0,e=o.length-1;t<e;t++){const e=o[t];if(e>n)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for($s(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t<i;t++)$s(e,c,d,a[t],a[t+1]);return $s(e,c,d,h,s(n)?e.length:h+n),c}return $s(e,c,d),c}function $s(t,e,i,s,n){const o=l(s,0),a=Math.min(l(n,t.length),t.length);let r,h,c,d=0;for(i=Math.ceil(i),n&&(r=n-s,i=r/Math.floor(r/i)),c=o;c<0;)d++,c=Math.round(o+d*i);for(h=Math.max(o,0);h<a;h++)h===c&&(e.push(t[h]),d++,c=Math.round(o+d*i))}const Ys=(t,e,i)=>\"top\"===e||\"left\"===e?t[e]+i:t[e]-i,Us=(t,e)=>Math.min(e||t,t);function Xs(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;o<n;o+=s)i.push(t[Math.floor(o)]);return i}function qs(t,e,i){const s=t.ticks.length,n=Math.min(e,s-1),o=t._startPixel,a=t._endPixel,r=1e-6;let l,h=t.getPixelForTick(n);if(!(i&&(l=1===s?Math.max(h-o,a-h):0===e?(t.getPixelForTick(1)-h)/2:(h-t.getPixelForTick(n-1))/2,h+=n<e?l:-l,h<o-r||h>a+r)))return h}function Ks(t){return t.drawTicks?t.tickLength:0}function Gs(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Zs(t,e,i){let s=ut(t);return(i&&\"right\"!==e||!i&&\"right\"===e)&&(s=(t=>\"left\"===t?\"right\":\"right\"===t?\"left\":t)(s)),s}class Js extends Hs{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;r<l;++r)e=a[r].controller.getMinMax(this,t),n||(i=Math.min(i,e.min)),o||(s=Math.max(s,e.max));return i=o&&i>s?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a<this.ticks.length;this._convertTicksToLabels(r?Xs(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),o.display&&(o.autoSkip||\"auto\"===o.source)&&(this.ticks=js(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),r&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let t,e,i=this.options.reverse;this.isHorizontal()?(t=this.left,e=this.right):(t=this.top,e=this.bottom,i=!i),this._startPixel=t,this._endPixel=e,this._reversePixels=i,this._length=e-t,this._alignToPixels=this.options.alignToPixels}afterUpdate(){d(this.options.afterUpdate,[this])}beforeSetDimensions(){d(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){d(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),d(this.options[t],[this])}beforeDataLimits(){this._callHooks(\"beforeDataLimits\")}determineDataLimits(){}afterDataLimits(){this._callHooks(\"afterDataLimits\")}beforeBuildTicks(){this._callHooks(\"beforeBuildTicks\")}buildTicks(){return[]}afterBuildTicks(){this._callHooks(\"afterBuildTicks\")}beforeTickToLabelConversion(){d(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(t){const e=this.options.ticks;let i,s,n;for(i=0,s=t.length;i<s;i++)n=t[i],n.label=d(e.callback,[n.value,i,t],this)}afterTickToLabelConversion(){d(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){d(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,e=t.ticks,i=Us(this.ticks.length,t.ticks.maxTicksLimit),s=e.minRotation||0,n=e.maxRotation;let o,a,r,l=s;if(!this._isVisible()||!e.display||s>=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=J(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Ks(t.grid)-e.padding-Gs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(J((h.highest.height+6)/o,-1,1)),Math.asin(J(a/r,-1,1))-Math.asin(J(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Gs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Ks(n)+o):(t.height=this.maxHeight,t.width=Ks(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l=\"top\"!==a&&\"x\"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):\"start\"===n?d=e.width:\"end\"===n?c=t.width:\"inner\"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;\"start\"===n?(i=0,s=t.height):\"end\"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return\"top\"===e||\"bottom\"===e||\"x\"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e<i;e++)s(t[e].label)&&(t.splice(e,1),i--,e--);this.afterTickToLabelConversion()}_getLabelSizes(){let t=this._labelSizes;if(!t){const e=this.options.ticks.sampleSize;let i=this.ticks;e<i.length&&(i=Xs(i,e)),this._labelSizes=t=this._computeLabelSizes(i,i.length,this.options.ticks.maxTicksLimit)}return t}_computeLabelSizes(t,e,i){const{ctx:o,_longestTextCache:a}=this,r=[],l=[],h=Math.floor(e/Us(e,i));let c,d,f,g,p,m,b,x,_,y,v,M=0,w=0;for(c=0;c<e;c+=h){if(g=t[c].label,p=this._resolveTickFontOptions(c),o.font=m=p.string,b=a[m]=a[m]||{data:{},gc:[]},x=p.lineHeight,_=y=0,s(g)||n(g)){if(n(g))for(d=0,f=g.length;d<f;++d)v=g[d],s(v)||n(v)||(_=Ce(o,b.data,b.gc,_,v),y+=x)}else _=Ce(o,b.data,b.gc,_,g),y=x;r.push(_),l.push(y),M=Math.max(_,M),w=Math.max(y,w)}!function(t,e){u(t,(t=>{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n<s;++n)delete t.data[i[n]];i.splice(0,s)}}))}(a,e);const k=r.indexOf(M),S=l.indexOf(w),P=t=>({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&t<e.length){const i=e[t];return i.$context||(i.$context=function(t,e,i){return Ci(t,{tick:i,index:e,type:\"tick\"})}(this.getContext(),t,i))}return this.$context||(this.$context=Ci(this.chart.getContext(),{scale:this,type:\"scale\"}))}_tickSize(){const t=this.options.ticks,e=$(this.labelRotation),i=Math.abs(Math.cos(e)),s=Math.abs(Math.sin(e)),n=this._getLabelSizes(),o=t.autoSkipPadding||0,a=n?n.widest.width+o:0,r=n?n.highest.height+o:0;return this.isHorizontal()?r*i>a*s?a/i:r/s:r*s<a*i?r/i:a/s}_isVisible(){const t=this.options.display;return\"auto\"!==t?!!t:this.getMatchingVisibleMetas().length>0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Ks(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,b=function(t){return Ae(i,t,p)};let x,_,y,v,M,w,k,S,P,D,C,O;if(\"top\"===a)x=b(this.bottom),w=this.bottom-u,S=x-m,D=b(t.top)+m,O=t.bottom;else if(\"bottom\"===a)x=b(this.top),D=t.top,O=b(t.bottom)-m,w=x+m,S=this.top+u;else if(\"left\"===a)x=b(this.right),M=this.right-u,k=x-m,P=b(t.left)+m,C=t.right;else if(\"right\"===a)x=b(this.left),P=t.left,C=b(t.right)-m,M=x+m,k=this.left+u;else if(\"x\"===e){if(\"center\"===a)x=b((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];x=b(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=x+m,S=w+u}else if(\"y\"===e){if(\"center\"===a)x=b((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];x=b(this.chart.scales[t].getPixelForValue(e))}M=x-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_<d;_+=T){const t=this.getContext(_),e=n.setContext(t),s=r.setContext(t),o=e.lineWidth,a=e.color,l=s.dash||[],d=s.dashOffset,u=e.tickWidth,g=e.tickColor,p=e.tickBorderDash||[],m=e.tickBorderDashOffset;y=qs(this,_,h),void 0!==y&&(v=Ae(i,y,o),c?M=k=P=C=v:w=S=D=O=v,f.push({tx1:M,ty1:w,tx2:k,ty2:S,x1:P,y1:D,x2:C,y2:O,width:o,color:a,borderDash:l,borderDashOffset:d,tickWidth:u,tickColor:g,tickBorderDash:p,tickBorderDashOffset:m}))}return this._ticksLength=d,this._borderValue=x,f}_computeLabelItems(t){const e=this.axis,i=this.options,{position:s,ticks:a}=i,r=this.isHorizontal(),l=this.ticks,{align:h,crossAlign:c,padding:d,mirror:u}=a,f=Ks(i.grid),g=f+d,p=u?-d:g,m=-$(this.labelRotation),b=[];let x,_,y,v,M,w,k,S,P,D,C,O,A=\"middle\";if(\"top\"===s)w=this.bottom-p,k=this._getXAxisLabelAlignment();else if(\"bottom\"===s)w=this.top+p,k=this._getXAxisLabelAlignment();else if(\"left\"===s){const t=this._getYAxisLabelAlignment(f);k=t.textAlign,M=t.x}else if(\"right\"===s){const t=this._getYAxisLabelAlignment(f);k=t.textAlign,M=t.x}else if(\"x\"===e){if(\"center\"===s)w=(t.top+t.bottom)/2+g;else if(o(s)){const t=Object.keys(s)[0],e=s[t];w=this.chart.scales[t].getPixelForValue(e)+g}k=this._getXAxisLabelAlignment()}else if(\"y\"===e){if(\"center\"===s)M=(t.left+t.right)/2-g;else if(o(s)){const t=Object.keys(s)[0],e=s[t];M=this.chart.scales[t].getPixelForValue(e)}k=this._getYAxisLabelAlignment(f).textAlign}\"y\"===e&&(\"start\"===h?A=\"top\":\"end\"===h&&(A=\"bottom\"));const T=this._getLabelSizes();for(x=0,_=l.length;x<_;++x){y=l[x],v=y.label;const t=a.setContext(this.getContext(x));S=this.getPixelForTick(x)+a.labelOffset,P=this._resolveTickFontOptions(x),D=P.lineHeight,C=n(v)?v.length:1;const e=C/2,i=t.color,o=t.textStrokeColor,h=t.textStrokeWidth;let d,f=k;if(r?(M=S,\"inner\"===k&&(f=x===_-1?this.options.reverse?\"left\":\"right\":0===x?this.options.reverse?\"right\":\"left\":\"center\"),O=\"top\"===s?\"near\"===c||0!==m?-C*D+D/2:\"center\"===c?-T.highest.height/2-e*D+D:-T.highest.height+D/2:\"near\"===c||0!==m?D/2:\"center\"===c?T.highest.height/2-e*D:T.highest.height-C*D,u&&(O*=-1),0===m||t.showLabelBackdrop||(M+=D/2*Math.sin(m))):(w=S,O=(1-C)*D/2),t.showLabelBackdrop){const e=ki(t.backdropPadding),i=T.heights[x],s=T.widths[x];let n=O-e.top,o=0-e.left;switch(A){case\"middle\":n-=i/2;break;case\"bottom\":n-=i}switch(k){case\"center\":o-=s/2;break;case\"right\":o-=s}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}b.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return b}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return\"top\"===t?\"left\":\"right\";let i=\"center\";return\"start\"===e.align?i=\"left\":\"end\"===e.align?i=\"right\":\"inner\"===e.align&&(i=\"inner\"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return\"left\"===e?s?(l=this.right+n,\"near\"===i?r=\"left\":\"center\"===i?(r=\"center\",l+=a/2):(r=\"right\",l+=a)):(l=this.right-o,\"near\"===i?r=\"right\":\"center\"===i?(r=\"center\",l-=a/2):(r=\"left\",l=this.left)):\"right\"===e?s?(l=this.left+n,\"near\"===i?r=\"right\":\"center\"===i?(r=\"center\",l-=a/2):(r=\"left\",l-=a)):(l=this.left+o,\"near\"===i?r=\"left\":\"center\"===i?(r=\"center\",l+=a/2):(r=\"right\",l=this.right)):r=\"right\",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return\"left\"===e||\"right\"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:\"top\"===e||\"bottom\"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n<o;++n){const t=s[n];e.drawOnChartArea&&a({x:t.x1,y:t.y1},{x:t.x2,y:t.y2},t),e.drawTicks&&a({x:t.tx1,y:t.ty1},{x:t.tx2,y:t.ty2},{color:t.tickColor,width:t.tickWidth,borderDash:t.tickBorderDash,borderDashOffset:t.tickBorderDashOffset})}}drawBorder(){const{chart:t,ctx:e,options:{border:i,grid:s}}=this,n=i.setContext(this.getContext()),o=i.display?n.width:0;if(!o)return;const a=s.setContext(this.getContext(0)).lineWidth,r=this._borderValue;let l,h,c,d;this.isHorizontal()?(l=Ae(t,this.left,o)-o/2,h=Ae(t,this.right,a)+a/2,c=d=r):(c=Ae(t,this.top,o)-o/2,d=Ae(t,this.bottom,a)+a/2,l=h=r),e.save(),e.lineWidth=n.width,e.strokeStyle=n.color,e.beginPath(),e.moveTo(l,c),e.lineTo(h,d),e.stroke(),e.restore()}drawLabels(t){if(!this.options.ticks.display)return;const e=this.ctx,i=this._computeLabelArea();i&&Ie(e,i);const s=this.getLabelItems(t);for(const t of s){const i=t.options,s=t.font;Ne(e,t.label,0,t.textOffset,s,i)}i&&ze(e)}drawTitle(){const{ctx:t,options:{position:e,title:i,reverse:s}}=this;if(!i.display)return;const a=Si(i.font),r=ki(i.padding),l=i.align;let h=a.lineHeight/2;\"bottom\"===e||\"center\"===e||o(e)?(h+=r.bottom,n(i.text)&&(h+=a.lineHeight*(i.text.length-1))):h+=r.top;const{titleX:c,titleY:d,maxWidth:u,rotation:f}=function(t,e,i,s){const{top:n,left:a,bottom:r,right:l,chart:h}=t,{chartArea:c,scales:d}=h;let u,f,g,p=0;const m=r-n,b=l-a;if(t.isHorizontal()){if(f=ft(s,a,l),o(i)){const t=Object.keys(i)[0],s=i[t];g=d[t].getPixelForValue(s)+m-e}else g=\"center\"===i?(c.bottom+c.top)/2+m-e:Ys(t,i,e);u=l-a}else{if(o(i)){const t=Object.keys(i)[0],s=i[t];f=d[t].getPixelForValue(s)-b+e}else f=\"center\"===i?(c.left+c.right)/2-b+e:Ys(t,i,e);g=ft(s,r,n),p=\"left\"===i?-E:E}return{titleX:f,titleY:g,maxWidth:u,rotation:p}}(this,h,e,l);Ne(t,i.text,0,0,a,{color:i.color,maxWidth:u,rotation:f,textAlign:Zs(l,e,s),textBaseline:\"middle\",translation:[c,d]})}draw(t){this._isVisible()&&(this.drawBackground(),this.drawGrid(t),this.drawBorder(),this.drawTitle(),this.drawLabels(t))}_layers(){const t=this.options,e=t.ticks&&t.ticks.z||0,i=l(t.grid&&t.grid.z,-1),s=l(t.border&&t.border.z,0);return this._isVisible()&&this.draw===Js.prototype.draw?[{z:i,draw:t=>{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+\"AxisID\",s=[];let n,o;for(n=0,o=e.length;n<o;++n){const o=e[n];o[i]!==this.id||t&&o.type!==t||s.push(o)}return s}_resolveTickFontOptions(t){return Si(this.options.ticks.setContext(this.getContext(t)).font)}_maxDigits(){const t=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/t}}class Qs{constructor(t,e,i){this.type=t,this.scope=e,this.override=i,this.items=Object.create(null)}isForType(t){return Object.prototype.isPrototypeOf.call(this.type.prototype,t.prototype)}register(t){const e=Object.getPrototypeOf(t);let i;(function(t){return\"id\"in t&&\"defaults\"in t})(e)&&(i=this.register(e));const s=this.items,n=t.id,o=this.scope+\".\"+n;if(!n)throw new Error(\"class does not have id: \"+t);return n in s||(s[n]=t,function(t,e,i){const s=b(Object.create(null),[i?ue.get(i):{},ue.get(e),t.defaults]);ue.set(e,s),t.defaultRoutes&&function(t,e){Object.keys(e).forEach((i=>{const s=i.split(\".\"),n=s.pop(),o=[t].concat(s).join(\".\"),a=e[i].split(\".\"),r=a.pop(),l=a.join(\".\");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class tn{constructor(){this.controllers=new Qs(Ns,\"datasets\",!0),this.elements=new Qs(Hs,\"elements\"),this.plugins=new Qs(Object,\"plugins\"),this.scales=new Qs(Js,\"scales\"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each(\"register\",t)}remove(...t){this._each(\"unregister\",t)}addControllers(...t){this._each(\"register\",t,this.controllers)}addElements(...t){this._each(\"register\",t,this.elements)}addPlugins(...t){this._each(\"register\",t,this.plugins)}addScales(...t){this._each(\"register\",t,this.scales)}getController(t){return this._get(t,this.controllers,\"controller\")}getElement(t){return this._get(t,this.elements,\"element\")}getPlugin(t){return this._get(t,this.plugins,\"plugin\")}getScale(t){return this._get(t,this.scales,\"scale\")}removeControllers(...t){this._each(\"unregister\",t,this.controllers)}removeElements(...t){this._each(\"unregister\",t,this.elements)}removePlugins(...t){this._each(\"unregister\",t,this.plugins)}removeScales(...t){this._each(\"unregister\",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i[\"before\"+s],[],i),e[t](i),d(i[\"after\"+s],[],i)}_getRegistryForType(t){for(let e=0;e<this._typedRegistries.length;e++){const i=this._typedRegistries[e];if(i.isForType(t))return i}return this.plugins}_get(t,e,i){const s=e.get(t);if(void 0===s)throw new Error('\"'+t+'\" is not a registered '+i+\".\");return s}}var en=new tn;class sn{constructor(){this._init=[]}notify(t,e,i,s){\"beforeInit\"===e&&(this._init=this._createDescriptors(t,!0),this._notify(this._init,t,\"install\"));const n=s?this._descriptors(t).filter(s):this._descriptors(t),o=this._notify(n,t,e,i);return\"afterDestroy\"===e&&(this._notify(n,t,\"stop\"),this._notify(this._init,t,\"uninstall\")),o}_notify(t,e,i,s){s=s||{};for(const n of t){const t=n.plugin;if(!1===d(t[i],[e,s,n.options],t)&&s.cancelable)return!1}return!0}invalidate(){s(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(t){if(this._cache)return this._cache;const e=this._cache=this._createDescriptors(t);return this._notifyStateChanges(t),e}_createDescriptors(t,e){const i=t&&t.config,s=l(i.options&&i.options.plugins,{}),n=function(t){const e={},i=[],s=Object.keys(en.plugins.items);for(let t=0;t<s.length;t++)i.push(en.getPlugin(s[t]));const n=t.plugins||[];for(let t=0;t<n.length;t++){const s=n[t];-1===i.indexOf(s)&&(i.push(s),e[s.id]=!0)}return{plugins:i,localIds:e}}(i);return!1!==s||e?function(t,{plugins:e,localIds:i},s,n){const o=[],a=t.getContext();for(const r of e){const e=r.id,l=nn(s[e],n);null!==l&&o.push({plugin:r,options:on(t.config,{plugin:r,local:i[e]},l,a)})}return o}(t,n,s,e):[]}_notifyStateChanges(t){const e=this._oldCache||[],i=this._cache,s=(t,e)=>t.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,\"stop\"),this._notify(s(i,e),t,\"start\")}}function nn(t,e){return e||!1!==t?!0===t?{}:t:null}function on(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[\"\"],{scriptable:!1,indexable:!1,allKeys:!0})}function an(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||\"x\"}function rn(t){if(\"x\"===t||\"y\"===t||\"r\"===t)return t}function ln(t,...e){if(rn(t))return t;for(const s of e){const e=s.axis||(\"top\"===(i=s.position)||\"bottom\"===i?\"x\":\"left\"===i||\"right\"===i?\"y\":void 0)||t.length>1&&rn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function hn(t,e,i){if(i[e+\"AxisID\"]===t)return{axis:e}}function cn(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=an(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=ln(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return hn(t,\"x\",i[0])||hn(t,\"y\",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?\"_index_\":\"_value_\"}(l,n),c=i.scales||{};a[e]=x(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||an(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return\"_index_\"===t?i=e:\"_value_\"===t&&(i=\"x\"===e?\"y\":\"x\"),i}(t,o),n=i[e+\"AxisID\"]||e;a[n]=a[n]||Object.create(null),x(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];x(e,[ue.scales[e.type],ue.scale])})),a}function dn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=cn(t,e)}function un(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const fn=new Map,gn=new Set;function pn(t,e){let i=fn.get(t);return i||(i=e(),fn.set(t,i),gn.add(i)),i}const mn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class bn{constructor(t){this._config=function(t){return(t=t||{}).data=un(t.data),dn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=un(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),dn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return pn(t,(()=>[[`datasets.${t}`,\"\"]]))}datasetAnimationScopeKeys(t,e){return pn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,\"\"]]))}datasetElementScopeKeys(t,e){return pn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,\"\"]]))}pluginScopeKeys(t){const e=t.id;return pn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>mn(r,t,e)))),e.forEach((t=>mn(r,s,t))),e.forEach((t=>mn(r,re[n]||{},t))),e.forEach((t=>mn(r,ue,t))),e.forEach((t=>mn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),gn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[\"\"]){const o={$shared:!0},{resolver:a,subPrefixes:r}=xn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||_n(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[\"\"],s){const{resolver:n}=xn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function xn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes(\"hover\")))},s.set(n,o)}return o}const _n=t=>o(t)&&Object.getOwnPropertyNames(t).reduce(((e,i)=>e||S(t[i])),!1);const yn=[\"top\",\"bottom\",\"left\",\"right\",\"chartArea\"];function vn(t,e){return\"top\"===t||\"bottom\"===t||-1===yn.indexOf(t)&&\"x\"===e}function Mn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function wn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins(\"afterRender\"),d(i&&i.onComplete,[t],e)}function kn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Sn(t){return fe()&&\"string\"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Pn={},Dn=t=>{const e=Sn(t);return Object.values(Pn).filter((t=>t.canvas===e)).pop()};function Cn(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}function On(t,e,i){return t.options.clip?t[i]:e[i]}class An{static defaults=ue;static instances=Pn;static overrides=re;static registry=en;static version=\"4.4.0\";static getChart=Dn;static register(...t){en.add(...t),Tn()}static unregister(...t){en.remove(...t),Tn()}constructor(t,e){const s=this.config=new bn(e),n=Sn(t),o=Dn(n);if(o)throw new Error(\"Canvas is already in use. Chart with ID '\"+o.id+\"' must be destroyed before the canvas with ID '\"+o.canvas.id+\"' can be reused.\");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||ks(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new sn,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Pn[this.id]=this,r&&l?(xt.listen(this,\"complete\",wn),xt.listen(this,\"progress\",kn),this._initialize(),this.attached&&this.update()):console.error(\"Failed to create chart: can't acquire context from the given item\")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return en}_initialize(){return this.notifyPlugins(\"beforeInit\"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins(\"afterInit\"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return xt.stop(this),this}resize(t,e){xt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?\"resize\":\"attach\";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins(\"resize\",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=ln(t,i),n=\"r\"===s,o=\"x\"===s;return{options:i,dposition:n?\"chartArea\":o?\"bottom\":\"left\",dtype:n?\"radialLinear\":o?\"category\":\"linear\"}})))),u(n,(e=>{const n=e.options,o=n.id,a=ln(o,n),r=l(n.type,e.dtype);void 0!==n.position&&vn(n.position,a)===vn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(en.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{as.configure(this,t,t.options),as.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;t<i;++t)this._destroyDatasetMeta(t);t.splice(e,i-e)}this._sortedMetasets=t.slice(0).sort(Mn(\"order\",\"index\"))}_removeUnreferencedMetasets(){const{_metasets:t,data:{datasets:e}}=this;t.length>e.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i<s;i++){const s=e[i];let n=this.getDatasetMeta(i);const o=s.type||this.config.type;if(n.type&&n.type!==o&&(this._destroyDatasetMeta(i),n=this.getDatasetMeta(i)),n.type=o,n.indexAxis=s.indexAxis||an(o,this.options),n.order=s.order||0,n.index=i,n.label=\"\"+s.label,n.visible=this.isDatasetVisible(i),n.controller)n.controller.updateIndex(i),n.controller.linkScales();else{const e=en.getController(o),{datasetElementType:s,dataElementType:a}=ue.datasets[o];Object.assign(e,{dataElementType:en.getElement(a),datasetElementType:s&&en.getElement(s)}),n.controller=new e(this,i),t.push(n.controller)}}return this._updateMetasets(),t}_resetElements(){u(this.data.datasets,((t,e)=>{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins(\"reset\")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins(\"beforeUpdate\",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins(\"beforeElementsUpdate\");let o=0;for(let t=0,e=this.data.datasets.length;t<e;t++){const{controller:e}=this.getDatasetMeta(t),i=!s&&-1===n.indexOf(e);e.buildOrUpdateElements(i),o=Math.max(+e.getMaxOverflow(),o)}o=this._minPadding=i.layout.autoPadding?o:0,this._updateLayout(o),s||u(n,(t=>{t.reset()})),this._updateDatasets(t),this.notifyPlugins(\"afterUpdate\",{mode:t}),this._layers.sort(Mn(\"z\",\"_idx\"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{as.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){Cn(t,s,\"_removeElements\"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+\",\"+t.splice(1).join(\",\")))),s=i(0);for(let t=1;t<e;t++)if(!P(s,i(t)))return;return Array.from(s).map((t=>t.split(\",\"))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins(\"beforeLayout\",{cancelable:!0}))return;as.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&\"chartArea\"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins(\"afterLayout\")}_updateDatasets(t){if(!1!==this.notifyPlugins(\"beforeDatasetsUpdate\",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t<e;++t)this.getDatasetMeta(t).controller.configure();for(let e=0,i=this.data.datasets.length;e<i;++e)this._updateDataset(e,S(t)?t({datasetIndex:e}):t);this.notifyPlugins(\"afterDatasetsUpdate\",{mode:t})}}_updateDataset(t,e){const i=this.getDatasetMeta(t),s={meta:i,index:t,mode:e,cancelable:!0};!1!==this.notifyPlugins(\"beforeDatasetUpdate\",s)&&(i.controller._update(e),s.cancelable=!1,this.notifyPlugins(\"afterDatasetUpdate\",s))}render(){!1!==this.notifyPlugins(\"beforeRender\",{cancelable:!0})&&(xt.has(this)?this.attached&&!xt.running(this)&&xt.start(this):(this.draw(),wn({chart:this})))}draw(){let t;if(this._resizeBeforeDraw){const{width:t,height:e}=this._resizeBeforeDraw;this._resize(t,e),this._resizeBeforeDraw=null}if(this.clear(),this.width<=0||this.height<=0)return;if(!1===this.notifyPlugins(\"beforeDraw\",{cancelable:!0}))return;const e=this._layers;for(t=0;t<e.length&&e[t].z<=0;++t)e[t].draw(this.chartArea);for(this._drawDatasets();t<e.length;++t)e[t].draw(this.chartArea);this.notifyPlugins(\"afterDraw\")}_getSortedDatasetMetas(t){const e=this._sortedMetasets,i=[];let s,n;for(s=0,n=e.length;s<n;++s){const n=e[s];t&&!n.visible||i.push(n)}return i}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(!1===this.notifyPlugins(\"beforeDatasetsDraw\",{cancelable:!0}))return;const t=this.getSortedVisibleDatasetMetas();for(let e=t.length-1;e>=0;--e)this._drawDataset(t[e]);this.notifyPlugins(\"afterDatasetsDraw\")}_drawDataset(t){const e=this.ctx,i=t._clip,s=!i.disabled,n=function(t,e){const{xScale:i,yScale:s}=t;return i&&s?{left:On(i,e,\"left\"),right:On(i,e,\"right\"),top:On(s,e,\"top\"),bottom:On(s,e,\"bottom\")}:e}(t,this.chartArea),o={meta:t,index:t.index,cancelable:!0};!1!==this.notifyPlugins(\"beforeDatasetDraw\",o)&&(s&&Ie(e,{left:!1===i.left?0:n.left-i.left,right:!1===i.right?this.width:n.right+i.right,top:!1===i.top?0:n.top-i.top,bottom:!1===i.bottom?this.height:n.bottom+i.bottom}),t.controller.draw(),s&&ze(e),o.cancelable=!1,this.notifyPlugins(\"afterDatasetDraw\",o))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Xi.modes[e];return\"function\"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:\"chart\"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return\"boolean\"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?\"show\":\"hide\",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),xt.remove(this),t=0,e=this.data.datasets.length;t<e;++t)this._destroyDatasetMeta(t)}destroy(){this.notifyPlugins(\"beforeDestroy\");const{canvas:t,ctx:e}=this;this._stop(),this.config.clearCache(),t&&(this.unbindEvents(),Te(t,e),this.platform.releaseContext(e),this.canvas=null,this.ctx=null),delete Pn[this.id],this.notifyPlugins(\"afterDestroy\")}toBase64Image(...t){return this.canvas.toDataURL(...t)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const t=this._listeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s(\"attach\",a),this.attached=!0,this.resize(),i(\"resize\",n),i(\"detach\",o)};o=()=>{this.attached=!1,s(\"resize\",n),this._stop(),this._resize(0,0),i(\"attach\",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?\"set\":\"remove\";let n,o,a,r;for(\"dataset\"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller[\"_\"+s+\"DatasetHoverStyle\"]()),a=0,r=t.length;a<r;++a){o=t[a];const e=o&&this.getDatasetMeta(o.datasetIndex).controller;e&&e[s+\"HoverStyle\"](o.element,o.datasetIndex,o.index)}}getActiveElements(){return this._active||[]}setActiveElements(t){const e=this._active||[],i=t.map((({datasetIndex:t,index:e})=>{const i=this.getDatasetMeta(t);if(!i)throw new Error(\"No dataset found at index \"+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins(\"beforeEvent\",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins(\"afterEvent\",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&\"mouseout\"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if(\"mouseout\"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Tn(){return u(An.instances,(t=>t._plugins.invalidate()))}function Ln(){throw new Error(\"This method is not implemented: Check that a complete date adapter is provided.\")}class En{static override(t){Object.assign(En.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return Ln()}parse(){return Ln()}format(){return Ln()}add(){return Ln()}diff(){return Ln()}startOf(){return Ln()}endOf(){return Ln()}}var Rn={_date:En};function In(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;e<n;e++)s=s.concat(i[e].controller.getAllParsedValues(t));t._cache.$bar=lt(s.sort(((t,e)=>t-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;s<n;++s)o=e.getPixelForValue(i[s]),l();for(a=void 0,s=0,n=e.ticks.length;s<n;++s)o=e.getPixelForTick(s),l();return r}function zn(t,e,i,s){return n(t)?function(t,e,i,s){const n=i.parse(t[0],s),o=i.parse(t[1],s),a=Math.min(n,o),r=Math.max(n,o);let l=a,h=r;Math.abs(a)>Math.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Fn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;h<c;++h)u=e[h],d={},d[n.axis]=r||n.parse(a[h],h),l.push(zn(u,d,o,h));return l}function Vn(t){return t&&void 0!==t.barStart&&void 0!==t.barEnd}function Bn(t,e,i,s){let n=e.borderSkipped;const o={};if(!n)return void(t.borderSkipped=o);if(!0===n)return void(t.borderSkipped={top:!0,right:!0,bottom:!0,left:!0});const{start:a,end:r,reverse:l,top:h,bottom:c}=function(t){let e,i,s,n,o;return t.horizontal?(e=t.base>t.x,i=\"left\",s=\"right\"):(e=t.base<t.y,i=\"bottom\",s=\"top\"),e?(n=\"end\",o=\"start\"):(n=\"start\",o=\"end\"),{start:i,end:s,reverse:e,top:n,bottom:o}}(t);\"middle\"===n&&i&&(t.enableBorderRadius=!0,(i._top||0)===s?n=h:(i._bottom||0)===s?n=c:(o[Wn(c,a,r,l)]=!0,n=h)),o[Wn(n,a,r,l)]=!0,t.borderSkipped=o}function Wn(t,e,i,s){var n,o,a;return s?(a=i,t=Nn(t=(n=t)===(o=e)?a:n===a?o:n,i,e)):t=Nn(t,e,i),t}function Nn(t,e,i){return\"start\"===t?e:\"end\"===t?i:t}function Hn(t,{inflateAmount:e},i){t.inflateAmount=\"auto\"===e?1===i?.33:0:e}class jn extends Ns{static id=\"doughnut\";static defaults={datasetElementType:!1,dataElementType:\"arc\",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:\"number\",properties:[\"circumference\",\"endAngle\",\"innerRadius\",\"outerRadius\",\"startAngle\",\"x\",\"y\",\"offset\",\"borderWidth\",\"spacing\"]}},cutout:\"50%\",rotation:0,circumference:360,radius:\"100%\",spacing:0,indexAxis:\"r\"};static descriptors={_scriptable:t=>\"spacing\"!==t,_indexable:t=>\"spacing\"!==t&&!t.startsWith(\"borderDash\")&&!t.startsWith(\"hoverBorderDash\")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t=\"value\"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;n<a;++n)s._parsed[n]=r(n)}}_getRotation(){return $(this.options.rotation-90)}_getCircumference(){return $(this.options.circumference)}_getRotationExtents(){let t=O,e=-O;for(let i=0;i<this.chart.data.datasets.length;++i)if(this.chart.isDatasetVisible(i)&&this.chart.getDatasetMeta(i).type===this._type){const s=this.chart.getDatasetMeta(i).controller,n=s._getRotation(),o=s._getCircumference();t=Math.min(t,n),e=Math.max(e,n+o)}return{rotation:t,circumference:e-t}}update(t){const e=this.chart,{chartArea:i}=e,s=this._cachedMeta,n=s.data,o=this.getMaxBorderWidth()+this.getMaxOffset(n)+this.options.spacing,a=Math.max((Math.min(i.width,i.height)-o)/2,0),r=Math.min(h(this.options.cutout,a),1),l=this._getRingWeight(this.index),{circumference:d,rotation:u}=this._getRotationExtents(),{ratioX:f,ratioY:g,offsetX:p,offsetY:m}=function(t,e,i){let s=1,n=1,o=0,a=0;if(e<O){const r=t,l=r+e,h=Math.cos(r),c=Math.sin(r),d=Math.cos(l),u=Math.sin(l),f=(t,e,s)=>Z(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>Z(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),b=g(C,h,d),x=g(C+E,c,u);s=(p-b)/2,n=(m-x)/2,o=-(p+b)/2,a=-(m+x)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),b=(i.width-o)/f,x=(i.height-o)/g,_=Math.max(Math.min(b,x)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n=\"reset\"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p<e;++p)m+=this._circumference(p,n);for(p=e;p<e+i;++p){const e=this._circumference(p,n),i=t[p],o={x:l+this.offsetX,y:h+this.offsetY,startAngle:m,endAngle:m+e,circumference:e,outerRadius:u,innerRadius:d};g&&(o.options=f||this.resolveDataElementOptions(p,i.active?\"active\":s)),m+=e,this.updateElement(i,p,o,s)}}calculateTotal(){const t=this._cachedMeta,e=t.data;let i,s=0;for(i=0;i<e.length;i++){const n=t._parsed[i];null===n||isNaN(n)||!this.chart.getDataVisibility(i)||e[i].hidden||(s+=Math.abs(n))}return s}calculateCircumference(t){const e=this._cachedMeta.total;return e>0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||\"\",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s<n;++s)if(i.isDatasetVisible(s)){o=i.getDatasetMeta(s),t=o.data,a=o.controller;break}if(!t)return 0;for(s=0,n=t.length;s<n;++s)r=a.resolveDataElementOptions(s),\"inner\"!==r.borderAlign&&(e=Math.max(e,r.borderWidth||0,r.hoverBorderWidth||0));return e}getMaxOffset(t){let e=0;for(let i=0,s=t.length;i<s;++i){const t=this.resolveDataElementOptions(i);e=Math.max(e,t.offset||0,t.hoverOffset||0)}return e}_getRingWeightOffset(t){let e=0;for(let i=0;i<t;++i)this.chart.isDatasetVisible(i)&&(e+=this._getRingWeight(i));return e}_getRingWeight(t){return Math.max(l(this.chart.data.datasets[t].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}class $n extends Ns{static id=\"polarArea\";static defaults={dataElementType:\"arc\",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:\"number\",properties:[\"x\",\"y\",\"startAngle\",\"endAngle\",\"innerRadius\",\"outerRadius\"]}},indexAxis:\"r\",startAngle:0};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:\"radialLinear\",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||\"\",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(s<e.min&&(e.min=s),s>e.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n=\"reset\"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d<e;++d)u+=this._computeAngle(d,s,f);for(d=e;d<e+i;d++){const e=t[d];let i=u,g=u+this._computeAngle(d,s,f),p=o.getDataVisibility(d)?r.getDistanceFromCenterForValue(this.getParsed(d).r):0;u=g,n&&(a.animateScale&&(p=0),a.animateRotate&&(i=g=c));const m={x:l,y:h,innerRadius:0,outerRadius:p,startAngle:i,endAngle:g,options:this.resolveDataElementOptions(d,e.active?\"active\":s)};this.updateElement(e,d,m,s)}}countVisibleElements(){const t=this._cachedMeta;let e=0;return t.data.forEach(((t,i)=>{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Yn=Object.freeze({__proto__:null,BarController:class extends Ns{static id=\"bar\";static defaults={datasetElementType:!1,dataElementType:\"bar\",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:\"number\",properties:[\"x\",\"y\",\"base\",\"width\",\"height\"]}}};static overrides={scales:{_index_:{type:\"category\",offset:!0,grid:{offset:!0}},_value_:{type:\"linear\",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Fn(t,e,i,s)}parseArrayData(t,e,i,s){return Fn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a=\"x\",yAxisKey:r=\"y\"}=this._parsing,l=\"x\"===n.axis?a:r,h=\"x\"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;d<u;++d)g=e[d],f={},f[n.axis]=n.parse(M(g,l),d),c.push(zn(M(g,h),f,o,d));return c}updateRangeFromParsed(t,e,i,s){super.updateRangeFromParsed(t,e,i,s);const n=i._custom;n&&e===this._cachedMeta.vScale&&(t.min=Math.min(t.min,n.min),t.max=Math.max(t.max,n.max))}getMaxOverflow(){return 0}getLabelAndValue(t){const e=this._cachedMeta,{iScale:i,vScale:s}=e,n=this.getParsed(t),o=n._custom,a=Vn(o)?\"[\"+o.start+\", \"+o.end+\"]\":\"\"+s.getLabelForValue(n[s.axis]);return{label:\"\"+i.getLabelForValue(n[i.axis]),value:a}}initialize(){this.enableOptionSharing=!0,super.initialize();this._cachedMeta.stack=this.getDataset().stack}update(t){const e=this._cachedMeta;this.updateElements(e.data,0,e.data.length,t)}updateElements(t,e,i,n){const o=\"reset\"===n,{index:a,_cachedMeta:{vScale:r}}=this,l=r.getBasePixel(),h=r.isHorizontal(),c=this._getRuler(),{sharedOptions:d,includeOptions:u}=this._getSharedOptions(e,n);for(let f=e;f<e+i;f++){const e=this.getParsed(f),i=o||s(e[r.axis])?{base:l,head:l}:this._calculateBarValuePixels(f),g=this._calculateBarIndexPixels(f,c),p=(e._stacks||{})[r.axis],m={horizontal:h,base:i.base,enableBorderRadius:!p||Vn(e._custom)||a===p._top||a===p._bottom,x:h?i.head:g.center,y:h?g.center:i.head,height:h?g.size:Math.abs(i.size),width:h?Math.abs(i.size):g.size};u&&(m.options=d||this.resolveDataElementOptions(f,t[f].active?\"active\":n));const b=m.options||t[f].options;Bn(m,b,p,a),Hn(m,b,c.ratio),this.updateElement(t[f],f,m,n)}}_getStacks(t,e){const{iScale:i}=this._cachedMeta,n=i.getMatchingVisibleMetas(this._type).filter((t=>t.controller.options.grouped)),o=i.options.stacked,a=[],r=t=>{const i=t.controller.getParsed(e),n=i&&i[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!r(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n<o;++n)s.push(i.getPixelForValue(this.getParsed(n)[i.axis],n));const a=t.barThickness;return{min:a||In(e),pixels:s,start:i._startPixel,end:i._endPixel,stackCount:this._getStackCount(),scale:i,grouped:t.grouped,ratio:a?1:t.categoryPercentage*t.barPercentage}}_calculateBarValuePixels(t){const{_cachedMeta:{vScale:e,_stacked:i,index:n},options:{base:o,minBarLength:a}}=this,r=o||0,l=this.getParsed(t),h=l._custom,c=Vn(h);let d,u,f=l[e.axis],g=0,p=i?this.applyStack(e,l,i):f;p!==f&&(g=p-f,p=f),c&&(f=h.barStart,p=h.barEnd-h.barStart,0!==f&&F(f)!==F(h.barEnd)&&(g=0),g+=f);const m=s(o)||c?g:o;let b=e.getPixelForValue(m);if(d=this.chart.getDataVisibility(t)?e.getPixelForValue(g+p):b,u=d-b,Math.abs(u)<a){u=function(t,e,i){return 0!==t?F(t):(e.isHorizontal()?1:-1)*(e.min>=i?1:-1)}(u,e,r)*a,f===r&&(b-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);b=Math.max(Math.min(b,h),o),d=b+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(b))}if(b===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;b+=t,u-=t}return{size:u,base:b,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,l=\"flex\"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t<n.length-1?n[t+1]:null;const l=i.categoryPercentage;null===a&&(a=o-(null===r?e.end-e.start:r-o)),null===r&&(r=o+o-a);const h=o-(o-Math.min(a,r))/2*l;return{chunk:Math.abs(r-a)/2*l/s,ratio:i.barPercentage,start:h}}(t,e,n,i):function(t,e,i,n){const o=i.barThickness;let a,r;return s(o)?(a=e.min*i.categoryPercentage,r=i.barPercentage):(a=o*n,r=1),{chunk:a/n,ratio:r,start:e.pixels[t]-a/2}}(t,e,n,i),c=this._getStackIndex(this.index,this._cachedMeta.stack,o?t:void 0);r=l.start+l.chunk*c+l.chunk/2,h=Math.min(a,l.chunk*l.ratio)}else r=i.getPixelForValue(this.getParsed(t)[i.axis],t),h=Math.min(a,e.min*e.ratio);return{base:r-h/2,head:r+h/2,center:r,size:h}}draw(){const t=this._cachedMeta,e=t.vScale,i=t.data,s=i.length;let n=0;for(;n<s;++n)null!==this.getParsed(n)[e.axis]&&i[n].draw(this._ctx)}},BubbleController:class extends Ns{static id=\"bubble\";static defaults={datasetElementType:!1,dataElementType:\"point\",animations:{numbers:{type:\"number\",properties:[\"x\",\"y\",\"borderWidth\",\"radius\"]}}};static overrides={scales:{x:{type:\"linear\"},y:{type:\"linear\"}}};initialize(){this.enableOptionSharing=!0,super.initialize()}parsePrimitiveData(t,e,i,s){const n=super.parsePrimitiveData(t,e,i,s);for(let t=0;t<n.length;t++)n[t]._custom=this.resolveDataElementOptions(t+i).radius;return n}parseArrayData(t,e,i,s){const n=super.parseArrayData(t,e,i,s);for(let t=0;t<n.length;t++){const s=e[i+t];n[t]._custom=l(s[2],this.resolveDataElementOptions(t+i).radius)}return n}parseObjectData(t,e,i,s){const n=super.parseObjectData(t,e,i,s);for(let t=0;t<n.length;t++){const s=e[i+t];n[t]._custom=l(s&&s.r&&+s.r,this.resolveDataElementOptions(t+i).radius)}return n}getMaxOverflow(){const t=this._cachedMeta.data;let e=0;for(let i=t.length-1;i>=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||\"\",value:\"(\"+a+\", \"+r+(l?\", \"+l:\"\")+\")\"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n=\"reset\"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d<e+i;d++){const e=t[d],i=!n&&this.getParsed(d),u={},f=u[h]=n?o.getPixelForDecimal(.5):o.getPixelForValue(i[h]),g=u[c]=n?a.getBasePixel():a.getPixelForValue(i[c]);u.skip=isNaN(f)||isNaN(g),l&&(u.options=r||this.resolveDataElementOptions(d,e.active?\"active\":s),n&&(u.options.radius=0)),this.updateElement(e,d,u,s)}}resolveDataElementOptions(t,e){const i=this.getParsed(t);let s=super.resolveDataElementOptions(t,e);s.$shared&&(s=Object.assign({},s,{$shared:!1}));const n=s.radius;return\"active\"!==e&&(s.radius=0),s.radius+=l(i&&i._custom,n),s}},DoughnutController:jn,LineController:class extends Ns{static id=\"line\";static defaults={datasetElementType:\"line\",dataElementType:\"point\",showLine:!0,spanGaps:!1};static overrides={scales:{_index_:{type:\"category\"},_value_:{type:\"linear\"}}};initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){const e=this._cachedMeta,{dataset:i,data:s=[],_dataset:n}=e,o=this.chart._animationsDisabled;let{start:a,count:r}=pt(e,s,o);this._drawStart=a,this._drawCount=r,mt(e)&&(a=0,r=s.length),i._chart=this.chart,i._datasetIndex=this.index,i._decimated=!!n._decimated,i.points=s;const l=this.resolveDatasetElementOptions(t);this.options.showLine||(l.borderWidth=0),l.segment=this.options.segment,this.updateElement(i,void 0,{animated:!o,options:l},t),this.updateElements(s,a,r,t)}updateElements(t,e,i,n){const o=\"reset\"===n,{iScale:a,vScale:r,_stacked:l,_dataset:h}=this._cachedMeta,{sharedOptions:c,includeOptions:d}=this._getSharedOptions(e,n),u=a.axis,f=r.axis,{spanGaps:g,segment:p}=this.options,m=N(g)?g:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||\"none\"===n,x=e+i,_=t.length;let y=e>0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=b?g:{};if(i<e||i>=x){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?\"active\":n)),b||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends jn{static id=\"pie\";static defaults={cutout:0,rotation:0,circumference:360,radius:\"100%\"}},PolarAreaController:$n,RadarController:class extends Ns{static id=\"radar\";static defaults={datasetElementType:\"line\",dataElementType:\"point\",indexAxis:\"r\",showLine:!0,elements:{line:{fill:\"start\"}}};static overrides={aspectRatio:1,scales:{r:{type:\"radialLinear\"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:\"\"+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,\"resize\"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o=\"reset\"===s;for(let a=e;a<e+i;a++){const e=t[a],i=this.resolveDataElementOptions(a,e.active?\"active\":s),r=n.getPointPositionForValue(a,this.getParsed(a).r),l=o?n.xCenter:r.x,h=o?n.yCenter:r.y,c={x:l,y:h,angle:r.angle,skip:isNaN(l)||isNaN(h),options:i};this.updateElement(e,a,c,s)}}},ScatterController:class extends Ns{static id=\"scatter\";static defaults={datasetElementType:!1,dataElementType:\"point\",showLine:!1,fill:!1};static overrides={interaction:{mode:\"point\"},scales:{x:{type:\"linear\"},y:{type:\"linear\"}}};getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y);return{label:i[t]||\"\",value:\"(\"+a+\", \"+r+\")\"}}update(t){const e=this._cachedMeta,{data:i=[]}=e,s=this.chart._animationsDisabled;let{start:n,count:o}=pt(e,i,s);if(this._drawStart=n,this._drawCount=o,mt(e)&&(n=0,o=i.length),this.options.showLine){this.datasetElementType||this.addElements();const{dataset:n,_dataset:o}=e;n._chart=this.chart,n._datasetIndex=this.index,n._decimated=!!o._decimated,n.points=i;const a=this.resolveDatasetElementOptions(t);a.segment=this.options.segment,this.updateElement(n,void 0,{animated:!s,options:a},t)}else this.datasetElementType&&(delete e.dataset,this.datasetElementType=!1);this.updateElements(i,n,o,t)}addElements(){const{showLine:t}=this.options;!this.datasetElementType&&t&&(this.datasetElementType=this.chart.registry.getElement(\"line\")),super.addElements()}updateElements(t,e,i,n){const o=\"reset\"===n,{iScale:a,vScale:r,_stacked:l,_dataset:h}=this._cachedMeta,c=this.resolveDataElementOptions(e,n),d=this.getSharedOptions(c),u=this.includeOptions(n,d),f=a.axis,g=r.axis,{spanGaps:p,segment:m}=this.options,b=N(p)?p:Number.POSITIVE_INFINITY,x=this.chart._animationsDisabled||o||\"none\"===n;let _=e>0&&this.getParsed(e-1);for(let c=e;c<e+i;++c){const e=t[c],i=this.getParsed(c),p=x?e:{},y=s(i[g]),v=p[f]=a.getPixelForValue(i[f],c),M=p[g]=o||y?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,i,l):i[g],c);p.skip=isNaN(v)||isNaN(M)||y,p.stop=c>0&&Math.abs(i[f]-_[f])>b,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?\"active\":n)),x||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Un(t,e,i,s){const n=vi(t.options.borderRadius,[\"outerStart\",\"outerEnd\",\"innerStart\",\"innerEnd\"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return J(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:J(n.innerStart,0,a),innerEnd:J(n.innerEnd,0,a)}}function Xn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function qn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,b=n-p-f,{outerStart:x,outerEnd:_,innerStart:y,innerEnd:v}=Un(e,u,d,b-m),M=d-x,w=d-_,k=m+x/M,S=b-_/w,P=u+y,D=u+v,O=m+y/P,A=b-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=Xn(w,S,a,r);t.arc(e.x,e.y,_,S,b+E)}const i=Xn(D,b,a,r);if(t.lineTo(i.x,i.y),v>0){const e=Xn(D,A,a,r);t.arc(e.x,e.y,v,b+E,A+Math.PI)}const s=(b-v/u+(m+y/u))/2;if(t.arc(a,r,u,b-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=Xn(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=Xn(M,m,a,r);if(t.lineTo(n.x,n.y),x>0){const e=Xn(M,k,a,r);t.arc(e.x,e.y,x,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function Kn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u}=l,f=\"inner\"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,f?(t.lineWidth=2*h,t.lineJoin=c||\"round\"):(t.lineWidth=h,t.lineJoin=c||\"bevel\");let g=e.endAngle;if(o){qn(t,e,i,s,g,n);for(let e=0;e<o;++e)t.stroke();isNaN(r)||(g=a+(r%O||O))}f&&function(t,e,i){const{startAngle:s,pixelMargin:n,x:o,y:a,outerRadius:r,innerRadius:l}=e;let h=n/r;t.beginPath(),t.arc(o,a,r,s-h,i+h),l>n?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,g),o||(qn(t,e,i,s,g,n),t.stroke())}function Gn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Zn(t,e,i){t.lineTo(i.x,i.y)}function Jn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=n<a&&o<a||n>r&&o>r;return{count:s,start:l,loop:e.loop,ilen:h<l&&!c?s+h-l:h-l}}function Qn(t,e,i,s){const{points:n,options:o}=e,{count:a,start:r,loop:l,ilen:h}=Jn(n,i,s),c=function(t){return t.stepped?Fe:t.tension||\"monotone\"===t.cubicInterpolationMode?Ve:Zn}(o);let d,u,f,{move:g=!0,reverse:p}=s||{};for(d=0;d<=h;++d)u=n[(r+(p?h-d:d))%a],u.skip||(g?(t.moveTo(u.x,u.y),g=!1):c(t,f,u,p,o.stepped),f=u);return l&&(u=n[(r+(p?h:0))%a],c(t,f,u,p,o.stepped)),!!l}function to(t,e,i,s){const n=e.points,{count:o,start:a,ilen:r}=Jn(n,i,s),{move:l=!0,reverse:h}=s||{};let c,d,u,f,g,p,m=0,b=0;const x=t=>(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[x(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[x(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(i<f?f=i:i>g&&(g=i),m=(b*m+e)/++b):(_(),t.lineTo(e,i),u=s,b=0,f=g=i),p=i}_()}function eo(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||\"monotone\"===e.cubicInterpolationMode||e.stepped||i)?to:Qn}const io=\"function\"==typeof Path2D;function so(t,e,i,s){io&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Gn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=eo(e);for(const r of n)Gn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class no extends Hs{static id=\"line\";static defaults={borderCapStyle:\"butt\",borderDash:[],borderDashOffset:0,borderJoinStyle:\"miter\",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:\"default\",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:\"backgroundColor\",borderColor:\"borderColor\"};static descriptors={_scriptable:!0,_indexable:t=>\"borderDash\"!==t&&\"fill\"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||\"monotone\"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||\"monotone\"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l<h;++l){const{start:h,end:c}=o[l],d=n[h],u=n[c];if(d===u){a.push(d);continue}const f=r(d,u,Math.abs((s-d[e])/(u[e]-d[e])),i.stepped);f[e]=t[e],a.push(f)}return 1===a.length?a[0]:a}pathSegment(t,e,i){return eo(this)(t,this,e,i)}path(t,e,i){const s=this.segments,n=eo(this);let o=this._loop;e=e||0,i=i||this.points.length-e;for(const a of s)o&=n(t,this,a,{start:e,end:e+i-1});return!!o}draw(t,e,i,s){const n=this.options||{};(this.points||[]).length&&n.borderWidth&&(t.save(),so(t,this,i,s),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}function oo(t,e,i,s){const n=t.options,{[i]:o}=t.getProps([i],s);return Math.abs(e-o)<n.radius+n.hitRadius}function ao(t,e){const{x:i,y:s,base:n,width:o,height:a}=t.getProps([\"x\",\"y\",\"base\",\"width\",\"height\"],e);let r,l,h,c,d;return t.horizontal?(d=a/2,r=Math.min(i,n),l=Math.max(i,n),h=s-d,c=s+d):(d=o/2,r=i-d,l=i+d,h=Math.min(s,n),c=Math.max(s,n)),{left:r,top:h,right:l,bottom:c}}function ro(t,e,i,s){return t?0:J(e,i,s)}function lo(t){const e=ao(t),i=e.right-e.left,s=e.bottom-e.top,n=function(t,e,i){const s=t.options.borderWidth,n=t.borderSkipped,o=Mi(s);return{t:ro(n.top,o.top,0,i),r:ro(n.right,o.right,0,e),b:ro(n.bottom,o.bottom,0,i),l:ro(n.left,o.left,0,e)}}(t,i/2,s/2),a=function(t,e,i){const{enableBorderRadius:s}=t.getProps([\"enableBorderRadius\"]),n=t.options.borderRadius,a=wi(n),r=Math.min(e,i),l=t.borderSkipped,h=s||o(n);return{topLeft:ro(!h||l.top||l.left,a.topLeft,0,r),topRight:ro(!h||l.top||l.right,a.topRight,0,r),bottomLeft:ro(!h||l.bottom||l.left,a.bottomLeft,0,r),bottomRight:ro(!h||l.bottom||l.right,a.bottomRight,0,r)}}(t,i/2,s/2);return{outer:{x:e.left,y:e.top,w:i,h:s,radius:a},inner:{x:e.left+n.l,y:e.top+n.t,w:i-n.l-n.r,h:s-n.t-n.b,radius:{topLeft:Math.max(0,a.topLeft-Math.max(n.t,n.l)),topRight:Math.max(0,a.topRight-Math.max(n.t,n.r)),bottomLeft:Math.max(0,a.bottomLeft-Math.max(n.b,n.l)),bottomRight:Math.max(0,a.bottomRight-Math.max(n.b,n.r))}}}}function ho(t,e,i,s){const n=null===e,o=null===i,a=t&&!(n&&o)&&ao(t,s);return a&&(n||tt(e,a.left,a.right))&&(o||tt(i,a.top,a.bottom))}function co(t,e){t.rect(e.x,e.y,e.w,e.h)}function uo(t,e,i={}){const s=t.x!==i.x?-e:0,n=t.y!==i.y?-e:0,o=(t.x+t.w!==i.x+i.w?e:0)-s,a=(t.y+t.h!==i.y+i.h?e:0)-n;return{x:t.x+s,y:t.y+n,w:t.w+o,h:t.h+a,radius:t.radius}}var fo=Object.freeze({__proto__:null,ArcElement:class extends Hs{static id=\"arc\";static defaults={borderAlign:\"center\",borderColor:\"#fff\",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0};static defaultRoutes={backgroundColor:\"backgroundColor\"};static descriptors={_scriptable:!0,_indexable:t=>\"borderDash\"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps([\"x\",\"y\"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps([\"startAngle\",\"endAngle\",\"innerRadius\",\"outerRadius\",\"circumference\"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a)>=O||Z(n,a,r),g=tt(o,h+u,c+u);return f&&g}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps([\"x\",\"y\",\"startAngle\",\"endAngle\",\"innerRadius\",\"outerRadius\"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin=\"inner\"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){qn(t,e,i,s,l,n);for(let e=0;e<o;++e)t.fill();isNaN(r)||(l=a+(r%O||O))}qn(t,e,i,s,l,n),t.fill()}(t,this,r,n,o),Kn(t,this,r,n,o),t.restore()}},BarElement:class extends Hs{static id=\"bar\";static defaults={borderSkipped:\"start\",borderWidth:0,borderRadius:0,inflateAmount:\"auto\",pointStyle:void 0};static defaultRoutes={backgroundColor:\"backgroundColor\",borderColor:\"borderColor\"};constructor(t){super(),this.options=void 0,this.horizontal=void 0,this.base=void 0,this.width=void 0,this.height=void 0,this.inflateAmount=void 0,t&&Object.assign(this,t)}draw(t){const{inflateAmount:e,options:{borderColor:i,backgroundColor:s}}=this,{inner:n,outer:o}=lo(this),a=(r=o.radius).topLeft||r.topRight||r.bottomLeft||r.bottomRight?He:co;var r;t.save(),o.w===n.w&&o.h===n.h||(t.beginPath(),a(t,uo(o,e,n)),t.clip(),a(t,uo(n,-e,o)),t.fillStyle=i,t.fill(\"evenodd\")),t.beginPath(),a(t,uo(n,e)),t.fillStyle=s,t.fill(),t.restore()}inRange(t,e,i){return ho(this,t,e,i)}inXRange(t,e){return ho(this,t,null,e)}inYRange(t,e){return ho(this,null,t,e)}getCenterPoint(t){const{x:e,y:i,base:s,horizontal:n}=this.getProps([\"x\",\"y\",\"base\",\"horizontal\"],t);return{x:n?(e+s)/2:e,y:n?i:(i+s)/2}}getRange(t){return\"x\"===t?this.width/2:this.height/2}},LineElement:no,PointElement:class extends Hs{static id=\"point\";parsed;skip;stop;static defaults={borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:\"circle\",radius:3,rotation:0};static defaultRoutes={backgroundColor:\"backgroundColor\",borderColor:\"borderColor\"};constructor(t){super(),this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.options,{x:n,y:o}=this.getProps([\"x\",\"y\"],i);return Math.pow(t-n,2)+Math.pow(e-o,2)<Math.pow(s.hitRadius+s.radius,2)}inXRange(t,e){return oo(this,t,\"x\",e)}inYRange(t,e){return oo(this,t,\"y\",e)}getCenterPoint(t){const{x:e,y:i}=this.getProps([\"x\",\"y\"],t);return{x:e,y:i}}size(t){let e=(t=t||this.options||{}).radius||0;e=Math.max(e,e&&t.hoverRadius||0);return 2*(e+(e&&t.borderWidth||0))}draw(t,e){const i=this.options;this.skip||i.radius<.1||!Re(this,e,this.size(i)/2)||(t.strokeStyle=i.borderColor,t.lineWidth=i.borderWidth,t.fillStyle=i.backgroundColor,Le(t,i,this.x,this.y))}getRange(){const t=this.options||{};return t.radius+t.hitRadius}}});function go(t,e,i,s){const n=t.indexOf(e);if(-1===n)return((t,e,i,s)=>(\"string\"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function po(t){const e=this.getLabels();return t>=0&&t<e.length?e[t]:t}function mo(t,e,{horizontal:i,minRotation:s}){const n=$(s),o=(i?Math.sin(n):Math.cos(n))||.001,a=.75*e*(\"\"+t).length;return Math.min(e/o,a)}class bo extends Js{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return s(t)||(\"number\"==typeof t||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){const{beginAtZero:t}=this.options,{minDefined:e,maxDefined:i}=this.getUserBounds();let{min:s,max:n}=this;const o=t=>s=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,b=!s(a),x=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!b&&!x)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),\"ticks\"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),b&&x&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=b?a:M,w=x?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(b&&(u&&M!==a?(i.push({value:a}),M<a&&D++,V(Math.round((M+D*S)*v)/v,a,mo(a,y,t))&&D++):M<a&&D++);D<k;++D){const t=Math.round((M+D*S)*v)/v;if(x&&t>r)break;i.push({value:t})}return x&&u&&w!==r?i.length&&V(i[i.length-1].value,r,mo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):x&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return\"ticks\"===t.bounds&&j(n,this,\"value\"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class xo extends bo{static id=\"linear\";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const _o=t=>Math.floor(z(t)),yo=(t,e)=>Math.pow(10,_o(t)+e);function vo(t){return 1===t/Math.pow(10,_o(t))}function Mo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function wo(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=_o(e);let o=function(t,e){let i=_o(e-t);for(;Mo(t,e,i)>10;)i++;for(;Mo(t,e,i)<10;)i--;return Math.min(i,_o(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f<i;)s.push({value:f,major:vo(f),significand:u}),u>=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:vo(g),significand:u}),s}class ko extends Js{static id=\"logarithmic\";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===yo(this.min,0)?yo(this.min,-1):yo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(yo(i,-1)),o(yo(s,1)))),i<=0&&n(yo(s,-1)),s<=0&&o(yo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=wo({min:this._userMin,max:this._userMax},this);return\"ticks\"===t.bounds&&j(e,this,\"value\"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?\"0\":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function So(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Po(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:t<s||t>n?{start:e-i,end:e}:{start:e,end:e+i}}function Do(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;u<a;u++){const a=r.setContext(t.getPointLabelContext(u));o[u]=a.padding;const f=t.getPointPosition(u,t.drawingArea+o[u],l),g=Si(a.font),p=(h=t.ctx,c=g,d=n(d=t._pointLabels[u])?d:[d],{w:Oe(h,c.string,d),h:d.length*c.lineHeight});s[u]=p;const m=G(t.getIndexAngle(u)+l),b=Math.round(Y(m));Co(i,e,m,Po(b,f.x,p.w,0,180),Po(b,f.y,p.h,90,270))}var h,c,d;t.setCenterPoint(e.l-i.l,i.r-e.r,e.t-i.t,i.b-e.b),t._pointLabelItems=function(t,e,i){const s=[],n=t._pointLabels.length,o=t.options,{centerPointLabels:a,display:r}=o.pointLabels,l={extra:So(o)/2,additionalAngle:a?C/n:0};let h;for(let o=0;o<n;o++){l.padding=i[o],l.size=e[o];const n=Oo(t,o,l);s.push(n),\"auto\"===r&&(n.visible=Ao(n,h),n.visible&&(h=n))}return s}(t,s,o)}function Co(t,e,i,s,n){const o=Math.abs(Math.sin(i)),a=Math.abs(Math.cos(i));let r=0,l=0;s.start<e.l?(r=(e.l-s.start)/o,t.l=Math.min(t.l,e.l-r)):s.end>e.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.start<e.t?(l=(e.t-n.start)/a,t.t=Math.min(t.t,e.t-l)):n.end>e.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Oo(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return\"center\";if(t<180)return\"left\";return\"right\"}(h),u=function(t,e,i){\"right\"===i?t-=e:\"center\"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function Ao(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function To(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Lo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;o<s;o++)i=t.getPointPosition(o,e),n.lineTo(i.x,i.y)}}class Eo extends bo{static id=\"radialLinear\";static defaults={display:!0,animate:!0,position:\"chartArea\",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:ae.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback:t=>t,padding:5,centerPointLabels:!1}};static defaultRoutes={\"angleLines.color\":\"borderColor\",\"pointLabels.color\":\"color\",\"ticks.color\":\"color\"};static descriptors={angleLines:{_fallback:\"grid\"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(So(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/So(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:\"\"})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Do(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t<e.length){const i=e[t];return function(t,e,i){return Ci(t,{label:i,index:e,type:\"pointLabel\"})}(this.getContext(),t,i)}}getPointPosition(t,e,i=0){const s=this.getIndexAngle(t)-E+i;return{x:Math.cos(s)*e+this.xCenter,y:Math.sin(s)*e+this.yCenter,angle:s}}getPointPositionForValue(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))}getBasePosition(t){return this.getPointPositionForValue(t||0,this.getBaseValue())}getPointLabelPosition(t){const{left:e,top:i,right:s,bottom:n}=this._pointLabelItems[t];return{left:e,top:i,right:s,bottom:n}}drawBackground(){const{backgroundColor:t,grid:{circular:e}}=this.options;if(t){const i=this.ctx;i.save(),i.beginPath(),Lo(this,this.getDistanceFromCenterForValue(this._endValue),e,this._pointLabels.length),i.closePath(),i.fillStyle=t,i.fill(),i.restore()}}drawGrid(){const t=this.ctx,e=this.options,{angleLines:i,grid:s,border:n}=e,o=this._pointLabels.length;let a,r,l;if(e.pointLabels.display&&function(t,e){const{ctx:i,options:{pointLabels:s}}=t;for(let n=e-1;n>=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));To(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;Ne(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:\"middle\"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash),o.lineDashOffset=n.dashOffset,o.beginPath(),Lo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.ticks.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign=\"center\",t.textBaseline=\"middle\",this.ticks.forEach(((s,a)=>{if(0===a&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}Ne(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Ro={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Io=Object.keys(Ro);function zo(t,e){return t-e}function Fo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return\"function\"==typeof n&&(l=n(l)),a(l)||(l=\"string\"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l=\"week\"!==o||!N(r)&&!0!==r?i.startOf(l,o):i.startOf(l,\"isoWeek\",r)),+l)}function Vo(t,e,i,s){const n=Io.length;for(let o=Io.indexOf(t);o<n-1;++o){const t=Ro[Io[o]],n=t.steps?t.steps:Number.MAX_SAFE_INTEGER;if(t.common&&Math.ceil((i-e)/(n*t.size))<=s)return Io[o]}return Io[n-1]}function Bo(t,e,i){if(i){if(i.length){const{lo:s,hi:n}=et(i,e);t[i[s]>=e?i[s]:i[n]]=!0}}else t[e]=!0}function Wo(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a<o;++a)r=e[a],n[r]=a,s.push({value:r,major:!1});return 0!==o&&i?function(t,e,i,s){const n=t._adapter,o=+n.startOf(e[0].value,s),a=e[e.length-1].value;let r,l;for(r=o;r<=a;r=+n.add(r,1,s))l=i[r],l>=0&&(e[l].major=!0);return e}(t,s,n,i):s}class No extends Js{static id=\"time\";static defaults={bounds:\"data\",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:\"millisecond\",displayFormats:{}},ticks:{source:\"auto\",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit=\"day\",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new Rn._date(t.adapters.date);s.init(e),x(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Fo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||\"day\";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),\"ticks\"===t.bounds&&\"labels\"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s=\"labels\"===i.source?this.getLabelTimestamps():this._generate();\"ticks\"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Vo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=Io.length-1;o>=Io.indexOf(i);o--){const i=Io[o];if(Ro[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return Io[i?Io.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&\"year\"!==this._unit?function(t){for(let e=Io.indexOf(t)+1,i=Io.length;e<i;++e)if(Ro[Io[e]].common)return Io[e]}(this._unit):void 0,this.initOffsets(s),t.reverse&&o.reverse(),Wo(this,o,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map((t=>+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=J(s,0,o),n=J(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Vo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r=\"week\"===o&&n.isoWeekday,h=N(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,\"isoWeek\",r)),f=+t.startOf(f,h?\"day\":o),t.diff(i,e,o)>1e5*a)throw new Error(e+\" and \"+i+\" are too far apart with stepSize of \"+a+\" \"+o);const g=\"data\"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d<i;d=+t.add(d,a,o),u++)Bo(c,d,g);return d!==i&&\"ticks\"!==s.bounds&&1!==u||Bo(c,d,g),Object.keys(c).sort(zo).map((t=>+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e<i;++e)s=t[e],s.label=this._tickFormatFunction(s.value,e,t)}getDecimalForValue(t){return null===t?NaN:(t-this.min)/(this.max-this.min)}getPixelForValue(t){const e=this._offsets,i=this.getDecimalForValue(t);return this.getPixelForDecimal((e.start+i)*e.factor)}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return this.min+i*(this.max-this.min)}_getLabelSize(t){const e=this.options.ticks,i=this.ctx.measureText(t).width,s=$(this.isHorizontal()?e.maxRotation:e.minRotation),n=Math.cos(s),o=Math.sin(s),a=this._resolveTickFontOptions(0).size;return{w:i*n+a*o,h:i*o+a*n}}_getLabelCapacity(t){const e=this.options.time,i=e.displayFormats,s=i[e.unit]||i.millisecond,n=this._tickFormatFunction(t,0,Wo(this,[t],this._majorUnit),s),o=this._getLabelSize(n),a=Math.floor(this.isHorizontal()?this.width/o.w:this.height/o.h)-1;return a>0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t<e;++t)i=i.concat(s[t].controller.getAllParsedValues(this));return this._cache.data=this.normalize(i)}getLabelTimestamps(){const t=this._cache.labels||[];let e,i;if(t.length)return t;const s=this.getLabels();for(e=0,i=s.length;e<i;++e)t.push(Fo(this,s[e]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return lt(t.sort(zo))}}function Ho(t,e,i){let s,n,o,a,r=0,l=t.length-1;i?(e>=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,\"pos\",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,\"time\",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var jo=Object.freeze({__proto__:null,CategoryScale:class extends Js{static id=\"category\";static defaults={ticks:{callback:po}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:J(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:go(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);\"ticks\"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return po.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return\"number\"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:xo,LogarithmicScale:ko,RadialLinearScale:Eo,TimeScale:No,TimeSeriesScale:class extends No{static id=\"timeseries\";static defaults=No.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=Ho(e,this.min),this._tableRange=Ho(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o<a;++o)l=t[o],l>=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;o<a;++o)h=s[o+1],r=s[o-1],l=s[o],Math.round((h+r)/2)!==l&&n.push({time:l,pos:o/(a-1)});return n}_generate(){const t=this.min,e=this.max;let i=super.getDataTimestamps();return i.includes(t)&&i.length||i.splice(0,0,t),i.includes(e)&&1!==i.length||i.push(e),i.sort(((t,e)=>t-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(Ho(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return Ho(this._table,i*this._tableRange+this._minPos,!0)}}});const $o=[\"rgb(54, 162, 235)\",\"rgb(255, 99, 132)\",\"rgb(255, 159, 64)\",\"rgb(255, 205, 86)\",\"rgb(75, 192, 192)\",\"rgb(153, 102, 255)\",\"rgb(201, 203, 207)\"],Yo=$o.map((t=>t.replace(\"rgb(\",\"rgba(\").replace(\")\",\", 0.5)\")));function Uo(t){return $o[t%$o.length]}function Xo(t){return Yo[t%Yo.length]}function qo(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof jn?e=function(t,e){return t.backgroundColor=t.data.map((()=>Uo(e++))),e}(i,e):n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Uo(e),t.backgroundColor=Xo(e),++e}(i,e))}}function Ko(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Go={id:\"colors\",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n;if(!i.forceOverride&&(Ko(s)||(a=n)&&(a.borderColor||a.backgroundColor)||o&&Ko(o)))return;var a;const r=qo(t);s.forEach(r)}};function Zo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,\"data\",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Jo(t){t.data.datasets.forEach((t=>{Zo(t)}))}var Qo={id:\"decimation\",defaults:{algorithm:\"min-max\",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Jo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if(\"y\"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if(\"linear\"!==c.type&&\"time\"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=J(it(e,o.axis,a).lo,0,i-1)),s=h?J(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Zo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,\"data\",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case\"lttb\":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;c<o-2;c++){let s,n=0,o=0;const h=Math.floor((c+1)*r)+1+e,m=Math.min(Math.floor((c+2)*r)+1,i)+e,b=m-h;for(s=h;s<m;s++)n+=t[s].x,o+=t[s].y;n/=b,o/=b;const x=Math.floor(c*r)+1+e,_=Math.min(Math.floor((c+1)*r)+1,i)+e,{x:y,y:v}=t[p];for(u=f=-1,s=x;s<_;s++)f=.5*Math.abs((y-n)*(t[s].y-v)-(y-t[s].x)*(o-v)),f>u&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case\"min-max\":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const b=[],x=e+i-1,_=t[e].x,y=t[x].x-_;for(o=e;o<e+i;++o){a=t[o],r=(a.x-_)/y*n,l=a.y;const e=0|r;if(e===h)l<f?(f=l,c=o):l>g&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&b.push({...t[e],x:p}),s!==u&&s!==i&&b.push({...t[s],x:p})}o>0&&i!==u&&b.push(t[i]),b.push(a),h=e,m=0,f=g=l,c=d=u=o}}return b}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Jo(t)}};function ta(t,e,i,s){if(s)return;let n=e[t],o=i[t];return\"angle\"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ea(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function ia(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function sa(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ea(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new no({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function na(t){return t&&!1!==t.fill}function oa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function aa(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return\"origin\";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){\"-\"!==t&&\"+\"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):[\"origin\",\"start\",\"end\",\"stack\",\"shape\"].indexOf(s)>=0&&s}function ra(t,e,i){const s=[];for(let n=0;n<i.length;n++){const o=i[n],{first:a,last:r,point:l}=la(o,e,\"x\");if(!(!l||a&&r))if(a)s.unshift(l);else if(t.push(l),!r)break}t.push(...s)}function la(t,e,i){const s=t.interpolate(e,i);if(!s)return{};const n=s[i],o=t.segments,a=t.points;let r=!1,l=!1;for(let t=0;t<o.length;t++){const e=o[t],s=a[e.start][i],h=a[e.end][i];if(tt(n,s,h)){r=n===s,l=n===h;break}}return{first:r,last:l,point:s}}class ha{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,i){const{x:s,y:n,radius:o}=this;return e=e||{start:0,end:O},t.arc(s,n,o,e.end,e.start,!0),!i.bounds}interpolate(t){const{x:e,y:i,radius:s}=this,n=t.angle;return{x:e+Math.cos(n)*s,y:i+Math.sin(n)*s,angle:n}}}function ca(t){const{chart:e,fill:i,line:s}=t;if(a(i))return function(t,e){const i=t.getDatasetMeta(e),s=i&&t.isDatasetVisible(e);return s?i.dataset:null}(e,i);if(\"stack\"===i)return function(t){const{scale:e,index:i,line:s}=t,n=[],o=s.segments,a=s.points,r=function(t,e){const i=[],s=t.getMatchingVisibleMetas(\"line\");for(let t=0;t<s.length;t++){const n=s[t];if(n.index===e)break;n.hidden||i.unshift(n.dataset)}return i}(e,i);r.push(sa({x:null,y:e.bottom},s));for(let t=0;t<o.length;t++){const e=o[t];for(let t=e.start;t<=e.end;t++)ra(n,a[t],r)}return new no({points:n,options:{}})}(t);if(\"shape\"===i)return!0;const n=function(t){const e=t.scale||{};if(e.getPointPositionForValue)return function(t){const{scale:e,fill:i}=t,s=e.options,n=e.getLabels().length,a=s.reverse?e.max:e.min,r=function(t,e,i){let s;return s=\"start\"===t?i:\"end\"===t?e.options.reverse?e.min:e.max:o(t)?t.value:e.getBaseValue(),s}(i,e,a),l=[];if(s.grid.circular){const t=e.getPointPositionForValue(0,a);return new ha({x:t.x,y:t.y,radius:e.getDistanceFromCenterForValue(r)})}for(let t=0;t<n;++t)l.push(e.getPointPositionForValue(t,r));return l}(t);return function(t){const{scale:e={},fill:i}=t,s=function(t,e){let i=null;return\"start\"===t?i=e.bottom:\"end\"===t?i=e.top:o(t)?i=e.getPixelForValue(t.value):e.getBasePixel&&(i=e.getBasePixel()),i}(i,e);if(a(s)){const t=e.isHorizontal();return{x:t?s:null,y:t?null:s}}return null}(t)}(t);return n instanceof ha?n:sa(n,s)}function da(t,e,i){const s=ca(e),{line:n,scale:o,axis:a}=e,r=n.options,l=r.fill,h=r.backgroundColor,{above:c=h,below:d=h}=l||{};s&&n.points.length&&(Ie(t,i),function(t,e){const{line:i,target:s,above:n,below:o,area:a,scale:r}=e,l=i._loop?\"angle\":e.axis;t.save(),\"x\"===l&&o!==n&&(ua(t,s,a.top),fa(t,{line:i,target:s,color:n,scale:r,property:l}),t.restore(),t.save(),ua(t,s,a.bottom));fa(t,{line:i,target:s,color:o,scale:r,property:l}),t.restore()}(t,{line:n,target:s,above:c,below:d,area:i,scale:o,axis:a}),ze(t))}function ua(t,e,i){const{segments:s,points:n}=e;let o=!0,a=!1;t.beginPath();for(const r of s){const{start:s,end:l}=r,h=n[s],c=n[ea(s,l,n)];o?(t.moveTo(h.x,h.y),o=!1):(t.lineTo(h.x,i),t.lineTo(h.x,h.y)),a=!!e.pathSegment(t,r,{move:a}),a?t.closePath():t.lineTo(c.x,i)}t.lineTo(e.first().x,i),t.closePath(),t.clip()}function fa(t,e){const{line:i,target:s,property:n,color:o,scale:a}=e,r=function(t,e,i){const s=t.segments,n=t.points,o=e.points,a=[];for(const t of s){let{start:s,end:r}=t;r=ea(s,r,n);const l=ta(i,n[s],n[r],t.loop);if(!e.segments){a.push({source:t,target:l,start:n[s],end:n[r]});continue}const h=Ii(e,l);for(const e of h){const s=ta(i,o[e.start],o[e.end],e.loop),r=Ri(t,n,s);for(const t of r)a.push({source:t,target:e,start:{[i]:ia(l,s,\"start\",Math.max)},end:{[i]:ia(l,s,\"end\",Math.min)}})}}return a}(i,s,n);for(const{source:e,target:l,start:h,end:c}of r){const{style:{backgroundColor:r=o}={}}=e,d=!0!==s;t.save(),t.fillStyle=r,ga(t,a,d&&ta(n,h,c)),t.beginPath();const u=!!i.pathSegment(t,e);let f;if(d){u?t.closePath():pa(t,s,c,n);const e=!!s.pathSegment(t,l,{move:u,reverse:!0});f=u&&e,f||pa(t,s,h,n)}t.closePath(),t.fill(f?\"evenodd\":\"nonzero\"),t.restore()}}function ga(t,e,i){const{top:s,bottom:n}=e.chart.chartArea,{property:o,start:a,end:r}=i||{};\"x\"===o&&(t.beginPath(),t.rect(a,s,r-a,n-s),t.clip())}function pa(t,e,i,s){const n=e.interpolate(i,s);n&&t.lineTo(n.x,n.y)}var ma={id:\"filler\",afterDatasetsUpdate(t,e,i){const s=(t.data.datasets||[]).length,n=[];let o,a,r,l;for(a=0;a<s;++a)o=t.getDatasetMeta(a),r=o.dataset,l=null,r&&r.options&&r instanceof no&&(l={visible:t.isDatasetVisible(a),index:a,fill:aa(r,a,s),chart:t,axis:o.controller.options.indexAxis,scale:o.vScale,line:r}),o.$filler=l,n.push(l);for(a=0;a<s;++a)l=n[a],l&&!1!==l.fill&&(l.fill=oa(n,a,i.propagate))},beforeDraw(t,e,i){const s=\"beforeDraw\"===i.drawTime,n=t.getSortedVisibleDatasetMetas(),o=t.chartArea;for(let e=n.length-1;e>=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&da(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if(\"beforeDatasetsDraw\"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;na(i)&&da(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;na(s)&&\"beforeDatasetDraw\"===i.drawTime&&da(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:\"beforeDatasetDraw\"}};const ba=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class xa extends Hs{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=ba(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign=\"left\",n.textBaseline=\"middle\";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&\"string\"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;\"string\"!=typeof e.text&&(s=_a(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return\"top\"===this.options.position||\"bottom\"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign(\"left\"),s.textBaseline=\"middle\",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=ba(o,d),b=this.isHorizontal(),x=this._computeTitleHeight();f=b?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+x,line:0}:{x:this.left+c,y:ft(n,this.top+x+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),b?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+x+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,\"butt\"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,\"miter\"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,b?S+k:this.right,t.rtl),function(t,e,i){Ne(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),b)f.x+=k+c;else if(\"string\"!=typeof y.text){const t=h.lineHeight;f.y+=_a(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline=\"middle\",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,Ne(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;i<n.length;++i)if(s=n[i],tt(t,s.left,s.left+s.width)&&tt(e,s.top,s.top+s.height))return this.legendItems[i];return null}handleEvent(t){const e=this.options;if(!function(t,e){if((\"mousemove\"===t||\"mouseout\"===t)&&(e.onHover||e.onLeave))return!0;if(e.onClick&&(\"click\"===t||\"mouseup\"===t))return!0;return!1}(t.type,e))return;const i=this._getLegendItemAt(t.x,t.y);if(\"mousemove\"===t.type||\"mouseout\"===t.type){const o=this._hoveredItem,a=(n=i,null!==(s=o)&&null!==n&&s.datasetIndex===n.datasetIndex&&s.index===n.index);o&&!a&&d(e.onLeave,[t,o,this],this),this._hoveredItem=i,i&&!a&&d(e.onHover,[t,i,this],this)}else i&&d(e.onClick,[t,i,this],this);var s,n}}function _a(t,e){return e*(t.text?t.text.length:0)}var ya={id:\"legend\",_element:xa,start(t,e,i){const s=t.legend=new xa({ctx:t.ctx,options:i,chart:t});as.configure(t,s,i),as.addBox(t,s)},stop(t){as.removeBox(t,t.legend),delete t.legend},beforeUpdate(t,e,i){const s=t.legend;as.configure(t,s,i),s.options=i},afterUpdate(t){const e=t.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(t,e){e.replay||t.legend.handleEvent(e.event)},defaults:{display:!0,position:\"top\",align:\"center\",fullSize:!0,reverse:!1,weight:1e3,onClick(t,e,i){const s=e.datasetIndex,n=i.chart;n.isDatasetVisible(s)?(n.hide(s),e.hidden=!0):(n.show(s),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:t=>t.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:\"center\",text:\"\"}},descriptors:{_scriptable:t=>!t.startsWith(\"on\"),labels:{_scriptable:t=>![\"generateLabels\",\"filter\",\"sort\"].includes(t)}}};class va extends Hs{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return\"top\"===t||\"bottom\"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):(\"left\"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);Ne(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:\"middle\",translation:[n,o]})}}var Ma={id:\"title\",_element:va,start(t,e,i){!function(t,e){const i=new va({ctx:t.ctx,options:e,chart:t});as.configure(t,i,e),as.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;as.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;as.configure(t,s,i),s.options=i},defaults:{align:\"center\",display:!1,font:{weight:\"bold\"},fullSize:!0,padding:10,position:\"top\",text:\"\",weight:2e3},defaultRoutes:{color:\"color\"},descriptors:{_scriptable:!0,_indexable:!1}};const wa=new WeakMap;var ka={id:\"subtitle\",start(t,e,i){const s=new va({ctx:t.ctx,options:i,chart:t});as.configure(t,s,i),as.addBox(t,s),wa.set(t,s)},stop(t){as.removeBox(t,wa.get(t)),wa.delete(t)},beforeUpdate(t,e,i){const s=wa.get(t);as.configure(t,s,i),s.options=i},defaults:{align:\"center\",display:!1,font:{weight:\"normal\"},fullSize:!0,padding:0,position:\"top\",text:\"\",weight:1500},defaultRoutes:{color:\"color\"},descriptors:{_scriptable:!0,_indexable:!1}};const Sa={average(t){if(!t.length)return!1;let e,i,s=0,n=0,o=0;for(e=0,i=t.length;e<i;++e){const i=t[e].element;if(i&&i.hasValue()){const t=i.tooltipPosition();s+=t.x,n+=t.y,++o}}return{x:s/o,y:n/o}},nearest(t,e){if(!t.length)return!1;let i,s,n,o=e.x,a=e.y,r=Number.POSITIVE_INFINITY;for(i=0,s=t.length;i<s;++i){const s=t[i].element;if(s&&s.hasValue()){const t=q(e,s.getCenterPoint());t<r&&(r=t,n=s)}}if(n){const t=n.tooltipPosition();o=t.x,a=t.y}return{x:o,y:a}}};function Pa(t,e){return e&&(n(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function Da(t){return(\"string\"==typeof t||t instanceof String)&&t.indexOf(\"\\n\")>-1?t.split(\"\\n\"):t}function Ca(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Oa(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,b=0,x=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(x+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),x){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(x-g)*l.lineHeight+(x-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){b=Math.max(b,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),b+=p.width,{width:b,height:m}}function Aa(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h=\"center\";return\"center\"===s?h=n<=(r+l)/2?\"left\":\"right\":n<=o/2?h=\"left\":n>=a-o/2&&(h=\"right\"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return\"left\"===t&&n+o+a>e.width||\"right\"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h=\"center\"),h}function Ta(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return i<s/2?\"top\":i>t.height-s/2?\"bottom\":\"center\"}(t,i);return{xAlign:i.xAlign||e.xAlign||Aa(t,e,i,s),yAlign:s}}function La(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return\"right\"===e?i-=s:\"center\"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return\"top\"===e?s+=i:s-=\"bottom\"===e?n+i:n/2,s}(e,l,h);return\"center\"===l?\"left\"===r?g+=h:\"right\"===r&&(g-=h):\"left\"===r?g-=Math.max(c,u)+n:\"right\"===r&&(g+=Math.max(d,f)+n),{x:J(g,0,s.width-e.width),y:J(p,0,s.height-e.height)}}function Ea(t,e,i){const s=ki(i.padding);return\"center\"===e?t.x+t.width/2:\"right\"===e?t.x+t.width-s.right:t.x+s.left}function Ra(t){return Pa([],Da(t))}function Ia(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const za={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&\"dataset\"===this.options.mode)return e.dataset.label||\"\";if(e.label)return e.label;if(s>0&&e.dataIndex<s)return i[e.dataIndex]}return\"\"},afterTitle:e,beforeBody:e,beforeLabel:e,label(t){if(this&&this.options&&\"dataset\"===this.options.mode)return t.label+\": \"+t.formattedValue||t.formattedValue;let e=t.dataset.label||\"\";e&&(e+=\": \");const i=t.formattedValue;return s(i)||(e+=i),e},labelColor(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:e.borderColor,backgroundColor:e.backgroundColor,borderWidth:e.borderWidth,borderDash:e.borderDash,borderDashOffset:e.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:e.pointStyle,rotation:e.rotation}},afterLabel:e,afterBody:e,beforeFooter:e,footer:e,afterFooter:e};function Fa(t,e,i,s){const n=t[e].call(i,s);return void 0===n?za[e].call(i,s):n}class Va extends Hs{static positioners=Sa;constructor(t){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=t.chart,this.options=t.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(t){this.options=t,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const t=this._cachedAnimations;if(t)return t;const e=this.chart,i=this.options.setContext(this.getContext()),s=i.enabled&&e.options.animation&&i.animations,n=new Os(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(n)),n}getContext(){return this.$context||(this.$context=(t=this.chart.getContext(),e=this,i=this._tooltipItems,Ci(t,{tooltip:e,tooltipItems:i,type:\"tooltip\"})));var t,e,i}getTitle(t,e){const{callbacks:i}=e,s=Fa(i,\"beforeTitle\",this,t),n=Fa(i,\"title\",this,t),o=Fa(i,\"afterTitle\",this,t);let a=[];return a=Pa(a,Da(s)),a=Pa(a,Da(n)),a=Pa(a,Da(o)),a}getBeforeBody(t,e){return Ra(Fa(e.callbacks,\"beforeBody\",this,t))}getBody(t,e){const{callbacks:i}=e,s=[];return u(t,(t=>{const e={before:[],lines:[],after:[]},n=Ia(i,t);Pa(e.before,Da(Fa(n,\"beforeLabel\",this,t))),Pa(e.lines,Fa(n,\"label\",this,t)),Pa(e.after,Da(Fa(n,\"afterLabel\",this,t))),s.push(e)})),s}getAfterBody(t,e){return Ra(Fa(e.callbacks,\"afterBody\",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Fa(i,\"beforeFooter\",this,t),n=Fa(i,\"footer\",this,t),o=Fa(i,\"afterFooter\",this,t);let a=[];return a=Pa(a,Da(s)),a=Pa(a,Da(n)),a=Pa(a,Da(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;a<r;++a)l.push(Ca(this.chart,e[a]));return t.filter&&(l=l.filter(((e,s,n)=>t.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=Ia(t.callbacks,e);s.push(Fa(i,\"labelColor\",this,e)),n.push(Fa(i,\"labelPointStyle\",this,e)),o.push(Fa(i,\"labelTextColor\",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Sa[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Oa(this,i),a=Object.assign({},t,e),r=Ta(this.chart,i,a),l=La(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,b,x,_,y;return\"center\"===n?(_=u+g/2,\"left\"===s?(p=d,m=p-o,x=_+o,y=_-o):(p=d+f,m=p+o,x=_-o,y=_+o),b=p):(m=\"left\"===s?d+Math.max(r,h)+o:\"right\"===s?d+f-Math.max(l,c)-o:this.caretX,\"top\"===n?(x=u,_=x-o,p=m-o,b=m+o):(x=u+g,_=x+o,p=m+o,b=m-o),y=x),{x1:p,x2:m,x3:b,y1:x,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ea(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline=\"middle\",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r<n;++r)e.fillText(s[r],l.x(t.x),t.y+o.lineHeight/2),t.y+=o.lineHeight+a,r+1===n&&(t.y+=i.titleMarginBottom-a)}}_drawColorBox(t,e,i,s,n){const a=this.labelColors[i],r=this.labelPointStyles[i],{boxHeight:l,boxWidth:h}=n,c=Si(n.bodyFont),d=Ea(this,\"left\",n),u=s.x(d),f=l<c.lineHeight?(c.lineHeight-l)/2:0,g=e.y+f;if(n.usePointStyle){const e={radius:Math.min(h,l)/2,pointStyle:r.pointStyle,rotation:r.rotation,borderWidth:1},i=s.leftForLtr(u,h)+h/2,o=g+l/2;t.strokeStyle=n.multiKeyBackground,t.fillStyle=n.multiKeyBackground,Le(t,e,i,o),t.strokeStyle=a.borderColor,t.fillStyle=a.backgroundColor,Le(t,e,i,o)}else{t.lineWidth=o(a.borderWidth)?Math.max(...Object.values(a.borderWidth)):a.borderWidth||1,t.strokeStyle=a.borderColor,t.setLineDash(a.borderDash||[]),t.lineDashOffset=a.borderDashOffset||0;const e=s.leftForLtr(u,h),i=s.leftForLtr(s.xPlus(u,1),h-2),r=wi(a.borderRadius);Object.values(r).some((t=>0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let b,x,_,y,v,M,w;for(e.textAlign=o,e.textBaseline=\"middle\",e.font=c.string,t.x=Ea(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&\"right\"!==m?\"center\"===o?l/2+h:l+2+h:0,y=0,M=s.length;y<M;++y){for(b=s[y],x=this.labelTextColors[y],e.fillStyle=x,u(b.before,p),_=b.lines,a&&_.length&&(this._drawColorBox(e,t,y,g,i),d=Math.max(c.lineHeight,r)),v=0,w=_.length;v<w;++v)p(_[v]),d=c.lineHeight;u(b.after,p)}f=0,d=c.lineHeight,u(this.afterBody,p),t.y-=n}drawFooter(t,e,i){const s=this.footer,n=s.length;let o,a;if(n){const r=Oi(i.rtl,this.x,this.width);for(t.x=Ea(this,i.footerAlign,i),t.y+=i.footerMarginTop,e.textAlign=r.textAlign(i.footerAlign),e.textBaseline=\"middle\",o=Si(i.footerFont),e.fillStyle=i.footerColor,e.font=o.string,a=0;a<n;++a)e.fillText(s[a],r.x(t.x),t.y+o.lineHeight/2),t.y+=o.lineHeight+i.footerSpacing}}drawBackground(t,e,i,s){const{xAlign:n,yAlign:o}=this,{x:a,y:r}=t,{width:l,height:h}=i,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(s.cornerRadius);e.fillStyle=s.backgroundColor,e.strokeStyle=s.borderColor,e.lineWidth=s.borderWidth,e.beginPath(),e.moveTo(a+c,r),\"top\"===o&&this.drawCaret(t,e,i,s),e.lineTo(a+l-d,r),e.quadraticCurveTo(a+l,r,a+l,r+d),\"center\"===o&&\"right\"===n&&this.drawCaret(t,e,i,s),e.lineTo(a+l,r+h-f),e.quadraticCurveTo(a+l,r+h,a+l-f,r+h),\"bottom\"===o&&this.drawCaret(t,e,i,s),e.lineTo(a+u,r+h),e.quadraticCurveTo(a,r+h,a,r+h-u),\"center\"===o&&\"left\"===n&&this.drawCaret(t,e,i,s),e.lineTo(a,r+c),e.quadraticCurveTo(a,r,a+c,r),e.closePath(),e.fill(),s.borderWidth>0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Sa[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Oa(this,t),a=Object.assign({},i,this._size),r=Ta(e,t,a),l=La(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error(\"Cannot find a dataset at index \"+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if(\"mouseout\"===t.type)return[];if(!s)return e;const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Sa[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Ba={id:\"tooltip\",_element:Va,positioners:Sa,afterInit(t,e,i){i&&(t.tooltip=new Va({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins(\"beforeTooltipDraw\",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins(\"afterTooltipDraw\",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:\"average\",backgroundColor:\"rgba(0,0,0,0.8)\",titleColor:\"#fff\",titleFont:{weight:\"bold\"},titleSpacing:2,titleMarginBottom:6,titleAlign:\"left\",bodyColor:\"#fff\",bodySpacing:2,bodyFont:{},bodyAlign:\"left\",footerColor:\"#fff\",footerSpacing:2,footerMarginTop:6,footerFont:{weight:\"bold\"},footerAlign:\"left\",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:\"#fff\",displayColors:!0,boxPadding:0,borderColor:\"rgba(0,0,0,0)\",borderWidth:0,animation:{duration:400,easing:\"easeOutQuart\"},animations:{numbers:{type:\"number\",properties:[\"x\",\"y\",\"width\",\"height\",\"caretX\",\"caretY\"]},opacity:{easing:\"linear\",duration:200}},callbacks:za},defaultRoutes:{bodyFont:\"font\",footerFont:\"font\",titleFont:\"font\"},descriptors:{_scriptable:t=>\"filter\"!==t&&\"itemSort\"!==t&&\"external\"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:\"animation\"}},additionalOptionScopes:[\"interaction\"]};return An.register(Yn,jo,fo,t),An.helpers={...Wi},An._adapters=Rn,An.Animation=Cs,An.Animations=Os,An.animator=xt,An.controllers=en.controllers.items,An.DatasetController=Ns,An.Element=Hs,An.elements=fo,An.Interaction=Xi,An.layouts=as,An.platforms=Ss,An.Scale=Js,An.Ticks=ae,Object.assign(An,Yn,jo,fo,t,Ss),An.Chart=An,\"undefined\"!=typeof window&&(window.Chart=An),An}));\n//# sourceMappingURL=chart.umd.js.map\n","knockoutjs/knockout-repeat.js":"// REPEAT binding for Knockout http://knockoutjs.com/\n// (c) Michael Best\n// License: MIT (http://www.opensource.org/licenses/mit-license.php)\n// Version 2.1.0\n\n(function(factory) {\n if (typeof define === 'function' && define.amd) {\n // [1] AMD anonymous module\n define(['knockout'], factory);\n } else if (typeof exports === 'object') {\n // [2] commonJS\n factory(require('knockout'));\n } else {\n // [3] No module loader (plain <script> tag) - put directly in global namespace\n factory(window.ko);\n }\n})(function(ko) {\n\nif (!ko.virtualElements)\n throw Error('Repeat requires at least Knockout 2.1');\n\nvar ko_bindingFlags = ko.bindingFlags || {};\nvar ko_unwrap = ko.utils.unwrapObservable;\n\nvar koProtoName = '__ko_proto__';\n\nif (ko.version >= \"3.0.0\") {\n // In Knockout 3.0.0, use the node preprocessor to replace a node with a repeat binding with a virtual element\n var provider = ko.bindingProvider.instance, previousPreprocessFn = provider.preprocessNode;\n provider.preprocessNode = function(node) {\n var newNodes, nodeBinding;\n if (!previousPreprocessFn || !(newNodes = previousPreprocessFn.call(this, node))) {\n if (node.nodeType === 1 && (nodeBinding = node.getAttribute('data-bind'))) {\n if (/^\\s*repeat\\s*:/.test(nodeBinding)) {\n var leadingComment = node.ownerDocument.createComment('ko ' + nodeBinding),\n trailingComment = node.ownerDocument.createComment('/ko');\n node.parentNode.insertBefore(leadingComment, node);\n node.parentNode.insertBefore(trailingComment, node.nextSibling);\n node.removeAttribute('data-bind');\n newNodes = [leadingComment, node, trailingComment];\n }\n }\n }\n return newNodes;\n };\n}\n\nko.virtualElements.allowedBindings.repeat = true;\nko.bindingHandlers.repeat = {\n flags: ko_bindingFlags.contentBind | ko_bindingFlags.canUseVirtual,\n init: function(element, valueAccessor, allBindingsAccessor, xxx, bindingContext) {\n\n // Read and set fixed options--these options cannot be changed\n var repeatParam = ko_unwrap(valueAccessor());\n if (repeatParam && typeof repeatParam == 'object' && !('length' in repeatParam)) {\n var repeatIndex = repeatParam.index,\n repeatData = repeatParam.item,\n repeatStep = repeatParam.step,\n repeatReversed = repeatParam.reverse,\n repeatBind = repeatParam.bind,\n repeatInit = repeatParam.init,\n repeatUpdate = repeatParam.update;\n }\n // Set default values for options that need it\n repeatIndex = repeatIndex || '$index';\n repeatData = repeatData || ko.bindingHandlers.repeat.itemName || '$item';\n repeatStep = repeatStep || 1;\n repeatReversed = repeatReversed || false;\n\n var parent = element.parentNode, placeholder;\n if (element.nodeType == 8) { // virtual element\n // Extract the \"children\" and find the single element node\n var childNodes = ko.utils.arrayFilter(ko.virtualElements.childNodes(element), function(node) { return node.nodeType == 1;});\n if (childNodes.length !== 1) {\n throw Error(\"Repeat binding requires a single element to repeat\");\n }\n ko.virtualElements.emptyNode(element);\n\n // The placeholder is the closing comment normally, or the opening comment if reversed\n placeholder = repeatReversed ? element : element.nextSibling;\n // The element to repeat is the contained element\n element = childNodes[0];\n } else { // regular element\n // First clean the element node and remove node's binding\n var origBindString = element.getAttribute('data-bind');\n ko.cleanNode(element);\n element.removeAttribute('data-bind');\n\n // Original element is no longer needed: delete it and create a placeholder comment\n placeholder = element.ownerDocument.createComment('ko_repeatplaceholder ' + origBindString);\n parent.replaceChild(placeholder, element);\n }\n\n // extract and remove a data-repeat-bind attribute, if present\n if (!repeatBind) {\n repeatBind = element.getAttribute('data-repeat-bind');\n if (repeatBind) {\n element.removeAttribute('data-repeat-bind');\n }\n }\n\n // Make a copy of the element node to be copied for each repetition\n var cleanNode = element.cloneNode(true);\n if (typeof repeatBind == \"string\") {\n cleanNode.setAttribute('data-bind', repeatBind);\n repeatBind = null;\n }\n\n // Set up persistent data\n var lastRepeatCount = 0,\n notificationObservable = ko.observable(),\n repeatArray, arrayObservable;\n\n if (repeatInit) {\n repeatInit(parent);\n }\n\n var subscribable = ko.computed(function() {\n function makeArrayItemAccessor(index) {\n var f = function(newValue) {\n var item = repeatArray[index];\n // Reading the value of the item\n if (!arguments.length) {\n notificationObservable(); // for dependency tracking\n return ko_unwrap(item);\n }\n // Writing a value to the item\n if (ko.isObservable(item)) {\n item(newValue);\n } else if (arrayObservable && arrayObservable.splice) {\n arrayObservable.splice(index, 1, newValue);\n } else {\n repeatArray[index] = newValue;\n }\n return this;\n };\n // Pretend that our accessor function is an observable\n f[koProtoName] = ko.observable;\n return f;\n }\n\n function makeBinding(item, index, context) {\n return repeatArray\n ? function() { return repeatBind.call(bindingContext.$data, item, index, context); }\n : function() { return repeatBind.call(bindingContext.$data, index, context); }\n }\n\n // Read and set up variable options--these options can change and will update the binding\n var paramObservable = valueAccessor(), repeatParam = ko_unwrap(paramObservable), repeatCount = 0;\n if (repeatParam && typeof repeatParam == 'object') {\n if ('length' in repeatParam) {\n repeatArray = repeatParam;\n repeatCount = repeatArray.length;\n } else {\n if ('foreach' in repeatParam) {\n repeatArray = ko_unwrap(paramObservable = repeatParam.foreach);\n if (repeatArray && typeof repeatArray == 'object' && 'length' in repeatArray) {\n repeatCount = repeatArray.length || 0;\n } else {\n repeatCount = repeatArray || 0;\n repeatArray = null;\n }\n }\n // If a count value is provided (>0), always output that number of items\n if ('count' in repeatParam)\n repeatCount = ko_unwrap(repeatParam.count) || repeatCount;\n // If a limit is provided, don't output more than the limit\n if ('limit' in repeatParam)\n repeatCount = Math.min(repeatCount, ko_unwrap(repeatParam.limit)) || repeatCount;\n }\n arrayObservable = repeatArray && ko.isObservable(paramObservable) ? paramObservable : null;\n } else {\n repeatCount = repeatParam || 0;\n }\n\n // Remove nodes from end if array is shorter\n for (; lastRepeatCount > repeatCount; lastRepeatCount-=repeatStep) {\n ko.removeNode(repeatReversed ? placeholder.nextSibling : placeholder.previousSibling);\n }\n\n // Notify existing nodes of change\n notificationObservable.notifySubscribers();\n\n // Add nodes to end if array is longer (also initially populates nodes)\n for (; lastRepeatCount < repeatCount; lastRepeatCount+=repeatStep) {\n // Clone node and add to document\n var newNode = cleanNode.cloneNode(true);\n parent.insertBefore(newNode, repeatReversed ? placeholder.nextSibling : placeholder);\n newNode.setAttribute('data-repeat-index', lastRepeatCount);\n\n // Apply bindings to inserted node\n if (repeatArray && repeatData == '$data') {\n var newContext = bindingContext.createChildContext(makeArrayItemAccessor(lastRepeatCount));\n } else {\n var newContext = bindingContext.extend();\n if (repeatArray)\n newContext[repeatData] = makeArrayItemAccessor(lastRepeatCount);\n }\n newContext[repeatIndex] = lastRepeatCount;\n if (repeatBind) {\n var result = ko.applyBindingsToNode(newNode, makeBinding(newContext[repeatData], lastRepeatCount, newContext), newContext, true),\n shouldBindDescendants = result && result.shouldBindDescendants;\n }\n if (!repeatBind || (result && shouldBindDescendants !== false)) {\n ko.applyBindings(newContext, newNode);\n }\n }\n if (repeatUpdate) {\n repeatUpdate(parent);\n }\n }, null, {disposeWhenNodeIsRemoved: placeholder});\n\n return { controlsDescendantBindings: true, subscribable: subscribable };\n }\n};\n});","knockoutjs/knockout-es5.js":"/*!\n * Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5\n * Copyright (c) Steve Sanderson\n * MIT license\n */\n\n(function(global, undefined) {\n 'use strict';\n\n var ko;\n\n // Model tracking\n // --------------\n //\n // This is the central feature of Knockout-ES5. We augment model objects by converting properties\n // into ES5 getter/setter pairs that read/write an underlying Knockout observable. This means you can\n // use plain JavaScript syntax to read/write the property while still getting the full benefits of\n // Knockout's automatic dependency detection and notification triggering.\n //\n // For comparison, here's Knockout ES3-compatible syntax:\n //\n // var firstNameLength = myModel.user().firstName().length; // Read\n // myModel.user().firstName('Bert'); // Write\n //\n // ... versus Knockout-ES5 syntax:\n //\n // var firstNameLength = myModel.user.firstName.length; // Read\n // myModel.user.firstName = 'Bert'; // Write\n\n // `ko.track(model)` converts each property on the given model object into a getter/setter pair that\n // wraps a Knockout observable. Optionally specify an array of property names to wrap; otherwise we\n // wrap all properties. If any of the properties are already observables, we replace them with\n // ES5 getter/setter pairs that wrap your original observable instances. In the case of readonly\n // ko.computed properties, we simply do not define a setter (so attempted writes will be ignored,\n // which is how ES5 readonly properties normally behave).\n //\n // By design, this does *not* recursively walk child object properties, because making literally\n // everything everywhere independently observable is usually unhelpful. When you do want to track\n // child object properties independently, define your own class for those child objects and put\n // a separate ko.track call into its constructor --- this gives you far more control.\n /**\n * @param {object} obj\n * @param {object|array.<string>} propertyNamesOrSettings\n * @param {boolean} propertyNamesOrSettings.deep Use deep track.\n * @param {array.<string>} propertyNamesOrSettings.fields Array of property names to wrap.\n * todo: @param {array.<string>} propertyNamesOrSettings.exclude Array of exclude property names to wrap.\n * todo: @param {function(string, *):boolean} propertyNamesOrSettings.filter Function to filter property \n * names to wrap. A function that takes ... params\n * @return {object}\n */\n function track(obj, propertyNamesOrSettings) {\n if (!obj || typeof obj !== 'object') {\n throw new Error('When calling ko.track, you must pass an object as the first parameter.');\n }\n\n var propertyNames;\n\n if ( isPlainObject(propertyNamesOrSettings) ) {\n // defaults\n propertyNamesOrSettings.deep = propertyNamesOrSettings.deep || false;\n propertyNamesOrSettings.fields = propertyNamesOrSettings.fields || Object.getOwnPropertyNames(obj);\n propertyNamesOrSettings.lazy = propertyNamesOrSettings.lazy || false;\n\n wrap(obj, propertyNamesOrSettings.fields, propertyNamesOrSettings);\n } else {\n propertyNames = propertyNamesOrSettings || Object.getOwnPropertyNames(obj);\n wrap(obj, propertyNames, {});\n }\n\n return obj;\n }\n\n // fix for ie\n var rFunctionName = /^function\\s*([^\\s(]+)/;\n function getFunctionName( ctor ){\n if (ctor.name) {\n return ctor.name;\n }\n return (ctor.toString().trim().match( rFunctionName ) || [])[1];\n }\n\n function canTrack(obj) {\n return obj && typeof obj === 'object' && getFunctionName(obj.constructor) === 'Object';\n }\n\n function createPropertyDescriptor(originalValue, prop, map) {\n var isObservable = ko.isObservable(originalValue);\n var isArray = !isObservable && Array.isArray(originalValue);\n var observable = isObservable ? originalValue\n : isArray ? ko.observableArray(originalValue)\n : ko.observable(originalValue);\n\n map[prop] = function () { return observable; };\n\n // add check in case the object is already an observable array\n if (isArray || (isObservable && 'push' in observable)) {\n notifyWhenPresentOrFutureArrayValuesMutate(ko, observable);\n }\n\n return {\n configurable: true,\n enumerable: true,\n get: observable,\n set: ko.isWriteableObservable(observable) ? observable : undefined\n };\n }\n\n function createLazyPropertyDescriptor(originalValue, prop, map) {\n if (ko.isObservable(originalValue)) {\n // no need to be lazy if we already have an observable\n return createPropertyDescriptor(originalValue, prop, map);\n }\n\n var observable;\n\n function getOrCreateObservable(value, writing) {\n if (observable) {\n return writing ? observable(value) : observable;\n }\n\n if (Array.isArray(value)) {\n observable = ko.observableArray(value);\n notifyWhenPresentOrFutureArrayValuesMutate(ko, observable);\n return observable;\n }\n\n return (observable = ko.observable(value));\n }\n\n map[prop] = function () { return getOrCreateObservable(originalValue); };\n return {\n configurable: true,\n enumerable: true,\n get: function () { return getOrCreateObservable(originalValue)(); },\n set: function (value) { getOrCreateObservable(value, true); }\n };\n }\n\n function wrap(obj, props, options) {\n if (!props.length) {\n return;\n }\n\n var allObservablesForObject = getAllObservablesForObject(obj, true);\n var descriptors = {};\n\n props.forEach(function (prop) {\n // Skip properties that are already tracked\n if (prop in allObservablesForObject) {\n return;\n }\n\n // Skip properties where descriptor can't be redefined\n if (Object.getOwnPropertyDescriptor(obj, prop).configurable === false){\n return;\n }\n\n var originalValue = obj[prop];\n descriptors[prop] = (options.lazy ? createLazyPropertyDescriptor : createPropertyDescriptor)\n (originalValue, prop, allObservablesForObject);\n\n if (options.deep && canTrack(originalValue)) {\n wrap(originalValue, Object.keys(originalValue), options);\n }\n });\n\n Object.defineProperties(obj, descriptors);\n }\n\n function isPlainObject( obj ){\n return !!obj && typeof obj === 'object' && obj.constructor === Object;\n }\n\n // Lazily created by `getAllObservablesForObject` below. Has to be created lazily because the\n // WeakMap factory isn't available until the module has finished loading (may be async).\n var objectToObservableMap;\n\n // Gets or creates the hidden internal key-value collection of observables corresponding to\n // properties on the model object.\n function getAllObservablesForObject(obj, createIfNotDefined) {\n if (!objectToObservableMap) {\n objectToObservableMap = weakMapFactory();\n }\n\n var result = objectToObservableMap.get(obj);\n if (!result && createIfNotDefined) {\n result = {};\n objectToObservableMap.set(obj, result);\n }\n return result;\n }\n\n // Removes the internal references to observables mapped to the specified properties\n // or the entire object reference if no properties are passed in. This allows the\n // observables to be replaced and tracked again.\n function untrack(obj, propertyNames) {\n if (!objectToObservableMap) {\n return;\n }\n\n if (arguments.length === 1) {\n objectToObservableMap['delete'](obj);\n } else {\n var allObservablesForObject = getAllObservablesForObject(obj, false);\n if (allObservablesForObject) {\n propertyNames.forEach(function(propertyName) {\n delete allObservablesForObject[propertyName];\n });\n }\n }\n }\n\n // Computed properties\n // -------------------\n //\n // The preceding code is already sufficient to upgrade ko.computed model properties to ES5\n // getter/setter pairs (or in the case of readonly ko.computed properties, just a getter).\n // These then behave like a regular property with a getter function, except they are smarter:\n // your evaluator is only invoked when one of its dependencies changes. The result is cached\n // and used for all evaluations until the next time a dependency changes).\n //\n // However, instead of forcing developers to declare a ko.computed property explicitly, it's\n // nice to offer a utility function that declares a computed getter directly.\n\n // Implements `ko.defineProperty`\n function defineComputedProperty(obj, propertyName, evaluatorOrOptions) {\n var ko = this,\n computedOptions = { owner: obj, deferEvaluation: true };\n\n if (typeof evaluatorOrOptions === 'function') {\n computedOptions.read = evaluatorOrOptions;\n } else {\n if ('value' in evaluatorOrOptions) {\n throw new Error('For ko.defineProperty, you must not specify a \"value\" for the property. ' +\n 'You must provide a \"get\" function.');\n }\n\n if (typeof evaluatorOrOptions.get !== 'function') {\n throw new Error('For ko.defineProperty, the third parameter must be either an evaluator function, ' +\n 'or an options object containing a function called \"get\".');\n }\n\n computedOptions.read = evaluatorOrOptions.get;\n computedOptions.write = evaluatorOrOptions.set;\n }\n\n obj[propertyName] = ko.computed(computedOptions);\n track.call(ko, obj, [propertyName]);\n return obj;\n }\n\n // Array handling\n // --------------\n //\n // Arrays are special, because unlike other property types, they have standard mutator functions\n // (`push`/`pop`/`splice`/etc.) and it's desirable to trigger a change notification whenever one of\n // those mutator functions is invoked.\n //\n // Traditionally, Knockout handles this by putting special versions of `push`/`pop`/etc. on observable\n // arrays that mutate the underlying array and then trigger a notification. That approach doesn't\n // work for Knockout-ES5 because properties now return the underlying arrays, so the mutator runs\n // in the context of the underlying array, not any particular observable:\n //\n // // Operates on the underlying array value\n // myModel.someCollection.push('New value');\n //\n // To solve this, Knockout-ES5 detects array values, and modifies them as follows:\n // 1. Associates a hidden subscribable with each array instance that it encounters\n // 2. Intercepts standard mutators (`push`/`pop`/etc.) and makes them trigger the subscribable\n // Then, for model properties whose values are arrays, the property's underlying observable\n // subscribes to the array subscribable, so it can trigger a change notification after mutation.\n\n // Given an observable that underlies a model property, watch for any array value that might\n // be assigned as the property value, and hook into its change events\n function notifyWhenPresentOrFutureArrayValuesMutate(ko, observable) {\n var watchingArraySubscription = null;\n ko.computed(function () {\n // Unsubscribe to any earlier array instance\n if (watchingArraySubscription) {\n watchingArraySubscription.dispose();\n watchingArraySubscription = null;\n }\n\n // Subscribe to the new array instance\n var newArrayInstance = observable();\n if (newArrayInstance instanceof Array) {\n watchingArraySubscription = startWatchingArrayInstance(ko, observable, newArrayInstance);\n }\n });\n }\n\n // Listens for array mutations, and when they happen, cause the observable to fire notifications.\n // This is used to make model properties of type array fire notifications when the array changes.\n // Returns a subscribable that can later be disposed.\n function startWatchingArrayInstance(ko, observable, arrayInstance) {\n var subscribable = getSubscribableForArray(ko, arrayInstance);\n return subscribable.subscribe(observable);\n }\n\n // Lazily created by `getSubscribableForArray` below. Has to be created lazily because the\n // WeakMap factory isn't available until the module has finished loading (may be async).\n var arraySubscribablesMap;\n\n // Gets or creates a subscribable that fires after each array mutation\n function getSubscribableForArray(ko, arrayInstance) {\n if (!arraySubscribablesMap) {\n arraySubscribablesMap = weakMapFactory();\n }\n\n var subscribable = arraySubscribablesMap.get(arrayInstance);\n if (!subscribable) {\n subscribable = new ko.subscribable();\n arraySubscribablesMap.set(arrayInstance, subscribable);\n\n var notificationPauseSignal = {};\n wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal);\n addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal);\n }\n\n return subscribable;\n }\n\n // After each array mutation, fires a notification on the given subscribable\n function wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal) {\n ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'].forEach(function(fnName) {\n var origMutator = arrayInstance[fnName];\n arrayInstance[fnName] = function() {\n var result = origMutator.apply(this, arguments);\n if (notificationPauseSignal.pause !== true) {\n subscribable.notifySubscribers(this);\n }\n return result;\n };\n });\n }\n\n // Adds Knockout's additional array mutation functions to the array\n function addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal) {\n ['remove', 'removeAll', 'destroy', 'destroyAll', 'replace'].forEach(function(fnName) {\n // Make it a non-enumerable property for consistency with standard Array functions\n Object.defineProperty(arrayInstance, fnName, {\n enumerable: false,\n value: function() {\n var result;\n\n // These additional array mutators are built using the underlying push/pop/etc.\n // mutators, which are wrapped to trigger notifications. But we don't want to\n // trigger multiple notifications, so pause the push/pop/etc. wrappers and\n // delivery only one notification at the end of the process.\n notificationPauseSignal.pause = true;\n try {\n // Creates a temporary observableArray that can perform the operation.\n result = ko.observableArray.fn[fnName].apply(ko.observableArray(arrayInstance), arguments);\n }\n finally {\n notificationPauseSignal.pause = false;\n }\n subscribable.notifySubscribers(arrayInstance);\n return result;\n }\n });\n });\n }\n\n // Static utility functions\n // ------------------------\n //\n // Since Knockout-ES5 sets up properties that return values, not observables, you can't\n // trivially subscribe to the underlying observables (e.g., `someProperty.subscribe(...)`),\n // or tell them that object values have mutated, etc. To handle this, we set up some\n // extra utility functions that can return or work with the underlying observables.\n\n // Returns the underlying observable associated with a model property (or `null` if the\n // model or property doesn't exist, or isn't associated with an observable). This means\n // you can subscribe to the property, e.g.:\n //\n // ko.getObservable(model, 'propertyName')\n // .subscribe(function(newValue) { ... });\n function getObservable(obj, propertyName) {\n if (!obj || typeof obj !== 'object') {\n return null;\n }\n\n var allObservablesForObject = getAllObservablesForObject(obj, false);\n if (allObservablesForObject && propertyName in allObservablesForObject) {\n return allObservablesForObject[propertyName]();\n }\n\n return null;\n }\n \n // Returns a boolean indicating whether the property on the object has an underlying\n // observables. This does the check in a way not to create an observable if the\n // object was created with lazily created observables\n function isTracked(obj, propertyName) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n \n var allObservablesForObject = getAllObservablesForObject(obj, false);\n return !!allObservablesForObject && propertyName in allObservablesForObject;\n }\n\n // Causes a property's associated observable to fire a change notification. Useful when\n // the property value is a complex object and you've modified a child property.\n function valueHasMutated(obj, propertyName) {\n var observable = getObservable(obj, propertyName);\n\n if (observable) {\n observable.valueHasMutated();\n }\n }\n\n // Module initialisation\n // ---------------------\n //\n // When this script is first evaluated, it works out what kind of module loading scenario\n // it is in (Node.js or a browser `<script>` tag), stashes a reference to its dependencies\n // (currently that's just the WeakMap shim), and then finally attaches itself to whichever\n // instance of Knockout.js it can find.\n\n // A function that returns a new ES6-compatible WeakMap instance (using ES5 shim if needed).\n // Instantiated by prepareExports, accounting for which module loader is being used.\n var weakMapFactory;\n\n // Extends a Knockout instance with Knockout-ES5 functionality\n function attachToKo(ko) {\n ko.track = track;\n ko.untrack = untrack;\n ko.getObservable = getObservable;\n ko.valueHasMutated = valueHasMutated;\n ko.defineProperty = defineComputedProperty;\n\n // todo: test it, maybe added it to ko. directly\n ko.es5 = {\n getAllObservablesForObject: getAllObservablesForObject,\n notifyWhenPresentOrFutureArrayValuesMutate: notifyWhenPresentOrFutureArrayValuesMutate,\n isTracked: isTracked\n };\n }\n\n // Determines which module loading scenario we're in, grabs dependencies, and attaches to KO\n function prepareExports() {\n if (typeof exports === 'object' && typeof module === 'object') {\n // Node.js case - load KO and WeakMap modules synchronously\n ko = require('knockout');\n var WM = require('../lib/weakmap');\n attachToKo(ko);\n weakMapFactory = function() { return new WM(); };\n module.exports = ko;\n } else if (typeof define === 'function' && define.amd) {\n define(['knockout'], function(koModule) {\n ko = koModule;\n attachToKo(koModule);\n weakMapFactory = function() { return new global.WeakMap(); };\n return koModule;\n });\n } else if ('ko' in global) {\n // Non-module case - attach to the global instance, and assume a global WeakMap constructor\n ko = global.ko;\n attachToKo(global.ko);\n weakMapFactory = function() { return new global.WeakMap(); };\n }\n }\n\n prepareExports();\n\n})(this);","knockoutjs/knockout-fast-foreach.js":"/*!\n Knockout Fast Foreach v0.4.1 (2015-07-17T14:06:15.974Z)\n By: Brian M Hunt (C) 2015\n License: MIT\n\n Adds `fastForEach` to `ko.bindingHandlers`.\n*/\n(function (root, factory) {\n if (typeof define === 'function' && define.amd) {\n define(['knockout'], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory(require('knockout'));\n } else {\n root.KnockoutFastForeach = factory(root.ko);\n }\n}(this, function (ko) {\n \"use strict\";\n// index.js\n// --------\n// Fast For Each\n//\n// Employing sound techniques to make a faster Knockout foreach binding.\n// --------\n\n// Utilities\n\n// from https://github.com/jonschlinkert/is-plain-object\nfunction isPlainObject(o) {\n return !!o && typeof o === 'object' && o.constructor === Object;\n}\n\n// From knockout/src/virtualElements.js\nvar commentNodesHaveTextProperty = document && document.createComment(\"test\").text === \"<!--test-->\";\nvar startCommentRegex = commentNodesHaveTextProperty ? /^<!--\\s*ko(?:\\s+([\\s\\S]+))?\\s*-->$/ : /^\\s*ko(?:\\s+([\\s\\S]+))?\\s*$/;\nvar supportsDocumentFragment = document && typeof document.createDocumentFragment === \"function\";\nfunction isVirtualNode(node) {\n return (node.nodeType === 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);\n}\n\n\n// Get a copy of the (possibly virtual) child nodes of the given element,\n// put them into a container, then empty the given node.\nfunction makeTemplateNode(sourceNode) {\n var container = document.createElement(\"div\");\n var parentNode;\n if (sourceNode.content) {\n // For e.g. <template> tags\n parentNode = sourceNode.content;\n } else if (sourceNode.tagName === 'SCRIPT') {\n parentNode = document.createElement(\"div\");\n parentNode.innerHTML = sourceNode.text;\n } else {\n // Anything else e.g. <div>\n parentNode = sourceNode;\n }\n ko.utils.arrayForEach(ko.virtualElements.childNodes(parentNode), function (child) {\n // FIXME - This cloneNode could be expensive; we may prefer to iterate over the\n // parentNode children in reverse (so as not to foul the indexes as childNodes are\n // removed from parentNode when inserted into the container)\n if (child) {\n container.insertBefore(child.cloneNode(true), null);\n }\n });\n return container;\n}\n\nfunction insertAllAfter(containerNode, nodeOrNodeArrayToInsert, insertAfterNode) {\n var frag, len, i;\n // poor man's node and array check, should be enough for this\n if (typeof nodeOrNodeArrayToInsert.nodeType !== \"undefined\" && typeof nodeOrNodeArrayToInsert.length === \"undefined\") {\n throw new Error(\"Expected a single node or a node array\");\n }\n\n if (typeof nodeOrNodeArrayToInsert.nodeType !== \"undefined\") {\n ko.virtualElements.insertAfter(containerNode, nodeOrNodeArrayToInsert, insertAfterNode);\n return;\n }\n\n if (nodeOrNodeArrayToInsert.length === 1) {\n ko.virtualElements.insertAfter(containerNode, nodeOrNodeArrayToInsert[0], insertAfterNode);\n return;\n }\n\n if (supportsDocumentFragment) {\n frag = document.createDocumentFragment();\n\n for (i = 0, len = nodeOrNodeArrayToInsert.length; i !== len; ++i) {\n frag.appendChild(nodeOrNodeArrayToInsert[i]);\n }\n ko.virtualElements.insertAfter(containerNode, frag, insertAfterNode);\n } else {\n // Nodes are inserted in reverse order - pushed down immediately after\n // the last node for the previous item or as the first node of element.\n for (i = nodeOrNodeArrayToInsert.length - 1; i >= 0; --i) {\n var child = nodeOrNodeArrayToInsert[i];\n if (!child) {\n return;\n }\n ko.virtualElements.insertAfter(containerNode, child, insertAfterNode);\n }\n }\n}\n\n// Mimic a KO change item 'add'\nfunction valueToChangeAddItem(value, index) {\n return {\n status: 'added',\n value: value,\n index: index\n };\n}\n\nfunction isAdditionAdjacentToLast(changeIndex, arrayChanges) {\n return changeIndex > 0 &&\n changeIndex < arrayChanges.length &&\n arrayChanges[changeIndex].status === \"added\" &&\n arrayChanges[changeIndex - 1].status === \"added\" &&\n arrayChanges[changeIndex - 1].index === arrayChanges[changeIndex].index - 1;\n}\n\nfunction FastForEach(spec) {\n this.element = spec.element;\n this.container = isVirtualNode(this.element) ?\n this.element.parentNode : this.element;\n this.$context = spec.$context;\n this.data = spec.data;\n this.as = spec.as;\n this.noContext = spec.noContext;\n this.templateNode = makeTemplateNode(\n spec.name ? document.getElementById(spec.name).cloneNode(true) : spec.element\n );\n this.afterQueueFlush = spec.afterQueueFlush;\n this.beforeQueueFlush = spec.beforeQueueFlush;\n this.changeQueue = [];\n this.lastNodesList = [];\n this.indexesToDelete = [];\n this.rendering_queued = false;\n\n // Remove existing content.\n ko.virtualElements.emptyNode(this.element);\n\n // Prime content\n var primeData = ko.unwrap(this.data);\n if (primeData.map) {\n this.onArrayChange(primeData.map(valueToChangeAddItem));\n }\n\n // Watch for changes\n if (ko.isObservable(this.data)) {\n if (!this.data.indexOf) {\n // Make sure the observable is trackable.\n this.data = this.data.extend({trackArrayChanges: true});\n }\n this.changeSubs = this.data.subscribe(this.onArrayChange, this, 'arrayChange');\n }\n}\n\n\nFastForEach.animateFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame ||\n window.mozRequestAnimationFrame || window.msRequestAnimationFrame ||\n function(cb) { return window.setTimeout(cb, 1000 / 60); };\n\n\nFastForEach.prototype.dispose = function () {\n if (this.changeSubs) {\n this.changeSubs.dispose();\n }\n};\n\n\n// If the array changes we register the change.\nFastForEach.prototype.onArrayChange = function (changeSet) {\n var self = this;\n var changeMap = {\n added: [],\n deleted: []\n };\n for (var i = 0, len = changeSet.length; i < len; i++) {\n // the change is appended to a last change info object when both are 'added' and have indexes next to each other\n // here I presume that ko is sending changes in monotonic order (in index variable) which happens to be true, tested with push and splice with multiple pushed values\n if (isAdditionAdjacentToLast(i, changeSet)) {\n var batchValues = changeMap.added[changeMap.added.length - 1].values;\n if (!batchValues) {\n // transform the last addition into a batch addition object\n var lastAddition = changeMap.added.pop();\n var batchAddition = {\n isBatch: true,\n status: 'added',\n index: lastAddition.index,\n values: [lastAddition.value]\n };\n batchValues = batchAddition.values;\n changeMap.added.push(batchAddition);\n }\n batchValues.push(changeSet[i].value);\n } else {\n changeMap[changeSet[i].status].push(changeSet[i]);\n }\n }\n if (changeMap.deleted.length > 0) {\n this.changeQueue.push.apply(this.changeQueue, changeMap.deleted);\n this.changeQueue.push({status: 'clearDeletedIndexes'});\n }\n this.changeQueue.push.apply(this.changeQueue, changeMap.added);\n // Once a change is registered, the ticking count-down starts for the processQueue.\n if (this.changeQueue.length > 0 && !this.rendering_queued) {\n this.rendering_queued = true;\n FastForEach.animateFrame.call(window, function () { self.processQueue(); });\n }\n};\n\n\n// Reflect all the changes in the queue in the DOM, then wipe the queue.\nFastForEach.prototype.processQueue = function () {\n var self = this;\n\n // Callback so folks can do things before the queue flush.\n if (typeof this.beforeQueueFlush === 'function') {\n this.beforeQueueFlush(this.changeQueue);\n }\n\n ko.utils.arrayForEach(this.changeQueue, function (changeItem) {\n // console.log(self.data(), \"CI\", JSON.stringify(changeItem, null, 2), JSON.stringify($(self.element).text()))\n self[changeItem.status](changeItem);\n // console.log(\" ==> \", JSON.stringify($(self.element).text()))\n });\n this.rendering_queued = false;\n // Callback so folks can do things.\n if (typeof this.afterQueueFlush === 'function') {\n this.afterQueueFlush(this.changeQueue);\n }\n this.changeQueue = [];\n};\n\n\n// Process a changeItem with {status: 'added', ...}\nFastForEach.prototype.added = function (changeItem) {\n var index = changeItem.index;\n var valuesToAdd = changeItem.isBatch ? changeItem.values : [changeItem.value];\n var referenceElement = this.lastNodesList[index - 1] || null;\n // gather all childnodes for a possible batch insertion\n var allChildNodes = [];\n\n for (var i = 0, len = valuesToAdd.length; i < len; ++i) {\n var templateClone = this.templateNode.cloneNode(true);\n var childContext;\n\n if (this.noContext) {\n childContext = this.$context.extend({\n '$item': valuesToAdd[i]\n });\n } else {\n childContext = this.$context.createChildContext(valuesToAdd[i], this.as || null);\n }\n\n // apply bindings first, and then process child nodes, because bindings can add childnodes\n ko.applyBindingsToDescendants(childContext, templateClone);\n\n var childNodes = ko.virtualElements.childNodes(templateClone);\n // Note discussion at https://github.com/angular/angular.js/issues/7851\n allChildNodes.push.apply(allChildNodes, Array.prototype.slice.call(childNodes));\n this.lastNodesList.splice(index + i, 0, childNodes[childNodes.length - 1]);\n }\n\n insertAllAfter(this.element, allChildNodes, referenceElement);\n};\n\n\n// Process a changeItem with {status: 'deleted', ...}\nFastForEach.prototype.deleted = function (changeItem) {\n var index = changeItem.index;\n var ptr = this.lastNodesList[index],\n // We use this.element because that will be the last previous node\n // for virtual element lists.\n lastNode = this.lastNodesList[index - 1] || this.element;\n do {\n ptr = ptr.previousSibling;\n ko.removeNode((ptr && ptr.nextSibling) || ko.virtualElements.firstChild(this.element));\n } while (ptr && ptr !== lastNode);\n // The \"last node\" in the DOM from which we begin our delets of the next adjacent node is\n // now the sibling that preceded the first node of this item.\n this.lastNodesList[index] = this.lastNodesList[index - 1];\n this.indexesToDelete.push(index);\n};\n\n\n// We batch our deletion of item indexes in our parallel array.\n// See brianmhunt/knockout-fast-foreach#6/#8\nFastForEach.prototype.clearDeletedIndexes = function () {\n // We iterate in reverse on the presumption (following the unit tests) that KO's diff engine\n // processes diffs (esp. deletes) monotonically ascending i.e. from index 0 -> N.\n for (var i = this.indexesToDelete.length - 1; i >= 0; --i) {\n this.lastNodesList.splice(this.indexesToDelete[i], 1);\n }\n this.indexesToDelete = [];\n};\n\n\nko.bindingHandlers.fastForEach = {\n // Valid valueAccessors:\n // []\n // ko.observable([])\n // ko.observableArray([])\n // ko.computed\n // {data: array, name: string, as: string}\n init: function init(element, valueAccessor, bindings, vm, context) {\n var value = valueAccessor(),\n ffe;\n if (isPlainObject(value)) {\n value.element = value.element || element;\n value.$context = context;\n ffe = new FastForEach(value);\n } else {\n ffe = new FastForEach({\n element: element,\n data: ko.unwrap(context.$rawData) === value ? context.$rawData : value,\n $context: context\n });\n }\n ko.utils.domNodeDisposal.addDisposeCallback(element, function () {\n ffe.dispose();\n });\n return {controlsDescendantBindings: true};\n },\n\n // Export for testing, debugging, and overloading.\n FastForEach: FastForEach\n};\n\nko.virtualElements.allowedBindings.fastForEach = true;\n}));","knockoutjs/knockout.js":"/*!\n * Knockout JavaScript library v3.5.1\n * (c) The Knockout.js team - http://knockoutjs.com/\n * License: MIT (http://www.opensource.org/licenses/mit-license.php)\n */\n\n(function(){\n var DEBUG=true;\n (function(undefined){\n // (0, eval)('this') is a robust way of getting a reference to the global object\n // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023\n var window = this || (0, eval)('this'),\n document = window['document'],\n navigator = window['navigator'],\n jQueryInstance = window[\"jQuery\"],\n JSON = window[\"JSON\"];\n\n if (!jQueryInstance && typeof jQuery !== \"undefined\") {\n jQueryInstance = jQuery;\n }\n (function(factory) {\n // Support three module loading scenarios\n if (typeof define === 'function' && define['amd']) {\n // [1] AMD anonymous module\n define(['exports', 'require'], factory);\n } else if (typeof exports === 'object' && typeof module === 'object') {\n // [2] CommonJS/Node.js\n factory(module['exports'] || exports); // module.exports is for Node.js\n } else {\n // [3] No module loader (plain <script> tag) - put directly in global namespace\n factory(window['ko'] = {});\n }\n }(function(koExports, amdRequire){\n// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).\n// In the future, the following \"ko\" variable may be made distinct from \"koExports\" so that private objects are not externally reachable.\n var ko = typeof koExports !== 'undefined' ? koExports : {};\n// Google Closure Compiler helpers (used only to make the minified file smaller)\n ko.exportSymbol = function(koPath, object) {\n var tokens = koPath.split(\".\");\n\n // In the future, \"ko\" may become distinct from \"koExports\" (so that non-exported objects are not reachable)\n // At that point, \"target\" would be set to: (typeof koExports !== \"undefined\" ? koExports : ko)\n var target = ko;\n\n for (var i = 0; i < tokens.length - 1; i++)\n target = target[tokens[i]];\n target[tokens[tokens.length - 1]] = object;\n };\n ko.exportProperty = function(owner, publicName, object) {\n owner[publicName] = object;\n };\n ko.version = \"3.5.1\";\n\n ko.exportSymbol('version', ko.version);\n// For any options that may affect various areas of Knockout and aren't directly associated with data binding.\n ko.options = {\n 'deferUpdates': false,\n 'useOnlyNativeEvents': false,\n 'foreachHidesDestroyed': false\n };\n\n//ko.exportSymbol('options', ko.options); // 'options' isn't minified\n ko.utils = (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty;\n\n function objectForEach(obj, action) {\n for (var prop in obj) {\n if (hasOwnProperty.call(obj, prop)) {\n action(prop, obj[prop]);\n }\n }\n }\n\n function extend(target, source) {\n if (source) {\n for(var prop in source) {\n if(hasOwnProperty.call(source, prop)) {\n target[prop] = source[prop];\n }\n }\n }\n return target;\n }\n\n function setPrototypeOf(obj, proto) {\n obj.__proto__ = proto;\n return obj;\n }\n\n var canSetPrototype = ({ __proto__: [] } instanceof Array);\n var canUseSymbols = !DEBUG && typeof Symbol === 'function';\n\n // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)\n var knownEvents = {}, knownEventTypesByEventName = {};\n var keyEventTypeName = (navigator && /Firefox\\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';\n knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];\n knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];\n objectForEach(knownEvents, function(eventType, knownEventsForType) {\n if (knownEventsForType.length) {\n for (var i = 0, j = knownEventsForType.length; i < j; i++)\n knownEventTypesByEventName[knownEventsForType[i]] = eventType;\n }\n });\n var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406\n\n // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)\n // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.\n // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.\n // If there is a future need to detect specific versions of IE10+, we will amend this.\n var ieVersion = document && (function() {\n var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');\n\n // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment\n while (\n div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',\n iElems[0]\n ) {}\n return version > 4 ? version : undefined;\n }());\n var isIe6 = ieVersion === 6,\n isIe7 = ieVersion === 7;\n\n function isClickOnCheckableElement(element, eventType) {\n if ((ko.utils.tagNameLower(element) !== \"input\") || !element.type) return false;\n if (eventType.toLowerCase() != \"click\") return false;\n var inputType = element.type;\n return (inputType == \"checkbox\") || (inputType == \"radio\");\n }\n\n // For details on the pattern for changing node classes\n // see: https://github.com/knockout/knockout/issues/1597\n var cssClassNameRegex = /\\S+/g;\n\n var jQueryEventAttachName;\n\n function toggleDomNodeCssClass(node, classNames, shouldHaveClass) {\n var addOrRemoveFn;\n if (classNames) {\n if (typeof node.classList === 'object') {\n addOrRemoveFn = node.classList[shouldHaveClass ? 'add' : 'remove'];\n ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {\n addOrRemoveFn.call(node.classList, className);\n });\n } else if (typeof node.className['baseVal'] === 'string') {\n // SVG tag .classNames is an SVGAnimatedString instance\n toggleObjectClassPropertyString(node.className, 'baseVal', classNames, shouldHaveClass);\n } else {\n // node.className ought to be a string.\n toggleObjectClassPropertyString(node, 'className', classNames, shouldHaveClass);\n }\n }\n }\n\n function toggleObjectClassPropertyString(obj, prop, classNames, shouldHaveClass) {\n // obj/prop is either a node/'className' or a SVGAnimatedString/'baseVal'.\n var currentClassNames = obj[prop].match(cssClassNameRegex) || [];\n ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {\n ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);\n });\n obj[prop] = currentClassNames.join(\" \");\n }\n\n return {\n fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],\n\n arrayForEach: function (array, action, actionOwner) {\n for (var i = 0, j = array.length; i < j; i++) {\n action.call(actionOwner, array[i], i, array);\n }\n },\n\n arrayIndexOf: typeof Array.prototype.indexOf == \"function\"\n ? function (array, item) {\n return Array.prototype.indexOf.call(array, item);\n }\n : function (array, item) {\n for (var i = 0, j = array.length; i < j; i++) {\n if (array[i] === item)\n return i;\n }\n return -1;\n },\n\n arrayFirst: function (array, predicate, predicateOwner) {\n for (var i = 0, j = array.length; i < j; i++) {\n if (predicate.call(predicateOwner, array[i], i, array))\n return array[i];\n }\n return undefined;\n },\n\n arrayRemoveItem: function (array, itemToRemove) {\n var index = ko.utils.arrayIndexOf(array, itemToRemove);\n if (index > 0) {\n array.splice(index, 1);\n }\n else if (index === 0) {\n array.shift();\n }\n },\n\n arrayGetDistinctValues: function (array) {\n var result = [];\n if (array) {\n ko.utils.arrayForEach(array, function(item) {\n if (ko.utils.arrayIndexOf(result, item) < 0)\n result.push(item);\n });\n }\n return result;\n },\n\n arrayMap: function (array, mapping, mappingOwner) {\n var result = [];\n if (array) {\n for (var i = 0, j = array.length; i < j; i++)\n result.push(mapping.call(mappingOwner, array[i], i));\n }\n return result;\n },\n\n arrayFilter: function (array, predicate, predicateOwner) {\n var result = [];\n if (array) {\n for (var i = 0, j = array.length; i < j; i++)\n if (predicate.call(predicateOwner, array[i], i))\n result.push(array[i]);\n }\n return result;\n },\n\n arrayPushAll: function (array, valuesToPush) {\n if (valuesToPush instanceof Array)\n array.push.apply(array, valuesToPush);\n else\n for (var i = 0, j = valuesToPush.length; i < j; i++)\n array.push(valuesToPush[i]);\n return array;\n },\n\n addOrRemoveItem: function(array, value, included) {\n var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);\n if (existingEntryIndex < 0) {\n if (included)\n array.push(value);\n } else {\n if (!included)\n array.splice(existingEntryIndex, 1);\n }\n },\n\n canSetPrototype: canSetPrototype,\n\n extend: extend,\n\n setPrototypeOf: setPrototypeOf,\n\n setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,\n\n objectForEach: objectForEach,\n\n objectMap: function(source, mapping, mappingOwner) {\n if (!source)\n return source;\n var target = {};\n for (var prop in source) {\n if (hasOwnProperty.call(source, prop)) {\n target[prop] = mapping.call(mappingOwner, source[prop], prop, source);\n }\n }\n return target;\n },\n\n emptyDomNode: function (domNode) {\n while (domNode.firstChild) {\n ko.removeNode(domNode.firstChild);\n }\n },\n\n moveCleanedNodesToContainerElement: function(nodes) {\n // Ensure it's a real array, as we're about to reparent the nodes and\n // we don't want the underlying collection to change while we're doing that.\n var nodesArray = ko.utils.makeArray(nodes);\n var templateDocument = (nodesArray[0] && nodesArray[0].ownerDocument) || document;\n\n var container = templateDocument.createElement('div');\n for (var i = 0, j = nodesArray.length; i < j; i++) {\n container.appendChild(ko.cleanNode(nodesArray[i]));\n }\n return container;\n },\n\n cloneNodes: function (nodesArray, shouldCleanNodes) {\n for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {\n var clonedNode = nodesArray[i].cloneNode(true);\n newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);\n }\n return newNodesArray;\n },\n\n setDomNodeChildren: function (domNode, childNodes) {\n ko.utils.emptyDomNode(domNode);\n if (childNodes) {\n for (var i = 0, j = childNodes.length; i < j; i++)\n domNode.appendChild(childNodes[i]);\n }\n },\n\n replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {\n var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;\n if (nodesToReplaceArray.length > 0) {\n var insertionPoint = nodesToReplaceArray[0];\n var parent = insertionPoint.parentNode;\n for (var i = 0, j = newNodesArray.length; i < j; i++)\n parent.insertBefore(newNodesArray[i], insertionPoint);\n for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {\n ko.removeNode(nodesToReplaceArray[i]);\n }\n }\n },\n\n fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {\n // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile\n // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that\n // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been\n // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.\n // So, this function translates the old \"map\" output array into its best guess of the set of current DOM nodes.\n //\n // Rules:\n // [A] Any leading nodes that have been removed should be ignored\n // These most likely correspond to memoization nodes that were already removed during binding\n // See https://github.com/knockout/knockout/pull/440\n // [B] Any trailing nodes that have been remove should be ignored\n // This prevents the code here from adding unrelated nodes to the array while processing rule [C]\n // See https://github.com/knockout/knockout/pull/1903\n // [C] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,\n // and include any nodes that have been inserted among the previous collection\n\n if (continuousNodeArray.length) {\n // The parent node can be a virtual element; so get the real parent node\n parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;\n\n // Rule [A]\n while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)\n continuousNodeArray.splice(0, 1);\n\n // Rule [B]\n while (continuousNodeArray.length > 1 && continuousNodeArray[continuousNodeArray.length - 1].parentNode !== parentNode)\n continuousNodeArray.length--;\n\n // Rule [C]\n if (continuousNodeArray.length > 1) {\n var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];\n // Replace with the actual new continuous node set\n continuousNodeArray.length = 0;\n while (current !== last) {\n continuousNodeArray.push(current);\n current = current.nextSibling;\n }\n continuousNodeArray.push(last);\n }\n }\n return continuousNodeArray;\n },\n\n setOptionNodeSelectionState: function (optionNode, isSelected) {\n // IE6 sometimes throws \"unknown error\" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.\n if (ieVersion < 7)\n optionNode.setAttribute(\"selected\", isSelected);\n else\n optionNode.selected = isSelected;\n },\n\n stringTrim: function (string) {\n return string === null || string === undefined ? '' :\n string.trim ?\n string.trim() :\n string.toString().replace(/^[\\s\\xa0]+|[\\s\\xa0]+$/g, '');\n },\n\n stringStartsWith: function (string, startsWith) {\n string = string || \"\";\n if (startsWith.length > string.length)\n return false;\n return string.substring(0, startsWith.length) === startsWith;\n },\n\n domNodeIsContainedBy: function (node, containedByNode) {\n if (node === containedByNode)\n return true;\n if (node.nodeType === 11)\n return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8\n if (containedByNode.contains)\n return containedByNode.contains(node.nodeType !== 1 ? node.parentNode : node);\n if (containedByNode.compareDocumentPosition)\n return (containedByNode.compareDocumentPosition(node) & 16) == 16;\n while (node && node != containedByNode) {\n node = node.parentNode;\n }\n return !!node;\n },\n\n domNodeIsAttachedToDocument: function (node) {\n return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);\n },\n\n anyDomNodeIsAttachedToDocument: function(nodes) {\n return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);\n },\n\n tagNameLower: function(element) {\n // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.\n // Possible future optimization: If we know it's an element from an XHTML document (not HTML),\n // we don't need to do the .toLowerCase() as it will always be lower case anyway.\n return element && element.tagName && element.tagName.toLowerCase();\n },\n\n catchFunctionErrors: function (delegate) {\n return ko['onError'] ? function () {\n try {\n return delegate.apply(this, arguments);\n } catch (e) {\n ko['onError'] && ko['onError'](e);\n throw e;\n }\n } : delegate;\n },\n\n setTimeout: function (handler, timeout) {\n return setTimeout(ko.utils.catchFunctionErrors(handler), timeout);\n },\n\n deferError: function (error) {\n setTimeout(function () {\n ko['onError'] && ko['onError'](error);\n throw error;\n }, 0);\n },\n\n registerEventHandler: function (element, eventType, handler) {\n var wrappedHandler = ko.utils.catchFunctionErrors(handler);\n\n var mustUseAttachEvent = eventsThatMustBeRegisteredUsingAttachEvent[eventType];\n if (!ko.options['useOnlyNativeEvents'] && !mustUseAttachEvent && jQueryInstance) {\n if (!jQueryEventAttachName) {\n jQueryEventAttachName = (typeof jQueryInstance(element)['on'] == 'function') ? 'on' : 'bind';\n }\n jQueryInstance(element)[jQueryEventAttachName](eventType, wrappedHandler);\n } else if (!mustUseAttachEvent && typeof element.addEventListener == \"function\")\n element.addEventListener(eventType, wrappedHandler, false);\n else if (typeof element.attachEvent != \"undefined\") {\n var attachEventHandler = function (event) { wrappedHandler.call(element, event); },\n attachEventName = \"on\" + eventType;\n element.attachEvent(attachEventName, attachEventHandler);\n\n // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)\n // so to avoid leaks, we have to remove them manually. See bug #856\n ko.utils.domNodeDisposal.addDisposeCallback(element, function() {\n element.detachEvent(attachEventName, attachEventHandler);\n });\n } else\n throw new Error(\"Browser doesn't support addEventListener or attachEvent\");\n },\n\n triggerEvent: function (element, eventType) {\n if (!(element && element.nodeType))\n throw new Error(\"element must be a DOM node when calling triggerEvent\");\n\n // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the\n // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)\n // IE doesn't change the checked state when you trigger the click event using \"fireEvent\".\n // In both cases, we'll use the click method instead.\n var useClickWorkaround = isClickOnCheckableElement(element, eventType);\n\n if (!ko.options['useOnlyNativeEvents'] && jQueryInstance && !useClickWorkaround) {\n jQueryInstance(element)['trigger'](eventType);\n } else if (typeof document.createEvent == \"function\") {\n if (typeof element.dispatchEvent == \"function\") {\n var eventCategory = knownEventTypesByEventName[eventType] || \"HTMLEvents\";\n var event = document.createEvent(eventCategory);\n event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);\n element.dispatchEvent(event);\n }\n else\n throw new Error(\"The supplied element doesn't support dispatchEvent\");\n } else if (useClickWorkaround && element.click) {\n element.click();\n } else if (typeof element.fireEvent != \"undefined\") {\n element.fireEvent(\"on\" + eventType);\n } else {\n throw new Error(\"Browser doesn't support triggering events\");\n }\n },\n\n unwrapObservable: function (value) {\n return ko.isObservable(value) ? value() : value;\n },\n\n peekObservable: function (value) {\n return ko.isObservable(value) ? value.peek() : value;\n },\n\n toggleDomNodeCssClass: toggleDomNodeCssClass,\n\n setTextContent: function(element, textContent) {\n var value = ko.utils.unwrapObservable(textContent);\n if ((value === null) || (value === undefined))\n value = \"\";\n\n // We need there to be exactly one child: a text node.\n // If there are no children, more than one, or if it's not a text node,\n // we'll clear everything and create a single text node.\n var innerTextNode = ko.virtualElements.firstChild(element);\n if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {\n ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);\n } else {\n innerTextNode.data = value;\n }\n\n ko.utils.forceRefresh(element);\n },\n\n setElementName: function(element, name) {\n element.name = name;\n\n // Workaround IE 6/7 issue\n // - https://github.com/SteveSanderson/knockout/issues/197\n // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/\n if (ieVersion <= 7) {\n try {\n var escapedName = element.name.replace(/[&<>'\"]/g, function(r){ return \"&#\" + r.charCodeAt(0) + \";\"; });\n element.mergeAttributes(document.createElement(\"<input name='\" + escapedName + \"'/>\"), false);\n }\n catch(e) {} // For IE9 with doc mode \"IE9 Standards\" and browser mode \"IE9 Compatibility View\"\n }\n },\n\n forceRefresh: function(node) {\n // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209\n if (ieVersion >= 9) {\n // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container\n var elem = node.nodeType == 1 ? node : node.parentNode;\n if (elem.style)\n elem.style.zoom = elem.style.zoom;\n }\n },\n\n ensureSelectElementIsRenderedCorrectly: function(selectElement) {\n // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.\n // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)\n // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)\n if (ieVersion) {\n var originalWidth = selectElement.style.width;\n selectElement.style.width = 0;\n selectElement.style.width = originalWidth;\n }\n },\n\n range: function (min, max) {\n min = ko.utils.unwrapObservable(min);\n max = ko.utils.unwrapObservable(max);\n var result = [];\n for (var i = min; i <= max; i++)\n result.push(i);\n return result;\n },\n\n makeArray: function(arrayLikeObject) {\n var result = [];\n for (var i = 0, j = arrayLikeObject.length; i < j; i++) {\n result.push(arrayLikeObject[i]);\n };\n return result;\n },\n\n createSymbolOrString: function(identifier) {\n return canUseSymbols ? Symbol(identifier) : identifier;\n },\n\n isIe6 : isIe6,\n isIe7 : isIe7,\n ieVersion : ieVersion,\n\n getFormFields: function(form, fieldName) {\n var fields = ko.utils.makeArray(form.getElementsByTagName(\"input\")).concat(ko.utils.makeArray(form.getElementsByTagName(\"textarea\")));\n var isMatchingField = (typeof fieldName == 'string')\n ? function(field) { return field.name === fieldName }\n : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate\n var matches = [];\n for (var i = fields.length - 1; i >= 0; i--) {\n if (isMatchingField(fields[i]))\n matches.push(fields[i]);\n };\n return matches;\n },\n\n parseJson: function (jsonString) {\n if (typeof jsonString == \"string\") {\n jsonString = ko.utils.stringTrim(jsonString);\n if (jsonString) {\n if (JSON && JSON.parse) // Use native parsing where available\n return JSON.parse(jsonString);\n return (new Function(\"return \" + jsonString))(); // Fallback on less safe parsing for older browsers\n }\n }\n return null;\n },\n\n stringifyJson: function (data, replacer, space) { // replacer and space are optional\n if (!JSON || !JSON.stringify)\n throw new Error(\"Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js\");\n return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);\n },\n\n postJson: function (urlOrForm, data, options) {\n options = options || {};\n var params = options['params'] || {};\n var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;\n var url = urlOrForm;\n\n // If we were given a form, use its 'action' URL and pick out any requested field values\n if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === \"form\")) {\n var originalForm = urlOrForm;\n url = originalForm.action;\n for (var i = includeFields.length - 1; i >= 0; i--) {\n var fields = ko.utils.getFormFields(originalForm, includeFields[i]);\n for (var j = fields.length - 1; j >= 0; j--)\n params[fields[j].name] = fields[j].value;\n }\n }\n\n data = ko.utils.unwrapObservable(data);\n var form = document.createElement(\"form\");\n form.style.display = \"none\";\n form.action = url;\n form.method = \"post\";\n for (var key in data) {\n // Since 'data' this is a model object, we include all properties including those inherited from its prototype\n var input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = key;\n input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));\n form.appendChild(input);\n }\n objectForEach(params, function(key, value) {\n var input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = key;\n input.value = value;\n form.appendChild(input);\n });\n document.body.appendChild(form);\n options['submitter'] ? options['submitter'](form) : form.submit();\n setTimeout(function () { form.parentNode.removeChild(form); }, 0);\n }\n }\n }());\n\n ko.exportSymbol('utils', ko.utils);\n ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);\n ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);\n ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);\n ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);\n ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);\n ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);\n ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);\n ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);\n ko.exportSymbol('utils.cloneNodes', ko.utils.cloneNodes);\n ko.exportSymbol('utils.createSymbolOrString', ko.utils.createSymbolOrString);\n ko.exportSymbol('utils.extend', ko.utils.extend);\n ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);\n ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);\n ko.exportSymbol('utils.objectMap', ko.utils.objectMap);\n ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);\n ko.exportSymbol('utils.postJson', ko.utils.postJson);\n ko.exportSymbol('utils.parseJson', ko.utils.parseJson);\n ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);\n ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);\n ko.exportSymbol('utils.range', ko.utils.range);\n ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);\n ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);\n ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);\n ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);\n ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);\n ko.exportSymbol('utils.setTextContent', ko.utils.setTextContent);\n ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly\n\n if (!Function.prototype['bind']) {\n // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)\n // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js\n Function.prototype['bind'] = function (object) {\n var originalFunction = this;\n if (arguments.length === 1) {\n return function () {\n return originalFunction.apply(object, arguments);\n };\n } else {\n var partialArgs = Array.prototype.slice.call(arguments, 1);\n return function () {\n var args = partialArgs.slice(0);\n args.push.apply(args, arguments);\n return originalFunction.apply(object, args);\n };\n }\n };\n }\n\n ko.utils.domData = new (function () {\n var uniqueId = 0;\n var dataStoreKeyExpandoPropertyName = \"__ko__\" + (new Date).getTime();\n var dataStore = {};\n\n var getDataForNode, clear;\n if (!ko.utils.ieVersion) {\n // We considered using WeakMap, but it has a problem in IE 11 and Edge that prevents using\n // it cross-window, so instead we just store the data directly on the node.\n // See https://github.com/knockout/knockout/issues/2141\n getDataForNode = function (node, createIfNotFound) {\n var dataForNode = node[dataStoreKeyExpandoPropertyName];\n if (!dataForNode && createIfNotFound) {\n dataForNode = node[dataStoreKeyExpandoPropertyName] = {};\n }\n return dataForNode;\n };\n clear = function (node) {\n if (node[dataStoreKeyExpandoPropertyName]) {\n delete node[dataStoreKeyExpandoPropertyName];\n return true; // Exposing \"did clean\" flag purely so specs can infer whether things have been cleaned up as intended\n }\n return false;\n };\n } else {\n // Old IE versions have memory issues if you store objects on the node, so we use a\n // separate data storage and link to it from the node using a string key.\n getDataForNode = function (node, createIfNotFound) {\n var dataStoreKey = node[dataStoreKeyExpandoPropertyName];\n var hasExistingDataStore = dataStoreKey && (dataStoreKey !== \"null\") && dataStore[dataStoreKey];\n if (!hasExistingDataStore) {\n if (!createIfNotFound)\n return undefined;\n dataStoreKey = node[dataStoreKeyExpandoPropertyName] = \"ko\" + uniqueId++;\n dataStore[dataStoreKey] = {};\n }\n return dataStore[dataStoreKey];\n };\n clear = function (node) {\n var dataStoreKey = node[dataStoreKeyExpandoPropertyName];\n if (dataStoreKey) {\n delete dataStore[dataStoreKey];\n node[dataStoreKeyExpandoPropertyName] = null;\n return true; // Exposing \"did clean\" flag purely so specs can infer whether things have been cleaned up as intended\n }\n return false;\n };\n }\n\n return {\n get: function (node, key) {\n var dataForNode = getDataForNode(node, false);\n return dataForNode && dataForNode[key];\n },\n set: function (node, key, value) {\n // Make sure we don't actually create a new domData key if we are actually deleting a value\n var dataForNode = getDataForNode(node, value !== undefined /* createIfNotFound */);\n dataForNode && (dataForNode[key] = value);\n },\n getOrSet: function (node, key, value) {\n var dataForNode = getDataForNode(node, true /* createIfNotFound */);\n return dataForNode[key] || (dataForNode[key] = value);\n },\n clear: clear,\n\n nextKey: function () {\n return (uniqueId++) + dataStoreKeyExpandoPropertyName;\n }\n };\n })();\n\n ko.exportSymbol('utils.domData', ko.utils.domData);\n ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully\n\n ko.utils.domNodeDisposal = new (function () {\n var domDataKey = ko.utils.domData.nextKey();\n var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document\n var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document\n\n function getDisposeCallbacksCollection(node, createIfNotFound) {\n var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);\n if ((allDisposeCallbacks === undefined) && createIfNotFound) {\n allDisposeCallbacks = [];\n ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);\n }\n return allDisposeCallbacks;\n }\n function destroyCallbacksCollection(node) {\n ko.utils.domData.set(node, domDataKey, undefined);\n }\n\n function cleanSingleNode(node) {\n // Run all the dispose callbacks\n var callbacks = getDisposeCallbacksCollection(node, false);\n if (callbacks) {\n callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)\n for (var i = 0; i < callbacks.length; i++)\n callbacks[i](node);\n }\n\n // Erase the DOM data\n ko.utils.domData.clear(node);\n\n // Perform cleanup needed by external libraries (currently only jQuery, but can be extended)\n ko.utils.domNodeDisposal[\"cleanExternalData\"](node);\n\n // Clear any immediate-child comment nodes, as these wouldn't have been found by\n // node.getElementsByTagName(\"*\") in cleanNode() (comment nodes aren't elements)\n if (cleanableNodeTypesWithDescendants[node.nodeType]) {\n cleanNodesInList(node.childNodes, true/*onlyComments*/);\n }\n }\n\n function cleanNodesInList(nodeList, onlyComments) {\n var cleanedNodes = [], lastCleanedNode;\n for (var i = 0; i < nodeList.length; i++) {\n if (!onlyComments || nodeList[i].nodeType === 8) {\n cleanSingleNode(cleanedNodes[cleanedNodes.length] = lastCleanedNode = nodeList[i]);\n if (nodeList[i] !== lastCleanedNode) {\n while (i-- && ko.utils.arrayIndexOf(cleanedNodes, nodeList[i]) == -1) {}\n }\n }\n }\n }\n\n return {\n addDisposeCallback : function(node, callback) {\n if (typeof callback != \"function\")\n throw new Error(\"Callback must be a function\");\n getDisposeCallbacksCollection(node, true).push(callback);\n },\n\n removeDisposeCallback : function(node, callback) {\n var callbacksCollection = getDisposeCallbacksCollection(node, false);\n if (callbacksCollection) {\n ko.utils.arrayRemoveItem(callbacksCollection, callback);\n if (callbacksCollection.length == 0)\n destroyCallbacksCollection(node);\n }\n },\n\n cleanNode : function(node) {\n ko.dependencyDetection.ignore(function () {\n // First clean this node, where applicable\n if (cleanableNodeTypes[node.nodeType]) {\n cleanSingleNode(node);\n\n // ... then its descendants, where applicable\n if (cleanableNodeTypesWithDescendants[node.nodeType]) {\n cleanNodesInList(node.getElementsByTagName(\"*\"));\n }\n }\n });\n\n return node;\n },\n\n removeNode : function(node) {\n ko.cleanNode(node);\n if (node.parentNode)\n node.parentNode.removeChild(node);\n },\n\n \"cleanExternalData\" : function (node) {\n // Special support for jQuery here because it's so commonly used.\n // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData\n // so notify it to tear down any resources associated with the node & descendants here.\n if (jQueryInstance && (typeof jQueryInstance['cleanData'] == \"function\"))\n jQueryInstance['cleanData']([node]);\n }\n };\n })();\n ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience\n ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience\n ko.exportSymbol('cleanNode', ko.cleanNode);\n ko.exportSymbol('removeNode', ko.removeNode);\n ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);\n ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);\n ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);\n (function () {\n var none = [0, \"\", \"\"],\n table = [1, \"<table>\", \"</table>\"],\n tbody = [2, \"<table><tbody>\", \"</tbody></table>\"],\n tr = [3, \"<table><tbody><tr>\", \"</tr></tbody></table>\"],\n select = [1, \"<select multiple='multiple'>\", \"</select>\"],\n lookup = {\n 'thead': table,\n 'tbody': table,\n 'tfoot': table,\n 'tr': tbody,\n 'td': tr,\n 'th': tr,\n 'option': select,\n 'optgroup': select\n },\n\n // This is needed for old IE if you're *not* using either jQuery or innerShiv. Doesn't affect other cases.\n mayRequireCreateElementHack = ko.utils.ieVersion <= 8;\n\n function getWrap(tags) {\n var m = tags.match(/^(?:<!--.*?-->\\s*?)*?<([a-z]+)[\\s>]/);\n return (m && lookup[m[1]]) || none;\n }\n\n function simpleHtmlParse(html, documentContext) {\n documentContext || (documentContext = document);\n var windowContext = documentContext['parentWindow'] || documentContext['defaultView'] || window;\n\n // Based on jQuery's \"clean\" function, but only accounting for table-related elements.\n // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's \"clean\" function directly\n\n // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of\n // a descendant node. For example: \"<div><!-- mycomment -->abc</div>\" will get parsed as \"<div>abc</div>\"\n // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node\n // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.\n\n // Trim whitespace, otherwise indexOf won't work as expected\n var tags = ko.utils.stringTrim(html).toLowerCase(), div = documentContext.createElement(\"div\"),\n wrap = getWrap(tags),\n depth = wrap[0];\n\n // Go to html and back, then peel off extra wrappers\n // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.\n var markup = \"ignored<div>\" + wrap[1] + html + wrap[2] + \"</div>\";\n if (typeof windowContext['innerShiv'] == \"function\") {\n // Note that innerShiv is deprecated in favour of html5shiv. We should consider adding\n // support for html5shiv (except if no explicit support is needed, e.g., if html5shiv\n // somehow shims the native APIs so it just works anyway)\n div.appendChild(windowContext['innerShiv'](markup));\n } else {\n if (mayRequireCreateElementHack) {\n // The document.createElement('my-element') trick to enable custom elements in IE6-8\n // only works if we assign innerHTML on an element associated with that document.\n documentContext.body.appendChild(div);\n }\n\n div.innerHTML = markup;\n\n if (mayRequireCreateElementHack) {\n div.parentNode.removeChild(div);\n }\n }\n\n // Move to the right depth\n while (depth--)\n div = div.lastChild;\n\n return ko.utils.makeArray(div.lastChild.childNodes);\n }\n\n function jQueryHtmlParse(html, documentContext) {\n // jQuery's \"parseHTML\" function was introduced in jQuery 1.8.0 and is a documented public API.\n if (jQueryInstance['parseHTML']) {\n return jQueryInstance['parseHTML'](html, documentContext) || []; // Ensure we always return an array and never null\n } else {\n // For jQuery < 1.8.0, we fall back on the undocumented internal \"clean\" function.\n var elems = jQueryInstance['clean']([html], documentContext);\n\n // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.\n // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.\n // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.\n if (elems && elems[0]) {\n // Find the top-most parent element that's a direct child of a document fragment\n var elem = elems[0];\n while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)\n elem = elem.parentNode;\n // ... then detach it\n if (elem.parentNode)\n elem.parentNode.removeChild(elem);\n }\n\n return elems;\n }\n }\n\n ko.utils.parseHtmlFragment = function(html, documentContext) {\n return jQueryInstance ?\n jQueryHtmlParse(html, documentContext) : // As below, benefit from jQuery's optimisations where possible\n simpleHtmlParse(html, documentContext); // ... otherwise, this simple logic will do in most common cases.\n };\n\n ko.utils.parseHtmlForTemplateNodes = function(html, documentContext) {\n var nodes = ko.utils.parseHtmlFragment(html, documentContext);\n return (nodes.length && nodes[0].parentElement) || ko.utils.moveCleanedNodesToContainerElement(nodes);\n };\n\n ko.utils.setHtml = function(node, html) {\n ko.utils.emptyDomNode(node);\n\n // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it\n html = ko.utils.unwrapObservable(html);\n\n if ((html !== null) && (html !== undefined)) {\n if (typeof html != 'string')\n html = html.toString();\n\n // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,\n // for example <tr> elements which are not normally allowed to exist on their own.\n // If you've referenced jQuery we'll use that rather than duplicating its code.\n if (jQueryInstance) {\n jQueryInstance(node)['html'](html);\n } else {\n // ... otherwise, use KO's own parsing logic.\n var parsedNodes = ko.utils.parseHtmlFragment(html, node.ownerDocument);\n for (var i = 0; i < parsedNodes.length; i++)\n node.appendChild(parsedNodes[i]);\n }\n }\n };\n })();\n\n ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);\n ko.exportSymbol('utils.setHtml', ko.utils.setHtml);\n\n ko.memoization = (function () {\n var memos = {};\n\n function randomMax8HexChars() {\n return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);\n }\n function generateRandomId() {\n return randomMax8HexChars() + randomMax8HexChars();\n }\n function findMemoNodes(rootNode, appendToArray) {\n if (!rootNode)\n return;\n if (rootNode.nodeType == 8) {\n var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);\n if (memoId != null)\n appendToArray.push({ domNode: rootNode, memoId: memoId });\n } else if (rootNode.nodeType == 1) {\n for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)\n findMemoNodes(childNodes[i], appendToArray);\n }\n }\n\n return {\n memoize: function (callback) {\n if (typeof callback != \"function\")\n throw new Error(\"You can only pass a function to ko.memoization.memoize()\");\n var memoId = generateRandomId();\n memos[memoId] = callback;\n return \"<!--[ko_memo:\" + memoId + \"]-->\";\n },\n\n unmemoize: function (memoId, callbackParams) {\n var callback = memos[memoId];\n if (callback === undefined)\n throw new Error(\"Couldn't find any memo with ID \" + memoId + \". Perhaps it's already been unmemoized.\");\n try {\n callback.apply(null, callbackParams || []);\n return true;\n }\n finally { delete memos[memoId]; }\n },\n\n unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {\n var memos = [];\n findMemoNodes(domNode, memos);\n for (var i = 0, j = memos.length; i < j; i++) {\n var node = memos[i].domNode;\n var combinedParams = [node];\n if (extraCallbackParamsArray)\n ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);\n ko.memoization.unmemoize(memos[i].memoId, combinedParams);\n node.nodeValue = \"\"; // Neuter this node so we don't try to unmemoize it again\n if (node.parentNode)\n node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)\n }\n },\n\n parseMemoText: function (memoText) {\n var match = memoText.match(/^\\[ko_memo\\:(.*?)\\]$/);\n return match ? match[1] : null;\n }\n };\n })();\n\n ko.exportSymbol('memoization', ko.memoization);\n ko.exportSymbol('memoization.memoize', ko.memoization.memoize);\n ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);\n ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);\n ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);\n ko.tasks = (function () {\n var scheduler,\n taskQueue = [],\n taskQueueLength = 0,\n nextHandle = 1,\n nextIndexToProcess = 0;\n\n if (window['MutationObserver']) {\n // Chrome 27+, Firefox 14+, IE 11+, Opera 15+, Safari 6.1+\n // From https://github.com/petkaantonov/bluebird * Copyright (c) 2014 Petka Antonov * License: MIT\n scheduler = (function (callback) {\n var div = document.createElement(\"div\");\n new MutationObserver(callback).observe(div, {attributes: true});\n return function () { div.classList.toggle(\"foo\"); };\n })(scheduledProcess);\n } else if (document && \"onreadystatechange\" in document.createElement(\"script\")) {\n // IE 6-10\n // From https://github.com/YuzuJS/setImmediate * Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola * License: MIT\n scheduler = function (callback) {\n var script = document.createElement(\"script\");\n script.onreadystatechange = function () {\n script.onreadystatechange = null;\n document.documentElement.removeChild(script);\n script = null;\n callback();\n };\n document.documentElement.appendChild(script);\n };\n } else {\n scheduler = function (callback) {\n setTimeout(callback, 0);\n };\n }\n\n function processTasks() {\n if (taskQueueLength) {\n // Each mark represents the end of a logical group of tasks and the number of these groups is\n // limited to prevent unchecked recursion.\n var mark = taskQueueLength, countMarks = 0;\n\n // nextIndexToProcess keeps track of where we are in the queue; processTasks can be called recursively without issue\n for (var task; nextIndexToProcess < taskQueueLength; ) {\n if (task = taskQueue[nextIndexToProcess++]) {\n if (nextIndexToProcess > mark) {\n if (++countMarks >= 5000) {\n nextIndexToProcess = taskQueueLength; // skip all tasks remaining in the queue since any of them could be causing the recursion\n ko.utils.deferError(Error(\"'Too much recursion' after processing \" + countMarks + \" task groups.\"));\n break;\n }\n mark = taskQueueLength;\n }\n try {\n task();\n } catch (ex) {\n ko.utils.deferError(ex);\n }\n }\n }\n }\n }\n\n function scheduledProcess() {\n processTasks();\n\n // Reset the queue\n nextIndexToProcess = taskQueueLength = taskQueue.length = 0;\n }\n\n function scheduleTaskProcessing() {\n ko.tasks['scheduler'](scheduledProcess);\n }\n\n var tasks = {\n 'scheduler': scheduler, // Allow overriding the scheduler\n\n schedule: function (func) {\n if (!taskQueueLength) {\n scheduleTaskProcessing();\n }\n\n taskQueue[taskQueueLength++] = func;\n return nextHandle++;\n },\n\n cancel: function (handle) {\n var index = handle - (nextHandle - taskQueueLength);\n if (index >= nextIndexToProcess && index < taskQueueLength) {\n taskQueue[index] = null;\n }\n },\n\n // For testing only: reset the queue and return the previous queue length\n 'resetForTesting': function () {\n var length = taskQueueLength - nextIndexToProcess;\n nextIndexToProcess = taskQueueLength = taskQueue.length = 0;\n return length;\n },\n\n runEarly: processTasks\n };\n\n return tasks;\n })();\n\n ko.exportSymbol('tasks', ko.tasks);\n ko.exportSymbol('tasks.schedule', ko.tasks.schedule);\n//ko.exportSymbol('tasks.cancel', ko.tasks.cancel); \"cancel\" isn't minified\n ko.exportSymbol('tasks.runEarly', ko.tasks.runEarly);\n ko.extenders = {\n 'throttle': function(target, timeout) {\n // Throttling means two things:\n\n // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies\n // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate\n target['throttleEvaluation'] = timeout;\n\n // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*\n // so the target cannot change value synchronously or faster than a certain rate\n var writeTimeoutInstance = null;\n return ko.dependentObservable({\n 'read': target,\n 'write': function(value) {\n clearTimeout(writeTimeoutInstance);\n writeTimeoutInstance = ko.utils.setTimeout(function() {\n target(value);\n }, timeout);\n }\n });\n },\n\n 'rateLimit': function(target, options) {\n var timeout, method, limitFunction;\n\n if (typeof options == 'number') {\n timeout = options;\n } else {\n timeout = options['timeout'];\n method = options['method'];\n }\n\n // rateLimit supersedes deferred updates\n target._deferUpdates = false;\n\n limitFunction = typeof method == 'function' ? method : method == 'notifyWhenChangesStop' ? debounce : throttle;\n target.limit(function(callback) {\n return limitFunction(callback, timeout, options);\n });\n },\n\n 'deferred': function(target, options) {\n if (options !== true) {\n throw new Error('The \\'deferred\\' extender only accepts the value \\'true\\', because it is not supported to turn deferral off once enabled.')\n }\n\n if (!target._deferUpdates) {\n target._deferUpdates = true;\n target.limit(function (callback) {\n var handle,\n ignoreUpdates = false;\n return function () {\n if (!ignoreUpdates) {\n ko.tasks.cancel(handle);\n handle = ko.tasks.schedule(callback);\n\n try {\n ignoreUpdates = true;\n target['notifySubscribers'](undefined, 'dirty');\n } finally {\n ignoreUpdates = false;\n }\n }\n };\n });\n }\n },\n\n 'notify': function(target, notifyWhen) {\n target[\"equalityComparer\"] = notifyWhen == \"always\" ?\n null : // null equalityComparer means to always notify\n valuesArePrimitiveAndEqual;\n }\n };\n\n var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };\n function valuesArePrimitiveAndEqual(a, b) {\n var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);\n return oldValueIsPrimitive ? (a === b) : false;\n }\n\n function throttle(callback, timeout) {\n var timeoutInstance;\n return function () {\n if (!timeoutInstance) {\n timeoutInstance = ko.utils.setTimeout(function () {\n timeoutInstance = undefined;\n callback();\n }, timeout);\n }\n };\n }\n\n function debounce(callback, timeout) {\n var timeoutInstance;\n return function () {\n clearTimeout(timeoutInstance);\n timeoutInstance = ko.utils.setTimeout(callback, timeout);\n };\n }\n\n function applyExtenders(requestedExtenders) {\n var target = this;\n if (requestedExtenders) {\n ko.utils.objectForEach(requestedExtenders, function(key, value) {\n var extenderHandler = ko.extenders[key];\n if (typeof extenderHandler == 'function') {\n target = extenderHandler(target, value) || target;\n }\n });\n }\n return target;\n }\n\n ko.exportSymbol('extenders', ko.extenders);\n\n ko.subscription = function (target, callback, disposeCallback) {\n this._target = target;\n this._callback = callback;\n this._disposeCallback = disposeCallback;\n this._isDisposed = false;\n this._node = null;\n this._domNodeDisposalCallback = null;\n ko.exportProperty(this, 'dispose', this.dispose);\n ko.exportProperty(this, 'disposeWhenNodeIsRemoved', this.disposeWhenNodeIsRemoved);\n };\n ko.subscription.prototype.dispose = function () {\n var self = this;\n if (!self._isDisposed) {\n if (self._domNodeDisposalCallback) {\n ko.utils.domNodeDisposal.removeDisposeCallback(self._node, self._domNodeDisposalCallback);\n }\n self._isDisposed = true;\n self._disposeCallback();\n\n self._target = self._callback = self._disposeCallback = self._node = self._domNodeDisposalCallback = null;\n }\n };\n ko.subscription.prototype.disposeWhenNodeIsRemoved = function (node) {\n this._node = node;\n ko.utils.domNodeDisposal.addDisposeCallback(node, this._domNodeDisposalCallback = this.dispose.bind(this));\n };\n\n ko.subscribable = function () {\n ko.utils.setPrototypeOfOrExtend(this, ko_subscribable_fn);\n ko_subscribable_fn.init(this);\n }\n\n var defaultEvent = \"change\";\n\n// Moved out of \"limit\" to avoid the extra closure\n function limitNotifySubscribers(value, event) {\n if (!event || event === defaultEvent) {\n this._limitChange(value);\n } else if (event === 'beforeChange') {\n this._limitBeforeChange(value);\n } else {\n this._origNotifySubscribers(value, event);\n }\n }\n\n var ko_subscribable_fn = {\n init: function(instance) {\n instance._subscriptions = { \"change\": [] };\n instance._versionNumber = 1;\n },\n\n subscribe: function (callback, callbackTarget, event) {\n var self = this;\n\n event = event || defaultEvent;\n var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;\n\n var subscription = new ko.subscription(self, boundCallback, function () {\n ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);\n if (self.afterSubscriptionRemove)\n self.afterSubscriptionRemove(event);\n });\n\n if (self.beforeSubscriptionAdd)\n self.beforeSubscriptionAdd(event);\n\n if (!self._subscriptions[event])\n self._subscriptions[event] = [];\n self._subscriptions[event].push(subscription);\n\n return subscription;\n },\n\n \"notifySubscribers\": function (valueToNotify, event) {\n event = event || defaultEvent;\n if (event === defaultEvent) {\n this.updateVersion();\n }\n if (this.hasSubscriptionsForEvent(event)) {\n var subs = event === defaultEvent && this._changeSubscriptions || this._subscriptions[event].slice(0);\n try {\n ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)\n for (var i = 0, subscription; subscription = subs[i]; ++i) {\n // In case a subscription was disposed during the arrayForEach cycle, check\n // for isDisposed on each subscription before invoking its callback\n if (!subscription._isDisposed)\n subscription._callback(valueToNotify);\n }\n } finally {\n ko.dependencyDetection.end(); // End suppressing dependency detection\n }\n }\n },\n\n getVersion: function () {\n return this._versionNumber;\n },\n\n hasChanged: function (versionToCheck) {\n return this.getVersion() !== versionToCheck;\n },\n\n updateVersion: function () {\n ++this._versionNumber;\n },\n\n limit: function(limitFunction) {\n var self = this, selfIsObservable = ko.isObservable(self),\n ignoreBeforeChange, notifyNextChange, previousValue, pendingValue, didUpdate,\n beforeChange = 'beforeChange';\n\n if (!self._origNotifySubscribers) {\n self._origNotifySubscribers = self[\"notifySubscribers\"];\n self[\"notifySubscribers\"] = limitNotifySubscribers;\n }\n\n var finish = limitFunction(function() {\n self._notificationIsPending = false;\n\n // If an observable provided a reference to itself, access it to get the latest value.\n // This allows computed observables to delay calculating their value until needed.\n if (selfIsObservable && pendingValue === self) {\n pendingValue = self._evalIfChanged ? self._evalIfChanged() : self();\n }\n var shouldNotify = notifyNextChange || (didUpdate && self.isDifferent(previousValue, pendingValue));\n\n didUpdate = notifyNextChange = ignoreBeforeChange = false;\n\n if (shouldNotify) {\n self._origNotifySubscribers(previousValue = pendingValue);\n }\n });\n\n self._limitChange = function(value, isDirty) {\n if (!isDirty || !self._notificationIsPending) {\n didUpdate = !isDirty;\n }\n self._changeSubscriptions = self._subscriptions[defaultEvent].slice(0);\n self._notificationIsPending = ignoreBeforeChange = true;\n pendingValue = value;\n finish();\n };\n self._limitBeforeChange = function(value) {\n if (!ignoreBeforeChange) {\n previousValue = value;\n self._origNotifySubscribers(value, beforeChange);\n }\n };\n self._recordUpdate = function() {\n didUpdate = true;\n };\n self._notifyNextChangeIfValueIsDifferent = function() {\n if (self.isDifferent(previousValue, self.peek(true /*evaluate*/))) {\n notifyNextChange = true;\n }\n };\n },\n\n hasSubscriptionsForEvent: function(event) {\n return this._subscriptions[event] && this._subscriptions[event].length;\n },\n\n getSubscriptionsCount: function (event) {\n if (event) {\n return this._subscriptions[event] && this._subscriptions[event].length || 0;\n } else {\n var total = 0;\n ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {\n if (eventName !== 'dirty')\n total += subscriptions.length;\n });\n return total;\n }\n },\n\n isDifferent: function(oldValue, newValue) {\n return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);\n },\n\n toString: function() {\n return '[object Object]'\n },\n\n extend: applyExtenders\n };\n\n ko.exportProperty(ko_subscribable_fn, 'init', ko_subscribable_fn.init);\n ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);\n ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);\n ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);\n\n// For browsers that support proto assignment, we overwrite the prototype of each\n// observable instance. Since observables are functions, we need Function.prototype\n// to still be in the prototype chain.\n if (ko.utils.canSetPrototype) {\n ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);\n }\n\n ko.subscribable['fn'] = ko_subscribable_fn;\n\n\n ko.isSubscribable = function (instance) {\n return instance != null && typeof instance.subscribe == \"function\" && typeof instance[\"notifySubscribers\"] == \"function\";\n };\n\n ko.exportSymbol('subscribable', ko.subscribable);\n ko.exportSymbol('isSubscribable', ko.isSubscribable);\n\n ko.computedContext = ko.dependencyDetection = (function () {\n var outerFrames = [],\n currentFrame,\n lastId = 0;\n\n // Return a unique ID that can be assigned to an observable for dependency tracking.\n // Theoretically, you could eventually overflow the number storage size, resulting\n // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53\n // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would\n // take over 285 years to reach that number.\n // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html\n function getId() {\n return ++lastId;\n }\n\n function begin(options) {\n outerFrames.push(currentFrame);\n currentFrame = options;\n }\n\n function end() {\n currentFrame = outerFrames.pop();\n }\n\n return {\n begin: begin,\n\n end: end,\n\n registerDependency: function (subscribable) {\n if (currentFrame) {\n if (!ko.isSubscribable(subscribable))\n throw new Error(\"Only subscribable things can act as dependencies\");\n currentFrame.callback.call(currentFrame.callbackTarget, subscribable, subscribable._id || (subscribable._id = getId()));\n }\n },\n\n ignore: function (callback, callbackTarget, callbackArgs) {\n try {\n begin();\n return callback.apply(callbackTarget, callbackArgs || []);\n } finally {\n end();\n }\n },\n\n getDependenciesCount: function () {\n if (currentFrame)\n return currentFrame.computed.getDependenciesCount();\n },\n\n getDependencies: function () {\n if (currentFrame)\n return currentFrame.computed.getDependencies();\n },\n\n isInitial: function() {\n if (currentFrame)\n return currentFrame.isInitial;\n },\n\n computed: function() {\n if (currentFrame)\n return currentFrame.computed;\n }\n };\n })();\n\n ko.exportSymbol('computedContext', ko.computedContext);\n ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);\n ko.exportSymbol('computedContext.getDependencies', ko.computedContext.getDependencies);\n ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);\n ko.exportSymbol('computedContext.registerDependency', ko.computedContext.registerDependency);\n\n ko.exportSymbol('ignoreDependencies', ko.ignoreDependencies = ko.dependencyDetection.ignore);\n var observableLatestValue = ko.utils.createSymbolOrString('_latestValue');\n\n ko.observable = function (initialValue) {\n function observable() {\n if (arguments.length > 0) {\n // Write\n\n // Ignore writes if the value hasn't changed\n if (observable.isDifferent(observable[observableLatestValue], arguments[0])) {\n observable.valueWillMutate();\n observable[observableLatestValue] = arguments[0];\n observable.valueHasMutated();\n }\n return this; // Permits chained assignments\n }\n else {\n // Read\n ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a \"read\" operation\n return observable[observableLatestValue];\n }\n }\n\n observable[observableLatestValue] = initialValue;\n\n // Inherit from 'subscribable'\n if (!ko.utils.canSetPrototype) {\n // 'subscribable' won't be on the prototype chain unless we put it there directly\n ko.utils.extend(observable, ko.subscribable['fn']);\n }\n ko.subscribable['fn'].init(observable);\n\n // Inherit from 'observable'\n ko.utils.setPrototypeOfOrExtend(observable, observableFn);\n\n if (ko.options['deferUpdates']) {\n ko.extenders['deferred'](observable, true);\n }\n\n return observable;\n }\n\n// Define prototype for observables\n var observableFn = {\n 'equalityComparer': valuesArePrimitiveAndEqual,\n peek: function() { return this[observableLatestValue]; },\n valueHasMutated: function () {\n this['notifySubscribers'](this[observableLatestValue], 'spectate');\n this['notifySubscribers'](this[observableLatestValue]);\n },\n valueWillMutate: function () { this['notifySubscribers'](this[observableLatestValue], 'beforeChange'); }\n };\n\n// Note that for browsers that don't support proto assignment, the\n// inheritance chain is created manually in the ko.observable constructor\n if (ko.utils.canSetPrototype) {\n ko.utils.setPrototypeOf(observableFn, ko.subscribable['fn']);\n }\n\n var protoProperty = ko.observable.protoProperty = '__ko_proto__';\n observableFn[protoProperty] = ko.observable;\n\n ko.isObservable = function (instance) {\n var proto = typeof instance == 'function' && instance[protoProperty];\n if (proto && proto !== observableFn[protoProperty] && proto !== ko.computed['fn'][protoProperty]) {\n throw Error(\"Invalid object that looks like an observable; possibly from another Knockout instance\");\n }\n return !!proto;\n };\n\n ko.isWriteableObservable = function (instance) {\n return (typeof instance == 'function' && (\n (instance[protoProperty] === observableFn[protoProperty]) || // Observable\n (instance[protoProperty] === ko.computed['fn'][protoProperty] && instance.hasWriteFunction))); // Writable computed observable\n };\n\n ko.exportSymbol('observable', ko.observable);\n ko.exportSymbol('isObservable', ko.isObservable);\n ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);\n ko.exportSymbol('isWritableObservable', ko.isWriteableObservable);\n ko.exportSymbol('observable.fn', observableFn);\n ko.exportProperty(observableFn, 'peek', observableFn.peek);\n ko.exportProperty(observableFn, 'valueHasMutated', observableFn.valueHasMutated);\n ko.exportProperty(observableFn, 'valueWillMutate', observableFn.valueWillMutate);\n ko.observableArray = function (initialValues) {\n initialValues = initialValues || [];\n\n if (typeof initialValues != 'object' || !('length' in initialValues))\n throw new Error(\"The argument passed when initializing an observable array must be an array, or null, or undefined.\");\n\n var result = ko.observable(initialValues);\n ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);\n return result.extend({'trackArrayChanges':true});\n };\n\n ko.observableArray['fn'] = {\n 'remove': function (valueOrPredicate) {\n var underlyingArray = this.peek();\n var removedValues = [];\n var predicate = typeof valueOrPredicate == \"function\" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };\n for (var i = 0; i < underlyingArray.length; i++) {\n var value = underlyingArray[i];\n if (predicate(value)) {\n if (removedValues.length === 0) {\n this.valueWillMutate();\n }\n if (underlyingArray[i] !== value) {\n throw Error(\"Array modified during remove; cannot remove item\");\n }\n removedValues.push(value);\n underlyingArray.splice(i, 1);\n i--;\n }\n }\n if (removedValues.length) {\n this.valueHasMutated();\n }\n return removedValues;\n },\n\n 'removeAll': function (arrayOfValues) {\n // If you passed zero args, we remove everything\n if (arrayOfValues === undefined) {\n var underlyingArray = this.peek();\n var allValues = underlyingArray.slice(0);\n this.valueWillMutate();\n underlyingArray.splice(0, underlyingArray.length);\n this.valueHasMutated();\n return allValues;\n }\n // If you passed an arg, we interpret it as an array of entries to remove\n if (!arrayOfValues)\n return [];\n return this['remove'](function (value) {\n return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;\n });\n },\n\n 'destroy': function (valueOrPredicate) {\n var underlyingArray = this.peek();\n var predicate = typeof valueOrPredicate == \"function\" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };\n this.valueWillMutate();\n for (var i = underlyingArray.length - 1; i >= 0; i--) {\n var value = underlyingArray[i];\n if (predicate(value))\n value[\"_destroy\"] = true;\n }\n this.valueHasMutated();\n },\n\n 'destroyAll': function (arrayOfValues) {\n // If you passed zero args, we destroy everything\n if (arrayOfValues === undefined)\n return this['destroy'](function() { return true });\n\n // If you passed an arg, we interpret it as an array of entries to destroy\n if (!arrayOfValues)\n return [];\n return this['destroy'](function (value) {\n return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;\n });\n },\n\n 'indexOf': function (item) {\n var underlyingArray = this();\n return ko.utils.arrayIndexOf(underlyingArray, item);\n },\n\n 'replace': function(oldItem, newItem) {\n var index = this['indexOf'](oldItem);\n if (index >= 0) {\n this.valueWillMutate();\n this.peek()[index] = newItem;\n this.valueHasMutated();\n }\n },\n\n 'sorted': function (compareFunction) {\n var arrayCopy = this().slice(0);\n return compareFunction ? arrayCopy.sort(compareFunction) : arrayCopy.sort();\n },\n\n 'reversed': function () {\n return this().slice(0).reverse();\n }\n };\n\n// Note that for browsers that don't support proto assignment, the\n// inheritance chain is created manually in the ko.observableArray constructor\n if (ko.utils.canSetPrototype) {\n ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);\n }\n\n// Populate ko.observableArray.fn with read/write functions from native arrays\n// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array\n// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale\n ko.utils.arrayForEach([\"pop\", \"push\", \"reverse\", \"shift\", \"sort\", \"splice\", \"unshift\"], function (methodName) {\n ko.observableArray['fn'][methodName] = function () {\n // Use \"peek\" to avoid creating a subscription in any computed that we're executing in the context of\n // (for consistency with mutating regular observables)\n var underlyingArray = this.peek();\n this.valueWillMutate();\n this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);\n var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);\n this.valueHasMutated();\n // The native sort and reverse methods return a reference to the array, but it makes more sense to return the observable array instead.\n return methodCallResult === underlyingArray ? this : methodCallResult;\n };\n });\n\n// Populate ko.observableArray.fn with read-only functions from native arrays\n ko.utils.arrayForEach([\"slice\"], function (methodName) {\n ko.observableArray['fn'][methodName] = function () {\n var underlyingArray = this();\n return underlyingArray[methodName].apply(underlyingArray, arguments);\n };\n });\n\n ko.isObservableArray = function (instance) {\n return ko.isObservable(instance)\n && typeof instance[\"remove\"] == \"function\"\n && typeof instance[\"push\"] == \"function\";\n };\n\n ko.exportSymbol('observableArray', ko.observableArray);\n ko.exportSymbol('isObservableArray', ko.isObservableArray);\n var arrayChangeEventName = 'arrayChange';\n ko.extenders['trackArrayChanges'] = function(target, options) {\n // Use the provided options--each call to trackArrayChanges overwrites the previously set options\n target.compareArrayOptions = {};\n if (options && typeof options == \"object\") {\n ko.utils.extend(target.compareArrayOptions, options);\n }\n target.compareArrayOptions['sparse'] = true;\n\n // Only modify the target observable once\n if (target.cacheDiffForKnownOperation) {\n return;\n }\n var trackingChanges = false,\n cachedDiff = null,\n changeSubscription,\n spectateSubscription,\n pendingChanges = 0,\n previousContents,\n underlyingBeforeSubscriptionAddFunction = target.beforeSubscriptionAdd,\n underlyingAfterSubscriptionRemoveFunction = target.afterSubscriptionRemove;\n\n // Watch \"subscribe\" calls, and for array change events, ensure change tracking is enabled\n target.beforeSubscriptionAdd = function (event) {\n if (underlyingBeforeSubscriptionAddFunction) {\n underlyingBeforeSubscriptionAddFunction.call(target, event);\n }\n if (event === arrayChangeEventName) {\n trackChanges();\n }\n };\n // Watch \"dispose\" calls, and for array change events, ensure change tracking is disabled when all are disposed\n target.afterSubscriptionRemove = function (event) {\n if (underlyingAfterSubscriptionRemoveFunction) {\n underlyingAfterSubscriptionRemoveFunction.call(target, event);\n }\n if (event === arrayChangeEventName && !target.hasSubscriptionsForEvent(arrayChangeEventName)) {\n if (changeSubscription) {\n changeSubscription.dispose();\n }\n if (spectateSubscription) {\n spectateSubscription.dispose();\n }\n spectateSubscription = changeSubscription = null;\n trackingChanges = false;\n previousContents = undefined;\n }\n };\n\n function trackChanges() {\n if (trackingChanges) {\n // Whenever there's a new subscription and there are pending notifications, make sure all previous\n // subscriptions are notified of the change so that all subscriptions are in sync.\n notifyChanges();\n return;\n }\n\n trackingChanges = true;\n\n // Track how many times the array actually changed value\n spectateSubscription = target.subscribe(function () {\n ++pendingChanges;\n }, null, \"spectate\");\n\n // Each time the array changes value, capture a clone so that on the next\n // change it's possible to produce a diff\n previousContents = [].concat(target.peek() || []);\n cachedDiff = null;\n changeSubscription = target.subscribe(notifyChanges);\n\n function notifyChanges() {\n if (pendingChanges) {\n // Make a copy of the current contents and ensure it's an array\n var currentContents = [].concat(target.peek() || []), changes;\n\n // Compute the diff and issue notifications, but only if someone is listening\n if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {\n changes = getChanges(previousContents, currentContents);\n }\n\n // Eliminate references to the old, removed items, so they can be GCed\n previousContents = currentContents;\n cachedDiff = null;\n pendingChanges = 0;\n\n if (changes && changes.length) {\n target['notifySubscribers'](changes, arrayChangeEventName);\n }\n }\n }\n }\n\n function getChanges(previousContents, currentContents) {\n // We try to re-use cached diffs.\n // The scenarios where pendingChanges > 1 are when using rate limiting or deferred updates,\n // which without this check would not be compatible with arrayChange notifications. Normally,\n // notifications are issued immediately so we wouldn't be queueing up more than one.\n if (!cachedDiff || pendingChanges > 1) {\n cachedDiff = ko.utils.compareArrays(previousContents, currentContents, target.compareArrayOptions);\n }\n\n return cachedDiff;\n }\n\n target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {\n // Only run if we're currently tracking changes for this observable array\n // and there aren't any pending deferred notifications.\n if (!trackingChanges || pendingChanges) {\n return;\n }\n var diff = [],\n arrayLength = rawArray.length,\n argsLength = args.length,\n offset = 0;\n\n function pushDiff(status, value, index) {\n return diff[diff.length] = { 'status': status, 'value': value, 'index': index };\n }\n switch (operationName) {\n case 'push':\n offset = arrayLength;\n case 'unshift':\n for (var index = 0; index < argsLength; index++) {\n pushDiff('added', args[index], offset + index);\n }\n break;\n\n case 'pop':\n offset = arrayLength - 1;\n case 'shift':\n if (arrayLength) {\n pushDiff('deleted', rawArray[offset], offset);\n }\n break;\n\n case 'splice':\n // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\n var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),\n endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),\n endAddIndex = startIndex + argsLength - 2,\n endIndex = Math.max(endDeleteIndex, endAddIndex),\n additions = [], deletions = [];\n for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {\n if (index < endDeleteIndex)\n deletions.push(pushDiff('deleted', rawArray[index], index));\n if (index < endAddIndex)\n additions.push(pushDiff('added', args[argsIndex], index));\n }\n ko.utils.findMovesInArrayComparison(deletions, additions);\n break;\n\n default:\n return;\n }\n cachedDiff = diff;\n };\n };\n var computedState = ko.utils.createSymbolOrString('_state');\n\n ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {\n if (typeof evaluatorFunctionOrOptions === \"object\") {\n // Single-parameter syntax - everything is on this \"options\" param\n options = evaluatorFunctionOrOptions;\n } else {\n // Multi-parameter syntax - construct the options according to the params passed\n options = options || {};\n if (evaluatorFunctionOrOptions) {\n options[\"read\"] = evaluatorFunctionOrOptions;\n }\n }\n if (typeof options[\"read\"] != \"function\")\n throw Error(\"Pass a function that returns the value of the ko.computed\");\n\n var writeFunction = options[\"write\"];\n var state = {\n latestValue: undefined,\n isStale: true,\n isDirty: true,\n isBeingEvaluated: false,\n suppressDisposalUntilDisposeWhenReturnsFalse: false,\n isDisposed: false,\n pure: false,\n isSleeping: false,\n readFunction: options[\"read\"],\n evaluatorFunctionTarget: evaluatorFunctionTarget || options[\"owner\"],\n disposeWhenNodeIsRemoved: options[\"disposeWhenNodeIsRemoved\"] || options.disposeWhenNodeIsRemoved || null,\n disposeWhen: options[\"disposeWhen\"] || options.disposeWhen,\n domNodeDisposalCallback: null,\n dependencyTracking: {},\n dependenciesCount: 0,\n evaluationTimeoutInstance: null\n };\n\n function computedObservable() {\n if (arguments.length > 0) {\n if (typeof writeFunction === \"function\") {\n // Writing a value\n writeFunction.apply(state.evaluatorFunctionTarget, arguments);\n } else {\n throw new Error(\"Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.\");\n }\n return this; // Permits chained assignments\n } else {\n // Reading the value\n if (!state.isDisposed) {\n ko.dependencyDetection.registerDependency(computedObservable);\n }\n if (state.isDirty || (state.isSleeping && computedObservable.haveDependenciesChanged())) {\n computedObservable.evaluateImmediate();\n }\n return state.latestValue;\n }\n }\n\n computedObservable[computedState] = state;\n computedObservable.hasWriteFunction = typeof writeFunction === \"function\";\n\n // Inherit from 'subscribable'\n if (!ko.utils.canSetPrototype) {\n // 'subscribable' won't be on the prototype chain unless we put it there directly\n ko.utils.extend(computedObservable, ko.subscribable['fn']);\n }\n ko.subscribable['fn'].init(computedObservable);\n\n // Inherit from 'computed'\n ko.utils.setPrototypeOfOrExtend(computedObservable, computedFn);\n\n if (options['pure']) {\n state.pure = true;\n state.isSleeping = true; // Starts off sleeping; will awake on the first subscription\n ko.utils.extend(computedObservable, pureComputedOverrides);\n } else if (options['deferEvaluation']) {\n ko.utils.extend(computedObservable, deferEvaluationOverrides);\n }\n\n if (ko.options['deferUpdates']) {\n ko.extenders['deferred'](computedObservable, true);\n }\n\n if (DEBUG) {\n // #1731 - Aid debugging by exposing the computed's options\n computedObservable[\"_options\"] = options;\n }\n\n if (state.disposeWhenNodeIsRemoved) {\n // Since this computed is associated with a DOM node, and we don't want to dispose the computed\n // until the DOM node is *removed* from the document (as opposed to never having been in the document),\n // we'll prevent disposal until \"disposeWhen\" first returns false.\n state.suppressDisposalUntilDisposeWhenReturnsFalse = true;\n\n // disposeWhenNodeIsRemoved: true can be used to opt into the \"only dispose after first false result\"\n // behaviour even if there's no specific node to watch. In that case, clear the option so we don't try\n // to watch for a non-node's disposal. This technique is intended for KO's internal use only and shouldn't\n // be documented or used by application code, as it's likely to change in a future version of KO.\n if (!state.disposeWhenNodeIsRemoved.nodeType) {\n state.disposeWhenNodeIsRemoved = null;\n }\n }\n\n // Evaluate, unless sleeping or deferEvaluation is true\n if (!state.isSleeping && !options['deferEvaluation']) {\n computedObservable.evaluateImmediate();\n }\n\n // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is\n // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).\n if (state.disposeWhenNodeIsRemoved && computedObservable.isActive()) {\n ko.utils.domNodeDisposal.addDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback = function () {\n computedObservable.dispose();\n });\n }\n\n return computedObservable;\n };\n\n// Utility function that disposes a given dependencyTracking entry\n function computedDisposeDependencyCallback(id, entryToDispose) {\n if (entryToDispose !== null && entryToDispose.dispose) {\n entryToDispose.dispose();\n }\n }\n\n// This function gets called each time a dependency is detected while evaluating a computed.\n// It's factored out as a shared function to avoid creating unnecessary function instances during evaluation.\n function computedBeginDependencyDetectionCallback(subscribable, id) {\n var computedObservable = this.computedObservable,\n state = computedObservable[computedState];\n if (!state.isDisposed) {\n if (this.disposalCount && this.disposalCandidates[id]) {\n // Don't want to dispose this subscription, as it's still being used\n computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);\n this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway\n --this.disposalCount;\n } else if (!state.dependencyTracking[id]) {\n // Brand new subscription - add it\n computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));\n }\n // If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)\n if (subscribable._notificationIsPending) {\n subscribable._notifyNextChangeIfValueIsDifferent();\n }\n }\n }\n\n var computedFn = {\n \"equalityComparer\": valuesArePrimitiveAndEqual,\n getDependenciesCount: function () {\n return this[computedState].dependenciesCount;\n },\n getDependencies: function () {\n var dependencyTracking = this[computedState].dependencyTracking, dependentObservables = [];\n\n ko.utils.objectForEach(dependencyTracking, function (id, dependency) {\n dependentObservables[dependency._order] = dependency._target;\n });\n\n return dependentObservables;\n },\n hasAncestorDependency: function (obs) {\n if (!this[computedState].dependenciesCount) {\n return false;\n }\n var dependencies = this.getDependencies();\n if (ko.utils.arrayIndexOf(dependencies, obs) !== -1) {\n return true;\n }\n return !!ko.utils.arrayFirst(dependencies, function (dep) {\n return dep.hasAncestorDependency && dep.hasAncestorDependency(obs);\n });\n },\n addDependencyTracking: function (id, target, trackingObj) {\n if (this[computedState].pure && target === this) {\n throw Error(\"A 'pure' computed must not be called recursively\");\n }\n\n this[computedState].dependencyTracking[id] = trackingObj;\n trackingObj._order = this[computedState].dependenciesCount++;\n trackingObj._version = target.getVersion();\n },\n haveDependenciesChanged: function () {\n var id, dependency, dependencyTracking = this[computedState].dependencyTracking;\n for (id in dependencyTracking) {\n if (Object.prototype.hasOwnProperty.call(dependencyTracking, id)) {\n dependency = dependencyTracking[id];\n if ((this._evalDelayed && dependency._target._notificationIsPending) || dependency._target.hasChanged(dependency._version)) {\n return true;\n }\n }\n }\n },\n markDirty: function () {\n // Process \"dirty\" events if we can handle delayed notifications\n if (this._evalDelayed && !this[computedState].isBeingEvaluated) {\n this._evalDelayed(false /*isChange*/);\n }\n },\n isActive: function () {\n var state = this[computedState];\n return state.isDirty || state.dependenciesCount > 0;\n },\n respondToChange: function () {\n // Ignore \"change\" events if we've already scheduled a delayed notification\n if (!this._notificationIsPending) {\n this.evaluatePossiblyAsync();\n } else if (this[computedState].isDirty) {\n this[computedState].isStale = true;\n }\n },\n subscribeToDependency: function (target) {\n if (target._deferUpdates) {\n var dirtySub = target.subscribe(this.markDirty, this, 'dirty'),\n changeSub = target.subscribe(this.respondToChange, this);\n return {\n _target: target,\n dispose: function () {\n dirtySub.dispose();\n changeSub.dispose();\n }\n };\n } else {\n return target.subscribe(this.evaluatePossiblyAsync, this);\n }\n },\n evaluatePossiblyAsync: function () {\n var computedObservable = this,\n throttleEvaluationTimeout = computedObservable['throttleEvaluation'];\n if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {\n clearTimeout(this[computedState].evaluationTimeoutInstance);\n this[computedState].evaluationTimeoutInstance = ko.utils.setTimeout(function () {\n computedObservable.evaluateImmediate(true /*notifyChange*/);\n }, throttleEvaluationTimeout);\n } else if (computedObservable._evalDelayed) {\n computedObservable._evalDelayed(true /*isChange*/);\n } else {\n computedObservable.evaluateImmediate(true /*notifyChange*/);\n }\n },\n evaluateImmediate: function (notifyChange) {\n var computedObservable = this,\n state = computedObservable[computedState],\n disposeWhen = state.disposeWhen,\n changed = false;\n\n if (state.isBeingEvaluated) {\n // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.\n // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost\n // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing\n // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387\n return;\n }\n\n // Do not evaluate (and possibly capture new dependencies) if disposed\n if (state.isDisposed) {\n return;\n }\n\n if (state.disposeWhenNodeIsRemoved && !ko.utils.domNodeIsAttachedToDocument(state.disposeWhenNodeIsRemoved) || disposeWhen && disposeWhen()) {\n // See comment above about suppressDisposalUntilDisposeWhenReturnsFalse\n if (!state.suppressDisposalUntilDisposeWhenReturnsFalse) {\n computedObservable.dispose();\n return;\n }\n } else {\n // It just did return false, so we can stop suppressing now\n state.suppressDisposalUntilDisposeWhenReturnsFalse = false;\n }\n\n state.isBeingEvaluated = true;\n try {\n changed = this.evaluateImmediate_CallReadWithDependencyDetection(notifyChange);\n } finally {\n state.isBeingEvaluated = false;\n }\n\n return changed;\n },\n evaluateImmediate_CallReadWithDependencyDetection: function (notifyChange) {\n // This function is really just part of the evaluateImmediate logic. You would never call it from anywhere else.\n // Factoring it out into a separate function means it can be independent of the try/catch block in evaluateImmediate,\n // which contributes to saving about 40% off the CPU overhead of computed evaluation (on V8 at least).\n\n var computedObservable = this,\n state = computedObservable[computedState],\n changed = false;\n\n // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).\n // Then, during evaluation, we cross off any that are in fact still being used.\n var isInitial = state.pure ? undefined : !state.dependenciesCount, // If we're evaluating when there are no previous dependencies, it must be the first time\n dependencyDetectionContext = {\n computedObservable: computedObservable,\n disposalCandidates: state.dependencyTracking,\n disposalCount: state.dependenciesCount\n };\n\n ko.dependencyDetection.begin({\n callbackTarget: dependencyDetectionContext,\n callback: computedBeginDependencyDetectionCallback,\n computed: computedObservable,\n isInitial: isInitial\n });\n\n state.dependencyTracking = {};\n state.dependenciesCount = 0;\n\n var newValue = this.evaluateImmediate_CallReadThenEndDependencyDetection(state, dependencyDetectionContext);\n\n if (!state.dependenciesCount) {\n computedObservable.dispose();\n changed = true; // When evaluation causes a disposal, make sure all dependent computeds get notified so they'll see the new state\n } else {\n changed = computedObservable.isDifferent(state.latestValue, newValue);\n }\n\n if (changed) {\n if (!state.isSleeping) {\n computedObservable[\"notifySubscribers\"](state.latestValue, \"beforeChange\");\n } else {\n computedObservable.updateVersion();\n }\n\n state.latestValue = newValue;\n if (DEBUG) computedObservable._latestValue = newValue;\n\n computedObservable[\"notifySubscribers\"](state.latestValue, \"spectate\");\n\n if (!state.isSleeping && notifyChange) {\n computedObservable[\"notifySubscribers\"](state.latestValue);\n }\n if (computedObservable._recordUpdate) {\n computedObservable._recordUpdate();\n }\n }\n\n if (isInitial) {\n computedObservable[\"notifySubscribers\"](state.latestValue, \"awake\");\n }\n\n return changed;\n },\n evaluateImmediate_CallReadThenEndDependencyDetection: function (state, dependencyDetectionContext) {\n // This function is really part of the evaluateImmediate_CallReadWithDependencyDetection logic.\n // You'd never call it from anywhere else. Factoring it out means that evaluateImmediate_CallReadWithDependencyDetection\n // can be independent of try/finally blocks, which contributes to saving about 40% off the CPU\n // overhead of computed evaluation (on V8 at least).\n\n try {\n var readFunction = state.readFunction;\n return state.evaluatorFunctionTarget ? readFunction.call(state.evaluatorFunctionTarget) : readFunction();\n } finally {\n ko.dependencyDetection.end();\n\n // For each subscription no longer being used, remove it from the active subscriptions list and dispose it\n if (dependencyDetectionContext.disposalCount && !state.isSleeping) {\n ko.utils.objectForEach(dependencyDetectionContext.disposalCandidates, computedDisposeDependencyCallback);\n }\n\n state.isStale = state.isDirty = false;\n }\n },\n peek: function (evaluate) {\n // By default, peek won't re-evaluate, except while the computed is sleeping or to get the initial value when \"deferEvaluation\" is set.\n // Pass in true to evaluate if needed.\n var state = this[computedState];\n if ((state.isDirty && (evaluate || !state.dependenciesCount)) || (state.isSleeping && this.haveDependenciesChanged())) {\n this.evaluateImmediate();\n }\n return state.latestValue;\n },\n limit: function (limitFunction) {\n // Override the limit function with one that delays evaluation as well\n ko.subscribable['fn'].limit.call(this, limitFunction);\n this._evalIfChanged = function () {\n if (!this[computedState].isSleeping) {\n if (this[computedState].isStale) {\n this.evaluateImmediate();\n } else {\n this[computedState].isDirty = false;\n }\n }\n return this[computedState].latestValue;\n };\n this._evalDelayed = function (isChange) {\n this._limitBeforeChange(this[computedState].latestValue);\n\n // Mark as dirty\n this[computedState].isDirty = true;\n if (isChange) {\n this[computedState].isStale = true;\n }\n\n // Pass the observable to the \"limit\" code, which will evaluate it when\n // it's time to do the notification.\n this._limitChange(this, !isChange /* isDirty */);\n };\n },\n dispose: function () {\n var state = this[computedState];\n if (!state.isSleeping && state.dependencyTracking) {\n ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {\n if (dependency.dispose)\n dependency.dispose();\n });\n }\n if (state.disposeWhenNodeIsRemoved && state.domNodeDisposalCallback) {\n ko.utils.domNodeDisposal.removeDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback);\n }\n state.dependencyTracking = undefined;\n state.dependenciesCount = 0;\n state.isDisposed = true;\n state.isStale = false;\n state.isDirty = false;\n state.isSleeping = false;\n state.disposeWhenNodeIsRemoved = undefined;\n state.disposeWhen = undefined;\n state.readFunction = undefined;\n if (!this.hasWriteFunction) {\n state.evaluatorFunctionTarget = undefined;\n }\n }\n };\n\n var pureComputedOverrides = {\n beforeSubscriptionAdd: function (event) {\n // If asleep, wake up the computed by subscribing to any dependencies.\n var computedObservable = this,\n state = computedObservable[computedState];\n if (!state.isDisposed && state.isSleeping && event == 'change') {\n state.isSleeping = false;\n if (state.isStale || computedObservable.haveDependenciesChanged()) {\n state.dependencyTracking = null;\n state.dependenciesCount = 0;\n if (computedObservable.evaluateImmediate()) {\n computedObservable.updateVersion();\n }\n } else {\n // First put the dependencies in order\n var dependenciesOrder = [];\n ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {\n dependenciesOrder[dependency._order] = id;\n });\n // Next, subscribe to each one\n ko.utils.arrayForEach(dependenciesOrder, function (id, order) {\n var dependency = state.dependencyTracking[id],\n subscription = computedObservable.subscribeToDependency(dependency._target);\n subscription._order = order;\n subscription._version = dependency._version;\n state.dependencyTracking[id] = subscription;\n });\n // Waking dependencies may have triggered effects\n if (computedObservable.haveDependenciesChanged()) {\n if (computedObservable.evaluateImmediate()) {\n computedObservable.updateVersion();\n }\n }\n }\n\n if (!state.isDisposed) { // test since evaluating could trigger disposal\n computedObservable[\"notifySubscribers\"](state.latestValue, \"awake\");\n }\n }\n },\n afterSubscriptionRemove: function (event) {\n var state = this[computedState];\n if (!state.isDisposed && event == 'change' && !this.hasSubscriptionsForEvent('change')) {\n ko.utils.objectForEach(state.dependencyTracking, function (id, dependency) {\n if (dependency.dispose) {\n state.dependencyTracking[id] = {\n _target: dependency._target,\n _order: dependency._order,\n _version: dependency._version\n };\n dependency.dispose();\n }\n });\n state.isSleeping = true;\n this[\"notifySubscribers\"](undefined, \"asleep\");\n }\n },\n getVersion: function () {\n // Because a pure computed is not automatically updated while it is sleeping, we can't\n // simply return the version number. Instead, we check if any of the dependencies have\n // changed and conditionally re-evaluate the computed observable.\n var state = this[computedState];\n if (state.isSleeping && (state.isStale || this.haveDependenciesChanged())) {\n this.evaluateImmediate();\n }\n return ko.subscribable['fn'].getVersion.call(this);\n }\n };\n\n var deferEvaluationOverrides = {\n beforeSubscriptionAdd: function (event) {\n // This will force a computed with deferEvaluation to evaluate when the first subscription is registered.\n if (event == 'change' || event == 'beforeChange') {\n this.peek();\n }\n }\n };\n\n// Note that for browsers that don't support proto assignment, the\n// inheritance chain is created manually in the ko.computed constructor\n if (ko.utils.canSetPrototype) {\n ko.utils.setPrototypeOf(computedFn, ko.subscribable['fn']);\n }\n\n// Set the proto values for ko.computed\n var protoProp = ko.observable.protoProperty; // == \"__ko_proto__\"\n computedFn[protoProp] = ko.computed;\n\n ko.isComputed = function (instance) {\n return (typeof instance == 'function' && instance[protoProp] === computedFn[protoProp]);\n };\n\n ko.isPureComputed = function (instance) {\n return ko.isComputed(instance) && instance[computedState] && instance[computedState].pure;\n };\n\n ko.exportSymbol('computed', ko.computed);\n ko.exportSymbol('dependentObservable', ko.computed); // export ko.dependentObservable for backwards compatibility (1.x)\n ko.exportSymbol('isComputed', ko.isComputed);\n ko.exportSymbol('isPureComputed', ko.isPureComputed);\n ko.exportSymbol('computed.fn', computedFn);\n ko.exportProperty(computedFn, 'peek', computedFn.peek);\n ko.exportProperty(computedFn, 'dispose', computedFn.dispose);\n ko.exportProperty(computedFn, 'isActive', computedFn.isActive);\n ko.exportProperty(computedFn, 'getDependenciesCount', computedFn.getDependenciesCount);\n ko.exportProperty(computedFn, 'getDependencies', computedFn.getDependencies);\n\n ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) {\n if (typeof evaluatorFunctionOrOptions === 'function') {\n return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, {'pure':true});\n } else {\n evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object\n evaluatorFunctionOrOptions['pure'] = true;\n return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget);\n }\n }\n ko.exportSymbol('pureComputed', ko.pureComputed);\n\n (function() {\n var maxNestedObservableDepth = 10; // Escape the (unlikely) pathological case where an observable's current value is itself (or similar reference cycle)\n\n ko.toJS = function(rootObject) {\n if (arguments.length == 0)\n throw new Error(\"When calling ko.toJS, pass the object you want to convert.\");\n\n // We just unwrap everything at every level in the object graph\n return mapJsObjectGraph(rootObject, function(valueToMap) {\n // Loop because an observable's value might in turn be another observable wrapper\n for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)\n valueToMap = valueToMap();\n return valueToMap;\n });\n };\n\n ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional\n var plainJavaScriptObject = ko.toJS(rootObject);\n return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);\n };\n\n function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {\n visitedObjects = visitedObjects || new objectLookup();\n\n rootObject = mapInputCallback(rootObject);\n var canHaveProperties = (typeof rootObject == \"object\") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof RegExp)) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));\n if (!canHaveProperties)\n return rootObject;\n\n var outputProperties = rootObject instanceof Array ? [] : {};\n visitedObjects.save(rootObject, outputProperties);\n\n visitPropertiesOrArrayEntries(rootObject, function(indexer) {\n var propertyValue = mapInputCallback(rootObject[indexer]);\n\n switch (typeof propertyValue) {\n case \"boolean\":\n case \"number\":\n case \"string\":\n case \"function\":\n outputProperties[indexer] = propertyValue;\n break;\n case \"object\":\n case \"undefined\":\n var previouslyMappedValue = visitedObjects.get(propertyValue);\n outputProperties[indexer] = (previouslyMappedValue !== undefined)\n ? previouslyMappedValue\n : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);\n break;\n }\n });\n\n return outputProperties;\n }\n\n function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {\n if (rootObject instanceof Array) {\n for (var i = 0; i < rootObject.length; i++)\n visitorCallback(i);\n\n // For arrays, also respect toJSON property for custom mappings (fixes #278)\n if (typeof rootObject['toJSON'] == 'function')\n visitorCallback('toJSON');\n } else {\n for (var propertyName in rootObject) {\n visitorCallback(propertyName);\n }\n }\n };\n\n function objectLookup() {\n this.keys = [];\n this.values = [];\n };\n\n objectLookup.prototype = {\n constructor: objectLookup,\n save: function(key, value) {\n var existingIndex = ko.utils.arrayIndexOf(this.keys, key);\n if (existingIndex >= 0)\n this.values[existingIndex] = value;\n else {\n this.keys.push(key);\n this.values.push(value);\n }\n },\n get: function(key) {\n var existingIndex = ko.utils.arrayIndexOf(this.keys, key);\n return (existingIndex >= 0) ? this.values[existingIndex] : undefined;\n }\n };\n })();\n\n ko.exportSymbol('toJS', ko.toJS);\n ko.exportSymbol('toJSON', ko.toJSON);\n ko.when = function(predicate, callback, context) {\n function kowhen (resolve) {\n var observable = ko.pureComputed(predicate, context).extend({notify:'always'});\n var subscription = observable.subscribe(function(value) {\n if (value) {\n subscription.dispose();\n resolve(value);\n }\n });\n // In case the initial value is true, process it right away\n observable['notifySubscribers'](observable.peek());\n\n return subscription;\n }\n if (typeof Promise === \"function\" && !callback) {\n return new Promise(kowhen);\n } else {\n return kowhen(callback.bind(context));\n }\n };\n\n ko.exportSymbol('when', ko.when);\n (function () {\n var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';\n\n // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values\n // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values\n // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.\n ko.selectExtensions = {\n readValue : function(element) {\n switch (ko.utils.tagNameLower(element)) {\n case 'option':\n if (element[hasDomDataExpandoProperty] === true)\n return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);\n return ko.utils.ieVersion <= 7\n ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)\n : element.value;\n case 'select':\n return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;\n default:\n return element.value;\n }\n },\n\n writeValue: function(element, value, allowUnset) {\n switch (ko.utils.tagNameLower(element)) {\n case 'option':\n if (typeof value === \"string\") {\n ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);\n if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node\n delete element[hasDomDataExpandoProperty];\n }\n element.value = value;\n }\n else {\n // Store arbitrary object using DomData\n ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);\n element[hasDomDataExpandoProperty] = true;\n\n // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.\n element.value = typeof value === \"number\" ? value : \"\";\n }\n break;\n case 'select':\n if (value === \"\" || value === null) // A blank string or null value will select the caption\n value = undefined;\n var selection = -1;\n for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {\n optionValue = ko.selectExtensions.readValue(element.options[i]);\n // Include special check to handle selecting a caption with a blank string value\n if (optionValue == value || (optionValue === \"\" && value === undefined)) {\n selection = i;\n break;\n }\n }\n if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {\n element.selectedIndex = selection;\n if (ko.utils.ieVersion === 6) {\n // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread\n // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread\n // to apply the value as well.\n ko.utils.setTimeout(function () {\n element.selectedIndex = selection;\n }, 0);\n }\n }\n break;\n default:\n if ((value === null) || (value === undefined))\n value = \"\";\n element.value = value;\n break;\n }\n }\n };\n })();\n\n ko.exportSymbol('selectExtensions', ko.selectExtensions);\n ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);\n ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);\n ko.expressionRewriting = (function () {\n var javaScriptReservedWords = [\"true\", \"false\", \"null\", \"undefined\"];\n\n // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor\n // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).\n // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).\n var javaScriptAssignmentTarget = /^(?:[$_a-z][$\\w]*|(.+)(\\.\\s*[$_a-z][$\\w]*|\\[.+\\]))$/i;\n\n function getWriteableValue(expression) {\n if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)\n return false;\n var match = expression.match(javaScriptAssignmentTarget);\n return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;\n }\n\n // The following regular expressions will be used to split an object-literal string into tokens\n\n var specials = ',\"\\'`{}()/:[\\\\]', // These characters have special meaning to the parser and must not appear in the middle of a token, except as part of a string.\n // Create the actual regular expression by or-ing the following regex strings. The order is important.\n bindingToken = RegExp([\n // These match strings, either with double quotes, single quotes, or backticks\n '\"(?:\\\\\\\\.|[^\"])*\"',\n \"'(?:\\\\\\\\.|[^'])*'\",\n \"`(?:\\\\\\\\.|[^`])*`\",\n // Match C style comments\n \"/\\\\*(?:[^*]|\\\\*+[^*/])*\\\\*+/\",\n // Match C++ style comments\n \"//.*\\n\",\n // Match a regular expression (text enclosed by slashes), but will also match sets of divisions\n // as a regular expression (this is handled by the parsing loop below).\n '/(?:\\\\\\\\.|[^/])+/\\w*',\n // Match text (at least two characters) that does not contain any of the above special characters,\n // although some of the special characters are allowed to start it (all but the colon and comma).\n // The text can contain spaces, but leading or trailing spaces are skipped.\n '[^\\\\s:,/][^' + specials + ']*[^\\\\s' + specials + ']',\n // Match any non-space character not matched already. This will match colons and commas, since they're\n // not matched by \"everyThingElse\", but will also match any other single character that wasn't already\n // matched (for example: in \"a: 1, b: 2\", each of the non-space characters will be matched by oneNotSpace).\n '[^\\\\s]'\n ].join('|'), 'g'),\n\n // Match end of previous token to determine whether a slash is a division or regex.\n divisionLookBehind = /[\\])\"'A-Za-z0-9_$]+$/,\n keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};\n\n function parseObjectLiteral(objectLiteralString) {\n // Trim leading and trailing spaces from the string\n var str = ko.utils.stringTrim(objectLiteralString);\n\n // Trim braces '{' surrounding the whole object literal\n if (str.charCodeAt(0) === 123) str = str.slice(1, -1);\n\n // Add a newline to correctly match a C++ style comment at the end of the string and\n // add a comma so that we don't need a separate code block to deal with the last item\n str += \"\\n,\";\n\n // Split into tokens\n var result = [], toks = str.match(bindingToken), key, values = [], depth = 0;\n\n if (toks.length > 1) {\n for (var i = 0, tok; tok = toks[i]; ++i) {\n var c = tok.charCodeAt(0);\n // A comma signals the end of a key/value pair if depth is zero\n if (c === 44) { // \",\"\n if (depth <= 0) {\n result.push((key && values.length) ? {key: key, value: values.join('')} : {'unknown': key || values.join('')});\n key = depth = 0;\n values = [];\n continue;\n }\n // Simply skip the colon that separates the name and value\n } else if (c === 58) { // \":\"\n if (!depth && !key && values.length === 1) {\n key = values.pop();\n continue;\n }\n // Comments: skip them\n } else if (c === 47 && tok.length > 1 && (tok.charCodeAt(1) === 47 || tok.charCodeAt(1) === 42)) { // \"//\" or \"/*\"\n continue;\n // A set of slashes is initially matched as a regular expression, but could be division\n } else if (c === 47 && i && tok.length > 1) { // \"/\"\n // Look at the end of the previous token to determine if the slash is actually division\n var match = toks[i-1].match(divisionLookBehind);\n if (match && !keywordRegexLookBehind[match[0]]) {\n // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)\n str = str.substr(str.indexOf(tok) + 1);\n toks = str.match(bindingToken);\n i = -1;\n // Continue with just the slash\n tok = '/';\n }\n // Increment depth for parentheses, braces, and brackets so that interior commas are ignored\n } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['\n ++depth;\n } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'\n --depth;\n // The key will be the first token; if it's a string, trim the quotes\n } else if (!key && !values.length && (c === 34 || c === 39)) { // '\"', \"'\"\n tok = tok.slice(1, -1);\n }\n values.push(tok);\n }\n if (depth > 0) {\n throw Error(\"Unbalanced parentheses, braces, or brackets\");\n }\n }\n return result;\n }\n\n // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.\n var twoWayBindings = {};\n\n function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {\n bindingOptions = bindingOptions || {};\n\n function processKeyValue(key, val) {\n var writableVal;\n function callPreprocessHook(obj) {\n return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;\n }\n if (!bindingParams) {\n if (!callPreprocessHook(ko['getBindingHandler'](key)))\n return;\n\n if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {\n // For two-way bindings, provide a write method in case the value\n // isn't a writable observable.\n var writeKey = typeof twoWayBindings[key] == 'string' ? twoWayBindings[key] : key;\n propertyAccessorResultStrings.push(\"'\" + writeKey + \"':function(_z){\" + writableVal + \"=_z}\");\n }\n }\n // Values are wrapped in a function so that each value can be accessed independently\n if (makeValueAccessors) {\n val = 'function(){return ' + val + ' }';\n }\n resultStrings.push(\"'\" + key + \"':\" + val);\n }\n\n var resultStrings = [],\n propertyAccessorResultStrings = [],\n makeValueAccessors = bindingOptions['valueAccessors'],\n bindingParams = bindingOptions['bindingParams'],\n keyValueArray = typeof bindingsStringOrKeyValueArray === \"string\" ?\n parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;\n\n ko.utils.arrayForEach(keyValueArray, function(keyValue) {\n processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);\n });\n\n if (propertyAccessorResultStrings.length)\n processKeyValue('_ko_property_writers', \"{\" + propertyAccessorResultStrings.join(\",\") + \" }\");\n\n return resultStrings.join(\",\");\n }\n\n return {\n bindingRewriteValidators: [],\n\n twoWayBindings: twoWayBindings,\n\n parseObjectLiteral: parseObjectLiteral,\n\n preProcessBindings: preProcessBindings,\n\n keyValueArrayContainsKey: function(keyValueArray, key) {\n for (var i = 0; i < keyValueArray.length; i++)\n if (keyValueArray[i]['key'] == key)\n return true;\n return false;\n },\n\n // Internal, private KO utility for updating model properties from within bindings\n // property: If the property being updated is (or might be) an observable, pass it here\n // If it turns out to be a writable observable, it will be written to directly\n // allBindings: An object with a get method to retrieve bindings in the current execution context.\n // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable\n // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'\n // value: The value to be written\n // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if\n // it is !== existing value on that writable observable\n writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {\n if (!property || !ko.isObservable(property)) {\n var propWriters = allBindings.get('_ko_property_writers');\n if (propWriters && propWriters[key])\n propWriters[key](value);\n } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {\n property(value);\n }\n }\n };\n })();\n\n ko.exportSymbol('expressionRewriting', ko.expressionRewriting);\n ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);\n ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);\n ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);\n\n// Making bindings explicitly declare themselves as \"two way\" isn't ideal in the long term (it would be better if\n// all bindings could use an official 'property writer' API without needing to declare that they might). However,\n// since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable\n// as an internal implementation detail in the short term.\n// For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an\n// undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official\n// public API, and we reserve the right to remove it at any time if we create a real public property writers API.\n ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);\n\n// For backward compatibility, define the following aliases. (Previously, these function names were misleading because\n// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)\n ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);\n ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);\n (function() {\n // \"Virtual elements\" is an abstraction on top of the usual DOM API which understands the notion that comment nodes\n // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).\n // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state\n // of that virtual hierarchy\n //\n // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)\n // without having to scatter special cases all over the binding and templating code.\n\n // IE 9 cannot reliably read the \"nodeValue\" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)\n // but it does give them a nonstandard alternative property called \"text\" that it can read reliably. Other browsers don't have that property.\n // So, use node.text where available, and node.nodeValue elsewhere\n var commentNodesHaveTextProperty = document && document.createComment(\"test\").text === \"<!--test-->\";\n\n var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\\s*ko(?:\\s+([\\s\\S]+))?\\s*-->$/ : /^\\s*ko(?:\\s+([\\s\\S]+))?\\s*$/;\n var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\\s*\\/ko\\s*-->$/ : /^\\s*\\/ko\\s*$/;\n var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };\n\n function isStartComment(node) {\n return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);\n }\n\n function isEndComment(node) {\n return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);\n }\n\n function isUnmatchedEndComment(node) {\n return isEndComment(node) && !(ko.utils.domData.get(node, matchedEndCommentDataKey));\n }\n\n var matchedEndCommentDataKey = \"__ko_matchedEndComment__\"\n\n function getVirtualChildren(startComment, allowUnbalanced) {\n var currentNode = startComment;\n var depth = 1;\n var children = [];\n while (currentNode = currentNode.nextSibling) {\n if (isEndComment(currentNode)) {\n ko.utils.domData.set(currentNode, matchedEndCommentDataKey, true);\n depth--;\n if (depth === 0)\n return children;\n }\n\n children.push(currentNode);\n\n if (isStartComment(currentNode))\n depth++;\n }\n if (!allowUnbalanced)\n throw new Error(\"Cannot find closing comment tag to match: \" + startComment.nodeValue);\n return null;\n }\n\n function getMatchingEndComment(startComment, allowUnbalanced) {\n var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);\n if (allVirtualChildren) {\n if (allVirtualChildren.length > 0)\n return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;\n return startComment.nextSibling;\n } else\n return null; // Must have no matching end comment, and allowUnbalanced is true\n }\n\n function getUnbalancedChildTags(node) {\n // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>\n // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->\n var childNode = node.firstChild, captureRemaining = null;\n if (childNode) {\n do {\n if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes\n captureRemaining.push(childNode);\n else if (isStartComment(childNode)) {\n var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);\n if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set\n childNode = matchingEndComment;\n else\n captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point\n } else if (isEndComment(childNode)) {\n captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing\n }\n } while (childNode = childNode.nextSibling);\n }\n return captureRemaining;\n }\n\n ko.virtualElements = {\n allowedBindings: {},\n\n childNodes: function(node) {\n return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;\n },\n\n emptyNode: function(node) {\n if (!isStartComment(node))\n ko.utils.emptyDomNode(node);\n else {\n var virtualChildren = ko.virtualElements.childNodes(node);\n for (var i = 0, j = virtualChildren.length; i < j; i++)\n ko.removeNode(virtualChildren[i]);\n }\n },\n\n setDomNodeChildren: function(node, childNodes) {\n if (!isStartComment(node))\n ko.utils.setDomNodeChildren(node, childNodes);\n else {\n ko.virtualElements.emptyNode(node);\n var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children\n for (var i = 0, j = childNodes.length; i < j; i++)\n endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);\n }\n },\n\n prepend: function(containerNode, nodeToPrepend) {\n var insertBeforeNode;\n\n if (isStartComment(containerNode)) {\n // Start comments must always have a parent and at least one following sibling (the end comment)\n insertBeforeNode = containerNode.nextSibling;\n containerNode = containerNode.parentNode;\n } else {\n insertBeforeNode = containerNode.firstChild;\n }\n\n if (!insertBeforeNode) {\n containerNode.appendChild(nodeToPrepend);\n } else if (nodeToPrepend !== insertBeforeNode) { // IE will sometimes crash if you try to insert a node before itself\n containerNode.insertBefore(nodeToPrepend, insertBeforeNode);\n }\n },\n\n insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {\n if (!insertAfterNode) {\n ko.virtualElements.prepend(containerNode, nodeToInsert);\n } else {\n // Children of start comments must always have a parent and at least one following sibling (the end comment)\n var insertBeforeNode = insertAfterNode.nextSibling;\n\n if (isStartComment(containerNode)) {\n containerNode = containerNode.parentNode;\n }\n\n if (!insertBeforeNode) {\n containerNode.appendChild(nodeToInsert);\n } else if (nodeToInsert !== insertBeforeNode) { // IE will sometimes crash if you try to insert a node before itself\n containerNode.insertBefore(nodeToInsert, insertBeforeNode);\n }\n }\n },\n\n firstChild: function(node) {\n if (!isStartComment(node)) {\n if (node.firstChild && isEndComment(node.firstChild)) {\n throw new Error(\"Found invalid end comment, as the first child of \" + node);\n }\n return node.firstChild;\n } else if (!node.nextSibling || isEndComment(node.nextSibling)) {\n return null;\n } else {\n return node.nextSibling;\n }\n },\n\n nextSibling: function(node) {\n if (isStartComment(node)) {\n node = getMatchingEndComment(node);\n }\n\n if (node.nextSibling && isEndComment(node.nextSibling)) {\n if (isUnmatchedEndComment(node.nextSibling)) {\n throw Error(\"Found end comment without a matching opening comment, as child of \" + node);\n } else {\n return null;\n }\n } else {\n return node.nextSibling;\n }\n },\n\n hasBindingValue: isStartComment,\n\n virtualNodeBindingValue: function(node) {\n var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);\n return regexMatch ? regexMatch[1] : null;\n },\n\n normaliseVirtualElementDomStructure: function(elementVerified) {\n // Workaround for https://github.com/SteveSanderson/knockout/issues/155\n // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes\n // that are direct descendants of <ul> into the preceding <li>)\n if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])\n return;\n\n // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags\n // must be intended to appear *after* that child, so move them there.\n var childNode = elementVerified.firstChild;\n if (childNode) {\n do {\n if (childNode.nodeType === 1) {\n var unbalancedTags = getUnbalancedChildTags(childNode);\n if (unbalancedTags) {\n // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child\n var nodeToInsertBefore = childNode.nextSibling;\n for (var i = 0; i < unbalancedTags.length; i++) {\n if (nodeToInsertBefore)\n elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);\n else\n elementVerified.appendChild(unbalancedTags[i]);\n }\n }\n }\n } while (childNode = childNode.nextSibling);\n }\n }\n };\n })();\n ko.exportSymbol('virtualElements', ko.virtualElements);\n ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);\n ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);\n//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified\n ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);\n//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified\n ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);\n ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);\n (function() {\n var defaultBindingAttributeName = \"data-bind\";\n\n ko.bindingProvider = function() {\n this.bindingCache = {};\n };\n\n ko.utils.extend(ko.bindingProvider.prototype, {\n 'nodeHasBindings': function(node) {\n switch (node.nodeType) {\n case 1: // Element\n return node.getAttribute(defaultBindingAttributeName) != null\n || ko.components['getComponentNameForNode'](node);\n case 8: // Comment node\n return ko.virtualElements.hasBindingValue(node);\n default: return false;\n }\n },\n\n 'getBindings': function(node, bindingContext) {\n var bindingsString = this['getBindingsString'](node, bindingContext),\n parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;\n return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false);\n },\n\n 'getBindingAccessors': function(node, bindingContext) {\n var bindingsString = this['getBindingsString'](node, bindingContext),\n parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null;\n return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true);\n },\n\n // The following function is only used internally by this default provider.\n // It's not part of the interface definition for a general binding provider.\n 'getBindingsString': function(node, bindingContext) {\n switch (node.nodeType) {\n case 1: return node.getAttribute(defaultBindingAttributeName); // Element\n case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node\n default: return null;\n }\n },\n\n // The following function is only used internally by this default provider.\n // It's not part of the interface definition for a general binding provider.\n 'parseBindingsString': function(bindingsString, bindingContext, node, options) {\n try {\n var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);\n return bindingFunction(bindingContext, node);\n } catch (ex) {\n ex.message = \"Unable to parse bindings.\\nBindings value: \" + bindingsString + \"\\nMessage: \" + ex.message;\n throw ex;\n }\n }\n });\n\n ko.bindingProvider['instance'] = new ko.bindingProvider();\n\n function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {\n var cacheKey = bindingsString + (options && options['valueAccessors'] || '');\n return cache[cacheKey]\n || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));\n }\n\n function createBindingsStringEvaluator(bindingsString, options) {\n // Build the source for a function that evaluates \"expression\"\n // For each scope variable, add an extra level of \"with\" nesting\n // Example result: with(sc1) { with(sc0) { return (expression) } }\n var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),\n functionBody = \"with($context){with($data||{}){return{\" + rewrittenBindings + \"}}}\";\n return new Function(\"$context\", \"$element\", functionBody);\n }\n })();\n\n ko.exportSymbol('bindingProvider', ko.bindingProvider);\n (function () {\n // Hide or don't minify context properties, see https://github.com/knockout/knockout/issues/2294\n var contextSubscribable = ko.utils.createSymbolOrString('_subscribable');\n var contextAncestorBindingInfo = ko.utils.createSymbolOrString('_ancestorBindingInfo');\n var contextDataDependency = ko.utils.createSymbolOrString('_dataDependency');\n\n ko.bindingHandlers = {};\n\n // The following element types will not be recursed into during binding.\n var bindingDoesNotRecurseIntoElementTypes = {\n // Don't want bindings that operate on text nodes to mutate <script> and <textarea> contents,\n // because it's unexpected and a potential XSS issue.\n // Also bindings should not operate on <template> elements since this breaks in Internet Explorer\n // and because such elements' contents are always intended to be bound in a different context\n // from where they appear in the document.\n 'script': true,\n 'textarea': true,\n 'template': true\n };\n\n // Use an overridable method for retrieving binding handlers so that plugins may support dynamically created handlers\n ko['getBindingHandler'] = function(bindingKey) {\n return ko.bindingHandlers[bindingKey];\n };\n\n var inheritParentVm = {};\n\n // The ko.bindingContext constructor is only called directly to create the root context. For child\n // contexts, use bindingContext.createChildContext or bindingContext.extend.\n ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, options) {\n\n // The binding context object includes static properties for the current, parent, and root view models.\n // If a view model is actually stored in an observable, the corresponding binding context object, and\n // any child contexts, must be updated when the view model is changed.\n function updateContext() {\n // Most of the time, the context will directly get a view model object, but if a function is given,\n // we call the function to retrieve the view model. If the function accesses any observables or returns\n // an observable, the dependency is tracked, and those observables can later cause the binding\n // context to be updated.\n var dataItemOrObservable = isFunc ? realDataItemOrAccessor() : realDataItemOrAccessor,\n dataItem = ko.utils.unwrapObservable(dataItemOrObservable);\n\n if (parentContext) {\n // Copy $root and any custom properties from the parent context\n ko.utils.extend(self, parentContext);\n\n // Copy Symbol properties\n if (contextAncestorBindingInfo in parentContext) {\n self[contextAncestorBindingInfo] = parentContext[contextAncestorBindingInfo];\n }\n } else {\n self['$parents'] = [];\n self['$root'] = dataItem;\n\n // Export 'ko' in the binding context so it will be available in bindings and templates\n // even if 'ko' isn't exported as a global, such as when using an AMD loader.\n // See https://github.com/SteveSanderson/knockout/issues/490\n self['ko'] = ko;\n }\n\n self[contextSubscribable] = subscribable;\n\n if (shouldInheritData) {\n dataItem = self['$data'];\n } else {\n self['$rawData'] = dataItemOrObservable;\n self['$data'] = dataItem;\n }\n\n if (dataItemAlias)\n self[dataItemAlias] = dataItem;\n\n // The extendCallback function is provided when creating a child context or extending a context.\n // It handles the specific actions needed to finish setting up the binding context. Actions in this\n // function could also add dependencies to this binding context.\n if (extendCallback)\n extendCallback(self, parentContext, dataItem);\n\n // When a \"parent\" context is given and we don't already have a dependency on its context, register a dependency on it.\n // Thus whenever the parent context is updated, this context will also be updated.\n if (parentContext && parentContext[contextSubscribable] && !ko.computedContext.computed().hasAncestorDependency(parentContext[contextSubscribable])) {\n parentContext[contextSubscribable]();\n }\n\n if (dataDependency) {\n self[contextDataDependency] = dataDependency;\n }\n\n return self['$data'];\n }\n\n var self = this,\n shouldInheritData = dataItemOrAccessor === inheritParentVm,\n realDataItemOrAccessor = shouldInheritData ? undefined : dataItemOrAccessor,\n isFunc = typeof(realDataItemOrAccessor) == \"function\" && !ko.isObservable(realDataItemOrAccessor),\n nodes,\n subscribable,\n dataDependency = options && options['dataDependency'];\n\n if (options && options['exportDependencies']) {\n // The \"exportDependencies\" option means that the calling code will track any dependencies and re-create\n // the binding context when they change.\n updateContext();\n } else {\n subscribable = ko.pureComputed(updateContext);\n subscribable.peek();\n\n // At this point, the binding context has been initialized, and the \"subscribable\" computed observable is\n // subscribed to any observables that were accessed in the process. If there is nothing to track, the\n // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in\n // the context object.\n if (subscribable.isActive()) {\n // Always notify because even if the model ($data) hasn't changed, other context properties might have changed\n subscribable['equalityComparer'] = null;\n } else {\n self[contextSubscribable] = undefined;\n }\n }\n }\n\n // Extend the binding context hierarchy with a new view model object. If the parent context is watching\n // any observables, the new child context will automatically get a dependency on the parent context.\n // But this does not mean that the $data value of the child context will also get updated. If the child\n // view model also depends on the parent view model, you must provide a function that returns the correct\n // view model on each update.\n ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback, options) {\n if (!options && dataItemAlias && typeof dataItemAlias == \"object\") {\n options = dataItemAlias;\n dataItemAlias = options['as'];\n extendCallback = options['extend'];\n }\n\n if (dataItemAlias && options && options['noChildContext']) {\n var isFunc = typeof(dataItemOrAccessor) == \"function\" && !ko.isObservable(dataItemOrAccessor);\n return new ko.bindingContext(inheritParentVm, this, null, function (self) {\n if (extendCallback)\n extendCallback(self);\n self[dataItemAlias] = isFunc ? dataItemOrAccessor() : dataItemOrAccessor;\n }, options);\n }\n\n return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function (self, parentContext) {\n // Extend the context hierarchy by setting the appropriate pointers\n self['$parentContext'] = parentContext;\n self['$parent'] = parentContext['$data'];\n self['$parents'] = (parentContext['$parents'] || []).slice(0);\n self['$parents'].unshift(self['$parent']);\n if (extendCallback)\n extendCallback(self);\n }, options);\n };\n\n // Extend the binding context with new custom properties. This doesn't change the context hierarchy.\n // Similarly to \"child\" contexts, provide a function here to make sure that the correct values are set\n // when an observable view model is updated.\n ko.bindingContext.prototype['extend'] = function(properties, options) {\n return new ko.bindingContext(inheritParentVm, this, null, function(self, parentContext) {\n ko.utils.extend(self, typeof(properties) == \"function\" ? properties(self) : properties);\n }, options);\n };\n\n var boundElementDomDataKey = ko.utils.domData.nextKey();\n\n function asyncContextDispose(node) {\n var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey),\n asyncContext = bindingInfo && bindingInfo.asyncContext;\n if (asyncContext) {\n bindingInfo.asyncContext = null;\n asyncContext.notifyAncestor();\n }\n }\n function AsyncCompleteContext(node, bindingInfo, ancestorBindingInfo) {\n this.node = node;\n this.bindingInfo = bindingInfo;\n this.asyncDescendants = [];\n this.childrenComplete = false;\n\n if (!bindingInfo.asyncContext) {\n ko.utils.domNodeDisposal.addDisposeCallback(node, asyncContextDispose);\n }\n\n if (ancestorBindingInfo && ancestorBindingInfo.asyncContext) {\n ancestorBindingInfo.asyncContext.asyncDescendants.push(node);\n this.ancestorBindingInfo = ancestorBindingInfo;\n }\n }\n AsyncCompleteContext.prototype.notifyAncestor = function () {\n if (this.ancestorBindingInfo && this.ancestorBindingInfo.asyncContext) {\n this.ancestorBindingInfo.asyncContext.descendantComplete(this.node);\n }\n };\n AsyncCompleteContext.prototype.descendantComplete = function (node) {\n ko.utils.arrayRemoveItem(this.asyncDescendants, node);\n if (!this.asyncDescendants.length && this.childrenComplete) {\n this.completeChildren();\n }\n };\n AsyncCompleteContext.prototype.completeChildren = function () {\n this.childrenComplete = true;\n if (this.bindingInfo.asyncContext && !this.asyncDescendants.length) {\n this.bindingInfo.asyncContext = null;\n ko.utils.domNodeDisposal.removeDisposeCallback(this.node, asyncContextDispose);\n ko.bindingEvent.notify(this.node, ko.bindingEvent.descendantsComplete);\n this.notifyAncestor();\n }\n };\n\n ko.bindingEvent = {\n childrenComplete: \"childrenComplete\",\n descendantsComplete : \"descendantsComplete\",\n\n subscribe: function (node, event, callback, context, options) {\n var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {});\n if (!bindingInfo.eventSubscribable) {\n bindingInfo.eventSubscribable = new ko.subscribable;\n }\n if (options && options['notifyImmediately'] && bindingInfo.notifiedEvents[event]) {\n ko.dependencyDetection.ignore(callback, context, [node]);\n }\n return bindingInfo.eventSubscribable.subscribe(callback, context, event);\n },\n\n notify: function (node, event) {\n var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey);\n if (bindingInfo) {\n bindingInfo.notifiedEvents[event] = true;\n if (bindingInfo.eventSubscribable) {\n bindingInfo.eventSubscribable['notifySubscribers'](node, event);\n }\n if (event == ko.bindingEvent.childrenComplete) {\n if (bindingInfo.asyncContext) {\n bindingInfo.asyncContext.completeChildren();\n } else if (bindingInfo.asyncContext === undefined && bindingInfo.eventSubscribable && bindingInfo.eventSubscribable.hasSubscriptionsForEvent(ko.bindingEvent.descendantsComplete)) {\n // It's currently an error to register a descendantsComplete handler for a node that was never registered as completing asynchronously.\n // That's because without the asyncContext, we don't have a way to know that all descendants have completed.\n throw new Error(\"descendantsComplete event not supported for bindings on this node\");\n }\n }\n }\n },\n\n startPossiblyAsyncContentBinding: function (node, bindingContext) {\n var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {});\n\n if (!bindingInfo.asyncContext) {\n bindingInfo.asyncContext = new AsyncCompleteContext(node, bindingInfo, bindingContext[contextAncestorBindingInfo]);\n }\n\n // If the provided context was already extended with this node's binding info, just return the extended context\n if (bindingContext[contextAncestorBindingInfo] == bindingInfo) {\n return bindingContext;\n }\n\n return bindingContext['extend'](function (ctx) {\n ctx[contextAncestorBindingInfo] = bindingInfo;\n });\n }\n };\n\n // Returns the valueAccessor function for a binding value\n function makeValueAccessor(value) {\n return function() {\n return value;\n };\n }\n\n // Returns the value of a valueAccessor function\n function evaluateValueAccessor(valueAccessor) {\n return valueAccessor();\n }\n\n // Given a function that returns bindings, create and return a new object that contains\n // binding value-accessors functions. Each accessor function calls the original function\n // so that it always gets the latest value and all dependencies are captured. This is used\n // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.\n function makeAccessorsFromFunction(callback) {\n return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {\n return function() {\n return callback()[key];\n };\n });\n }\n\n // Given a bindings function or object, create and return a new object that contains\n // binding value-accessors functions. This is used by ko.applyBindingsToNode.\n function makeBindingAccessors(bindings, context, node) {\n if (typeof bindings === 'function') {\n return makeAccessorsFromFunction(bindings.bind(null, context, node));\n } else {\n return ko.utils.objectMap(bindings, makeValueAccessor);\n }\n }\n\n // This function is used if the binding provider doesn't include a getBindingAccessors function.\n // It must be called with 'this' set to the provider instance.\n function getBindingsAndMakeAccessors(node, context) {\n return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));\n }\n\n function validateThatBindingIsAllowedForVirtualElements(bindingName) {\n var validator = ko.virtualElements.allowedBindings[bindingName];\n if (!validator)\n throw new Error(\"The binding '\" + bindingName + \"' cannot be used with virtual elements\")\n }\n\n function applyBindingsToDescendantsInternal(bindingContext, elementOrVirtualElement) {\n var nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);\n\n if (nextInQueue) {\n var currentChild,\n provider = ko.bindingProvider['instance'],\n preprocessNode = provider['preprocessNode'];\n\n // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's\n // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to\n // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that\n // trigger insertion of <template> contents at that point in the document.\n if (preprocessNode) {\n while (currentChild = nextInQueue) {\n nextInQueue = ko.virtualElements.nextSibling(currentChild);\n preprocessNode.call(provider, currentChild);\n }\n // Reset nextInQueue for the next loop\n nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);\n }\n\n while (currentChild = nextInQueue) {\n // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position\n nextInQueue = ko.virtualElements.nextSibling(currentChild);\n applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild);\n }\n }\n ko.bindingEvent.notify(elementOrVirtualElement, ko.bindingEvent.childrenComplete);\n }\n\n function applyBindingsToNodeAndDescendantsInternal(bindingContext, nodeVerified) {\n var bindingContextForDescendants = bindingContext;\n\n var isElement = (nodeVerified.nodeType === 1);\n if (isElement) // Workaround IE <= 8 HTML parsing weirdness\n ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);\n\n // Perf optimisation: Apply bindings only if...\n // (1) We need to store the binding info for the node (all element nodes)\n // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)\n var shouldApplyBindings = isElement || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified);\n if (shouldApplyBindings)\n bindingContextForDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext)['bindingContextForDescendants'];\n\n if (bindingContextForDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {\n applyBindingsToDescendantsInternal(bindingContextForDescendants, nodeVerified);\n }\n }\n\n function topologicalSortBindings(bindings) {\n // Depth-first sort\n var result = [], // The list of key/handler pairs that we will return\n bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'\n cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it\n ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {\n if (!bindingsConsidered[bindingKey]) {\n var binding = ko['getBindingHandler'](bindingKey);\n if (binding) {\n // First add dependencies (if any) of the current binding\n if (binding['after']) {\n cyclicDependencyStack.push(bindingKey);\n ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {\n if (bindings[bindingDependencyKey]) {\n if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {\n throw Error(\"Cannot combine the following bindings, because they have a cyclic dependency: \" + cyclicDependencyStack.join(\", \"));\n } else {\n pushBinding(bindingDependencyKey);\n }\n }\n });\n cyclicDependencyStack.length--;\n }\n // Next add the current binding\n result.push({ key: bindingKey, handler: binding });\n }\n bindingsConsidered[bindingKey] = true;\n }\n });\n\n return result;\n }\n\n function applyBindingsToNodeInternal(node, sourceBindings, bindingContext) {\n var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {});\n\n // Prevent multiple applyBindings calls for the same node, except when a binding value is specified\n var alreadyBound = bindingInfo.alreadyBound;\n if (!sourceBindings) {\n if (alreadyBound) {\n throw Error(\"You cannot apply bindings multiple times to the same element.\");\n }\n bindingInfo.alreadyBound = true;\n }\n if (!alreadyBound) {\n bindingInfo.context = bindingContext;\n }\n if (!bindingInfo.notifiedEvents) {\n bindingInfo.notifiedEvents = {};\n }\n\n // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings\n var bindings;\n if (sourceBindings && typeof sourceBindings !== 'function') {\n bindings = sourceBindings;\n } else {\n var provider = ko.bindingProvider['instance'],\n getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;\n\n // Get the binding from the provider within a computed observable so that we can update the bindings whenever\n // the binding context is updated or if the binding provider accesses observables.\n var bindingsUpdater = ko.dependentObservable(\n function() {\n bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);\n // Register a dependency on the binding context to support observable view models.\n if (bindings) {\n if (bindingContext[contextSubscribable]) {\n bindingContext[contextSubscribable]();\n }\n if (bindingContext[contextDataDependency]) {\n bindingContext[contextDataDependency]();\n }\n }\n return bindings;\n },\n null, { disposeWhenNodeIsRemoved: node }\n );\n\n if (!bindings || !bindingsUpdater.isActive())\n bindingsUpdater = null;\n }\n\n var contextToExtend = bindingContext;\n var bindingHandlerThatControlsDescendantBindings;\n if (bindings) {\n // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding\n // context update), just return the value accessor from the binding. Otherwise, return a function that always gets\n // the latest binding value and registers a dependency on the binding updater.\n var getValueAccessor = bindingsUpdater\n ? function(bindingKey) {\n return function() {\n return evaluateValueAccessor(bindingsUpdater()[bindingKey]);\n };\n } : function(bindingKey) {\n return bindings[bindingKey];\n };\n\n // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated\n function allBindings() {\n return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);\n }\n // The following is the 3.x allBindings API\n allBindings['get'] = function(key) {\n return bindings[key] && evaluateValueAccessor(getValueAccessor(key));\n };\n allBindings['has'] = function(key) {\n return key in bindings;\n };\n\n if (ko.bindingEvent.childrenComplete in bindings) {\n ko.bindingEvent.subscribe(node, ko.bindingEvent.childrenComplete, function () {\n var callback = evaluateValueAccessor(bindings[ko.bindingEvent.childrenComplete]);\n if (callback) {\n var nodes = ko.virtualElements.childNodes(node);\n if (nodes.length) {\n callback(nodes, ko.dataFor(nodes[0]));\n }\n }\n });\n }\n\n if (ko.bindingEvent.descendantsComplete in bindings) {\n contextToExtend = ko.bindingEvent.startPossiblyAsyncContentBinding(node, bindingContext);\n ko.bindingEvent.subscribe(node, ko.bindingEvent.descendantsComplete, function () {\n var callback = evaluateValueAccessor(bindings[ko.bindingEvent.descendantsComplete]);\n if (callback && ko.virtualElements.firstChild(node)) {\n callback(node);\n }\n });\n }\n\n // First put the bindings into the right order\n var orderedBindings = topologicalSortBindings(bindings);\n\n // Go through the sorted bindings, calling init and update for each\n ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {\n // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,\n // so bindingKeyAndHandler.handler will always be nonnull.\n var handlerInitFn = bindingKeyAndHandler.handler[\"init\"],\n handlerUpdateFn = bindingKeyAndHandler.handler[\"update\"],\n bindingKey = bindingKeyAndHandler.key;\n\n if (node.nodeType === 8) {\n validateThatBindingIsAllowedForVirtualElements(bindingKey);\n }\n\n try {\n // Run init, ignoring any dependencies\n if (typeof handlerInitFn == \"function\") {\n ko.dependencyDetection.ignore(function() {\n var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, contextToExtend['$data'], contextToExtend);\n\n // If this binding handler claims to control descendant bindings, make a note of this\n if (initResult && initResult['controlsDescendantBindings']) {\n if (bindingHandlerThatControlsDescendantBindings !== undefined)\n throw new Error(\"Multiple bindings (\" + bindingHandlerThatControlsDescendantBindings + \" and \" + bindingKey + \") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.\");\n bindingHandlerThatControlsDescendantBindings = bindingKey;\n }\n });\n }\n\n // Run update in its own computed wrapper\n if (typeof handlerUpdateFn == \"function\") {\n ko.dependentObservable(\n function() {\n handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, contextToExtend['$data'], contextToExtend);\n },\n null,\n { disposeWhenNodeIsRemoved: node }\n );\n }\n } catch (ex) {\n ex.message = \"Unable to process binding \\\"\" + bindingKey + \": \" + bindings[bindingKey] + \"\\\"\\nMessage: \" + ex.message;\n throw ex;\n }\n });\n }\n\n var shouldBindDescendants = bindingHandlerThatControlsDescendantBindings === undefined;\n return {\n 'shouldBindDescendants': shouldBindDescendants,\n 'bindingContextForDescendants': shouldBindDescendants && contextToExtend\n };\n };\n\n ko.storedBindingContextForNode = function (node) {\n var bindingInfo = ko.utils.domData.get(node, boundElementDomDataKey);\n return bindingInfo && bindingInfo.context;\n }\n\n function getBindingContext(viewModelOrBindingContext, extendContextCallback) {\n return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)\n ? viewModelOrBindingContext\n : new ko.bindingContext(viewModelOrBindingContext, undefined, undefined, extendContextCallback);\n }\n\n ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {\n if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness\n ko.virtualElements.normaliseVirtualElementDomStructure(node);\n return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext));\n };\n\n ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {\n var context = getBindingContext(viewModelOrBindingContext);\n return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);\n };\n\n ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {\n if (rootNode.nodeType === 1 || rootNode.nodeType === 8)\n applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode);\n };\n\n ko.applyBindings = function (viewModelOrBindingContext, rootNode, extendContextCallback) {\n // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.\n if (!jQueryInstance && window['jQuery']) {\n jQueryInstance = window['jQuery'];\n }\n\n if (arguments.length < 2) {\n rootNode = document.body;\n if (!rootNode) {\n throw Error(\"ko.applyBindings: could not find document.body; has the document been loaded?\");\n }\n } else if (!rootNode || (rootNode.nodeType !== 1 && rootNode.nodeType !== 8)) {\n throw Error(\"ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node\");\n }\n\n applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext, extendContextCallback), rootNode);\n };\n\n // Retrieving binding context from arbitrary nodes\n ko.contextFor = function(node) {\n // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)\n if (node && (node.nodeType === 1 || node.nodeType === 8)) {\n return ko.storedBindingContextForNode(node);\n }\n return undefined;\n };\n ko.dataFor = function(node) {\n var context = ko.contextFor(node);\n return context ? context['$data'] : undefined;\n };\n\n ko.exportSymbol('bindingHandlers', ko.bindingHandlers);\n ko.exportSymbol('bindingEvent', ko.bindingEvent);\n ko.exportSymbol('bindingEvent.subscribe', ko.bindingEvent.subscribe);\n ko.exportSymbol('bindingEvent.startPossiblyAsyncContentBinding', ko.bindingEvent.startPossiblyAsyncContentBinding);\n ko.exportSymbol('applyBindings', ko.applyBindings);\n ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);\n ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);\n ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);\n ko.exportSymbol('contextFor', ko.contextFor);\n ko.exportSymbol('dataFor', ko.dataFor);\n })();\n (function(undefined) {\n var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight\n loadedDefinitionsCache = {}; // Tracks component loads that have already completed\n\n ko.components = {\n get: function(componentName, callback) {\n var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName);\n if (cachedDefinition) {\n // It's already loaded and cached. Reuse the same definition object.\n // Note that for API consistency, even cache hits complete asynchronously by default.\n // You can bypass this by putting synchronous:true on your component config.\n if (cachedDefinition.isSynchronousComponent) {\n ko.dependencyDetection.ignore(function() { // See comment in loaderRegistryBehaviors.js for reasoning\n callback(cachedDefinition.definition);\n });\n } else {\n ko.tasks.schedule(function() { callback(cachedDefinition.definition); });\n }\n } else {\n // Join the loading process that is already underway, or start a new one.\n loadComponentAndNotify(componentName, callback);\n }\n },\n\n clearCachedDefinition: function(componentName) {\n delete loadedDefinitionsCache[componentName];\n },\n\n _getFirstResultFromLoaders: getFirstResultFromLoaders\n };\n\n function getObjectOwnProperty(obj, propName) {\n return Object.prototype.hasOwnProperty.call(obj, propName) ? obj[propName] : undefined;\n }\n\n function loadComponentAndNotify(componentName, callback) {\n var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),\n completedAsync;\n if (!subscribable) {\n // It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.\n subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();\n subscribable.subscribe(callback);\n\n beginLoadingComponent(componentName, function(definition, config) {\n var isSynchronousComponent = !!(config && config['synchronous']);\n loadedDefinitionsCache[componentName] = { definition: definition, isSynchronousComponent: isSynchronousComponent };\n delete loadingSubscribablesCache[componentName];\n\n // For API consistency, all loads complete asynchronously. However we want to avoid\n // adding an extra task schedule if it's unnecessary (i.e., the completion is already\n // async).\n //\n // You can bypass the 'always asynchronous' feature by putting the synchronous:true\n // flag on your component configuration when you register it.\n if (completedAsync || isSynchronousComponent) {\n // Note that notifySubscribers ignores any dependencies read within the callback.\n // See comment in loaderRegistryBehaviors.js for reasoning\n subscribable['notifySubscribers'](definition);\n } else {\n ko.tasks.schedule(function() {\n subscribable['notifySubscribers'](definition);\n });\n }\n });\n completedAsync = true;\n } else {\n subscribable.subscribe(callback);\n }\n }\n\n function beginLoadingComponent(componentName, callback) {\n getFirstResultFromLoaders('getConfig', [componentName], function(config) {\n if (config) {\n // We have a config, so now load its definition\n getFirstResultFromLoaders('loadComponent', [componentName, config], function(definition) {\n callback(definition, config);\n });\n } else {\n // The component has no config - it's unknown to all the loaders.\n // Note that this is not an error (e.g., a module loading error) - that would abort the\n // process and this callback would not run. For this callback to run, all loaders must\n // have confirmed they don't know about this component.\n callback(null, null);\n }\n });\n }\n\n function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {\n // On the first call in the stack, start with the full set of loaders\n if (!candidateLoaders) {\n candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array\n }\n\n // Try the next candidate\n var currentCandidateLoader = candidateLoaders.shift();\n if (currentCandidateLoader) {\n var methodInstance = currentCandidateLoader[methodName];\n if (methodInstance) {\n var wasAborted = false,\n synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function(result) {\n if (wasAborted) {\n callback(null);\n } else if (result !== null) {\n // This candidate returned a value. Use it.\n callback(result);\n } else {\n // Try the next candidate\n getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);\n }\n }));\n\n // Currently, loaders may not return anything synchronously. This leaves open the possibility\n // that we'll extend the API to support synchronous return values in the future. It won't be\n // a breaking change, because currently no loader is allowed to return anything except undefined.\n if (synchronousReturnValue !== undefined) {\n wasAborted = true;\n\n // Method to suppress exceptions will remain undocumented. This is only to keep\n // KO's specs running tidily, since we can observe the loading got aborted without\n // having exceptions cluttering up the console too.\n if (!currentCandidateLoader['suppressLoaderExceptions']) {\n throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.');\n }\n }\n } else {\n // This candidate doesn't have the relevant handler. Synchronously move on to the next one.\n getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);\n }\n } else {\n // No candidates returned a value\n callback(null);\n }\n }\n\n // Reference the loaders via string name so it's possible for developers\n // to replace the whole array by assigning to ko.components.loaders\n ko.components['loaders'] = [];\n\n ko.exportSymbol('components', ko.components);\n ko.exportSymbol('components.get', ko.components.get);\n ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition);\n })();\n (function(undefined) {\n\n // The default loader is responsible for two things:\n // 1. Maintaining the default in-memory registry of component configuration objects\n // (i.e., the thing you're writing to when you call ko.components.register(someName, ...))\n // 2. Answering requests for components by fetching configuration objects\n // from that default in-memory registry and resolving them into standard\n // component definition objects (of the form { createViewModel: ..., template: ... })\n // Custom loaders may override either of these facilities, i.e.,\n // 1. To supply configuration objects from some other source (e.g., conventions)\n // 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic.\n\n var defaultConfigRegistry = {};\n\n ko.components.register = function(componentName, config) {\n if (!config) {\n throw new Error('Invalid configuration for ' + componentName);\n }\n\n if (ko.components.isRegistered(componentName)) {\n throw new Error('Component ' + componentName + ' is already registered');\n }\n\n defaultConfigRegistry[componentName] = config;\n };\n\n ko.components.isRegistered = function(componentName) {\n return Object.prototype.hasOwnProperty.call(defaultConfigRegistry, componentName);\n };\n\n ko.components.unregister = function(componentName) {\n delete defaultConfigRegistry[componentName];\n ko.components.clearCachedDefinition(componentName);\n };\n\n ko.components.defaultLoader = {\n 'getConfig': function(componentName, callback) {\n var result = ko.components.isRegistered(componentName)\n ? defaultConfigRegistry[componentName]\n : null;\n callback(result);\n },\n\n 'loadComponent': function(componentName, config, callback) {\n var errorCallback = makeErrorCallback(componentName);\n possiblyGetConfigFromAmd(errorCallback, config, function(loadedConfig) {\n resolveConfig(componentName, errorCallback, loadedConfig, callback);\n });\n },\n\n 'loadTemplate': function(componentName, templateConfig, callback) {\n resolveTemplate(makeErrorCallback(componentName), templateConfig, callback);\n },\n\n 'loadViewModel': function(componentName, viewModelConfig, callback) {\n resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback);\n }\n };\n\n var createViewModelKey = 'createViewModel';\n\n // Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it\n // into the standard component definition format:\n // { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }.\n // Since both template and viewModel may need to be resolved asynchronously, both tasks are performed\n // in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure,\n // so this is implemented manually below.\n function resolveConfig(componentName, errorCallback, config, callback) {\n var result = {},\n makeCallBackWhenZero = 2,\n tryIssueCallback = function() {\n if (--makeCallBackWhenZero === 0) {\n callback(result);\n }\n },\n templateConfig = config['template'],\n viewModelConfig = config['viewModel'];\n\n if (templateConfig) {\n possiblyGetConfigFromAmd(errorCallback, templateConfig, function(loadedConfig) {\n ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function(resolvedTemplate) {\n result['template'] = resolvedTemplate;\n tryIssueCallback();\n });\n });\n } else {\n tryIssueCallback();\n }\n\n if (viewModelConfig) {\n possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function(loadedConfig) {\n ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function(resolvedViewModel) {\n result[createViewModelKey] = resolvedViewModel;\n tryIssueCallback();\n });\n });\n } else {\n tryIssueCallback();\n }\n }\n\n function resolveTemplate(errorCallback, templateConfig, callback) {\n if (typeof templateConfig === 'string') {\n // Markup - parse it\n callback(ko.utils.parseHtmlFragment(templateConfig));\n } else if (templateConfig instanceof Array) {\n // Assume already an array of DOM nodes - pass through unchanged\n callback(templateConfig);\n } else if (isDocumentFragment(templateConfig)) {\n // Document fragment - use its child nodes\n callback(ko.utils.makeArray(templateConfig.childNodes));\n } else if (templateConfig['element']) {\n var element = templateConfig['element'];\n if (isDomElement(element)) {\n // Element instance - copy its child nodes\n callback(cloneNodesFromTemplateSourceElement(element));\n } else if (typeof element === 'string') {\n // Element ID - find it, then copy its child nodes\n var elemInstance = document.getElementById(element);\n if (elemInstance) {\n callback(cloneNodesFromTemplateSourceElement(elemInstance));\n } else {\n errorCallback('Cannot find element with ID ' + element);\n }\n } else {\n errorCallback('Unknown element type: ' + element);\n }\n } else {\n errorCallback('Unknown template value: ' + templateConfig);\n }\n }\n\n function resolveViewModel(errorCallback, viewModelConfig, callback) {\n if (typeof viewModelConfig === 'function') {\n // Constructor - convert to standard factory function format\n // By design, this does *not* supply componentInfo to the constructor, as the intent is that\n // componentInfo contains non-viewmodel data (e.g., the component's element) that should only\n // be used in factory functions, not viewmodel constructors.\n callback(function (params /*, componentInfo */) {\n return new viewModelConfig(params);\n });\n } else if (typeof viewModelConfig[createViewModelKey] === 'function') {\n // Already a factory function - use it as-is\n callback(viewModelConfig[createViewModelKey]);\n } else if ('instance' in viewModelConfig) {\n // Fixed object instance - promote to createViewModel format for API consistency\n var fixedInstance = viewModelConfig['instance'];\n callback(function (params, componentInfo) {\n return fixedInstance;\n });\n } else if ('viewModel' in viewModelConfig) {\n // Resolved AMD module whose value is of the form { viewModel: ... }\n resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback);\n } else {\n errorCallback('Unknown viewModel value: ' + viewModelConfig);\n }\n }\n\n function cloneNodesFromTemplateSourceElement(elemInstance) {\n switch (ko.utils.tagNameLower(elemInstance)) {\n case 'script':\n return ko.utils.parseHtmlFragment(elemInstance.text);\n case 'textarea':\n return ko.utils.parseHtmlFragment(elemInstance.value);\n case 'template':\n // For browsers with proper <template> element support (i.e., where the .content property\n // gives a document fragment), use that document fragment.\n if (isDocumentFragment(elemInstance.content)) {\n return ko.utils.cloneNodes(elemInstance.content.childNodes);\n }\n }\n\n // Regular elements such as <div>, and <template> elements on old browsers that don't really\n // understand <template> and just treat it as a regular container\n return ko.utils.cloneNodes(elemInstance.childNodes);\n }\n\n function isDomElement(obj) {\n if (window['HTMLElement']) {\n return obj instanceof HTMLElement;\n } else {\n return obj && obj.tagName && obj.nodeType === 1;\n }\n }\n\n function isDocumentFragment(obj) {\n if (window['DocumentFragment']) {\n return obj instanceof DocumentFragment;\n } else {\n return obj && obj.nodeType === 11;\n }\n }\n\n function possiblyGetConfigFromAmd(errorCallback, config, callback) {\n if (typeof config['require'] === 'string') {\n // The config is the value of an AMD module\n if (amdRequire || window['require']) {\n (amdRequire || window['require'])([config['require']], function (module) {\n if (module && typeof module === 'object' && module.__esModule && module.default) {\n module = module.default;\n }\n callback(module);\n });\n } else {\n errorCallback('Uses require, but no AMD loader is present');\n }\n } else {\n callback(config);\n }\n }\n\n function makeErrorCallback(componentName) {\n return function (message) {\n throw new Error('Component \\'' + componentName + '\\': ' + message);\n };\n }\n\n ko.exportSymbol('components.register', ko.components.register);\n ko.exportSymbol('components.isRegistered', ko.components.isRegistered);\n ko.exportSymbol('components.unregister', ko.components.unregister);\n\n // Expose the default loader so that developers can directly ask it for configuration\n // or to resolve configuration\n ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader);\n\n // By default, the default loader is the only registered component loader\n ko.components['loaders'].push(ko.components.defaultLoader);\n\n // Privately expose the underlying config registry for use in old-IE shim\n ko.components._allRegisteredComponents = defaultConfigRegistry;\n })();\n (function (undefined) {\n // Overridable API for determining which component name applies to a given node. By overriding this,\n // you can for example map specific tagNames to components that are not preregistered.\n ko.components['getComponentNameForNode'] = function(node) {\n var tagNameLower = ko.utils.tagNameLower(node);\n if (ko.components.isRegistered(tagNameLower)) {\n // Try to determine that this node can be considered a *custom* element; see https://github.com/knockout/knockout/issues/1603\n if (tagNameLower.indexOf('-') != -1 || ('' + node) == \"[object HTMLUnknownElement]\" || (ko.utils.ieVersion <= 8 && node.tagName === tagNameLower)) {\n return tagNameLower;\n }\n }\n };\n\n ko.components.addBindingsForCustomElement = function(allBindings, node, bindingContext, valueAccessors) {\n // Determine if it's really a custom element matching a component\n if (node.nodeType === 1) {\n var componentName = ko.components['getComponentNameForNode'](node);\n if (componentName) {\n // It does represent a component, so add a component binding for it\n allBindings = allBindings || {};\n\n if (allBindings['component']) {\n // Avoid silently overwriting some other 'component' binding that may already be on the element\n throw new Error('Cannot use the \"component\" binding on a custom element matching a component');\n }\n\n var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) };\n\n allBindings['component'] = valueAccessors\n ? function() { return componentBindingValue; }\n : componentBindingValue;\n }\n }\n\n return allBindings;\n }\n\n var nativeBindingProviderInstance = new ko.bindingProvider();\n\n function getComponentParamsFromCustomElement(elem, bindingContext) {\n var paramsAttribute = elem.getAttribute('params');\n\n if (paramsAttribute) {\n var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }),\n rawParamComputedValues = ko.utils.objectMap(params, function(paramValue, paramName) {\n return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem });\n }),\n result = ko.utils.objectMap(rawParamComputedValues, function(paramValueComputed, paramName) {\n var paramValue = paramValueComputed.peek();\n // Does the evaluation of the parameter value unwrap any observables?\n if (!paramValueComputed.isActive()) {\n // No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly.\n // Example: \"someVal: firstName, age: 123\" (whether or not firstName is an observable/computed)\n return paramValue;\n } else {\n // Yes it does. Supply a computed property that unwraps both the outer (binding expression)\n // level of observability, and any inner (resulting model value) level of observability.\n // This means the component doesn't have to worry about multiple unwrapping. If the value is a\n // writable observable, the computed will also be writable and pass the value on to the observable.\n return ko.computed({\n 'read': function() {\n return ko.utils.unwrapObservable(paramValueComputed());\n },\n 'write': ko.isWriteableObservable(paramValue) && function(value) {\n paramValueComputed()(value);\n },\n disposeWhenNodeIsRemoved: elem\n });\n }\n });\n\n // Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw'\n // This is in case the developer wants to react to outer (binding) observability separately from inner\n // (model value) observability, or in case the model value observable has subobservables.\n if (!Object.prototype.hasOwnProperty.call(result, '$raw')) {\n result['$raw'] = rawParamComputedValues;\n }\n\n return result;\n } else {\n // For consistency, absence of a \"params\" attribute is treated the same as the presence of\n // any empty one. Otherwise component viewmodels need special code to check whether or not\n // 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying.\n return { '$raw': {} };\n }\n }\n\n // --------------------------------------------------------------------------------\n // Compatibility code for older (pre-HTML5) IE browsers\n\n if (ko.utils.ieVersion < 9) {\n // Whenever you preregister a component, enable it as a custom element in the current document\n ko.components['register'] = (function(originalFunction) {\n return function(componentName) {\n document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element\n return originalFunction.apply(this, arguments);\n }\n })(ko.components['register']);\n\n // Whenever you create a document fragment, enable all preregistered component names as custom elements\n // This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements\n document.createDocumentFragment = (function(originalFunction) {\n return function() {\n var newDocFrag = originalFunction(),\n allComponents = ko.components._allRegisteredComponents;\n for (var componentName in allComponents) {\n if (Object.prototype.hasOwnProperty.call(allComponents, componentName)) {\n newDocFrag.createElement(componentName);\n }\n }\n return newDocFrag;\n };\n })(document.createDocumentFragment);\n }\n })();(function(undefined) {\n var componentLoadingOperationUniqueId = 0;\n\n ko.bindingHandlers['component'] = {\n 'init': function(element, valueAccessor, ignored1, ignored2, bindingContext) {\n var currentViewModel,\n currentLoadingOperationId,\n afterRenderSub,\n disposeAssociatedComponentViewModel = function () {\n var currentViewModelDispose = currentViewModel && currentViewModel['dispose'];\n if (typeof currentViewModelDispose === 'function') {\n currentViewModelDispose.call(currentViewModel);\n }\n if (afterRenderSub) {\n afterRenderSub.dispose();\n }\n afterRenderSub = null;\n currentViewModel = null;\n // Any in-flight loading operation is no longer relevant, so make sure we ignore its completion\n currentLoadingOperationId = null;\n },\n originalChildNodes = ko.utils.makeArray(ko.virtualElements.childNodes(element));\n\n ko.virtualElements.emptyNode(element);\n ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel);\n\n ko.computed(function () {\n var value = ko.utils.unwrapObservable(valueAccessor()),\n componentName, componentParams;\n\n if (typeof value === 'string') {\n componentName = value;\n } else {\n componentName = ko.utils.unwrapObservable(value['name']);\n componentParams = ko.utils.unwrapObservable(value['params']);\n }\n\n if (!componentName) {\n throw new Error('No component name specified');\n }\n\n var asyncContext = ko.bindingEvent.startPossiblyAsyncContentBinding(element, bindingContext);\n\n var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId;\n ko.components.get(componentName, function(componentDefinition) {\n // If this is not the current load operation for this element, ignore it.\n if (currentLoadingOperationId !== loadingOperationId) {\n return;\n }\n\n // Clean up previous state\n disposeAssociatedComponentViewModel();\n\n // Instantiate and bind new component. Implicitly this cleans any old DOM nodes.\n if (!componentDefinition) {\n throw new Error('Unknown component \\'' + componentName + '\\'');\n }\n cloneTemplateIntoElement(componentName, componentDefinition, element);\n\n var componentInfo = {\n 'element': element,\n 'templateNodes': originalChildNodes\n };\n\n var componentViewModel = createViewModel(componentDefinition, componentParams, componentInfo),\n childBindingContext = asyncContext['createChildContext'](componentViewModel, {\n 'extend': function(ctx) {\n ctx['$component'] = componentViewModel;\n ctx['$componentTemplateNodes'] = originalChildNodes;\n }\n });\n\n if (componentViewModel && componentViewModel['koDescendantsComplete']) {\n afterRenderSub = ko.bindingEvent.subscribe(element, ko.bindingEvent.descendantsComplete, componentViewModel['koDescendantsComplete'], componentViewModel);\n }\n\n currentViewModel = componentViewModel;\n ko.applyBindingsToDescendants(childBindingContext, element);\n });\n }, null, { disposeWhenNodeIsRemoved: element });\n\n return { 'controlsDescendantBindings': true };\n }\n };\n\n ko.virtualElements.allowedBindings['component'] = true;\n\n function cloneTemplateIntoElement(componentName, componentDefinition, element) {\n var template = componentDefinition['template'];\n if (!template) {\n throw new Error('Component \\'' + componentName + '\\' has no template');\n }\n\n var clonedNodesArray = ko.utils.cloneNodes(template);\n ko.virtualElements.setDomNodeChildren(element, clonedNodesArray);\n }\n\n function createViewModel(componentDefinition, componentParams, componentInfo) {\n var componentViewModelFactory = componentDefinition['createViewModel'];\n return componentViewModelFactory\n ? componentViewModelFactory.call(componentDefinition, componentParams, componentInfo)\n : componentParams; // Template-only component\n }\n\n })();\n var attrHtmlToJavaScriptMap = { 'class': 'className', 'for': 'htmlFor' };\n ko.bindingHandlers['attr'] = {\n 'update': function(element, valueAccessor, allBindings) {\n var value = ko.utils.unwrapObservable(valueAccessor()) || {};\n ko.utils.objectForEach(value, function(attrName, attrValue) {\n attrValue = ko.utils.unwrapObservable(attrValue);\n\n // Find the namespace of this attribute, if any.\n var prefixLen = attrName.indexOf(':');\n var namespace = \"lookupNamespaceURI\" in element && prefixLen > 0 && element.lookupNamespaceURI(attrName.substr(0, prefixLen));\n\n // To cover cases like \"attr: { checked:someProp }\", we want to remove the attribute entirely\n // when someProp is a \"no value\"-like value (strictly null, false, or undefined)\n // (because the absence of the \"checked\" attr is how to mark an element as not checked, etc.)\n var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);\n if (toRemove) {\n namespace ? element.removeAttributeNS(namespace, attrName) : element.removeAttribute(attrName);\n } else {\n attrValue = attrValue.toString();\n }\n\n // In IE <= 7 and IE8 Quirks Mode, you have to use the JavaScript property name instead of the\n // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,\n // but instead of figuring out the mode, we'll just set the attribute through the JavaScript\n // property for IE <= 8.\n if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavaScriptMap) {\n attrName = attrHtmlToJavaScriptMap[attrName];\n if (toRemove)\n element.removeAttribute(attrName);\n else\n element[attrName] = attrValue;\n } else if (!toRemove) {\n namespace ? element.setAttributeNS(namespace, attrName, attrValue) : element.setAttribute(attrName, attrValue);\n }\n\n // Treat \"name\" specially - although you can think of it as an attribute, it also needs\n // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)\n // Deliberately being case-sensitive here because XHTML would regard \"Name\" as a different thing\n // entirely, and there's no strong reason to allow for such casing in HTML.\n if (attrName === \"name\") {\n ko.utils.setElementName(element, toRemove ? \"\" : attrValue);\n }\n });\n }\n };\n (function() {\n\n ko.bindingHandlers['checked'] = {\n 'after': ['value', 'attr'],\n 'init': function (element, valueAccessor, allBindings) {\n var checkedValue = ko.pureComputed(function() {\n // Treat \"value\" like \"checkedValue\" when it is included with \"checked\" binding\n if (allBindings['has']('checkedValue')) {\n return ko.utils.unwrapObservable(allBindings.get('checkedValue'));\n } else if (useElementValue) {\n if (allBindings['has']('value')) {\n return ko.utils.unwrapObservable(allBindings.get('value'));\n } else {\n return element.value;\n }\n }\n });\n\n function updateModel() {\n // This updates the model value from the view value.\n // It runs in response to DOM events (click) and changes in checkedValue.\n var isChecked = element.checked,\n elemValue = checkedValue();\n\n // When we're first setting up this computed, don't change any model state.\n if (ko.computedContext.isInitial()) {\n return;\n }\n\n // We can ignore unchecked radio buttons, because some other radio\n // button will be checked, and that one can take care of updating state.\n // Also ignore value changes to an already unchecked checkbox.\n if (!isChecked && (isRadio || ko.computedContext.getDependenciesCount())) {\n return;\n }\n\n var modelValue = ko.dependencyDetection.ignore(valueAccessor);\n if (valueIsArray) {\n var writableValue = rawValueIsNonArrayObservable ? modelValue.peek() : modelValue,\n saveOldValue = oldElemValue;\n oldElemValue = elemValue;\n\n if (saveOldValue !== elemValue) {\n // When we're responding to the checkedValue changing, and the element is\n // currently checked, replace the old elem value with the new elem value\n // in the model array.\n if (isChecked) {\n ko.utils.addOrRemoveItem(writableValue, elemValue, true);\n ko.utils.addOrRemoveItem(writableValue, saveOldValue, false);\n }\n } else {\n // When we're responding to the user having checked/unchecked a checkbox,\n // add/remove the element value to the model array.\n ko.utils.addOrRemoveItem(writableValue, elemValue, isChecked);\n }\n\n if (rawValueIsNonArrayObservable && ko.isWriteableObservable(modelValue)) {\n modelValue(writableValue);\n }\n } else {\n if (isCheckbox) {\n if (elemValue === undefined) {\n elemValue = isChecked;\n } else if (!isChecked) {\n elemValue = undefined;\n }\n }\n ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);\n }\n };\n\n function updateView() {\n // This updates the view value from the model value.\n // It runs in response to changes in the bound (checked) value.\n var modelValue = ko.utils.unwrapObservable(valueAccessor()),\n elemValue = checkedValue();\n\n if (valueIsArray) {\n // When a checkbox is bound to an array, being checked represents its value being present in that array\n element.checked = ko.utils.arrayIndexOf(modelValue, elemValue) >= 0;\n oldElemValue = elemValue;\n } else if (isCheckbox && elemValue === undefined) {\n // When a checkbox is bound to any other value (not an array) and \"checkedValue\" is not defined,\n // being checked represents the value being trueish\n element.checked = !!modelValue;\n } else {\n // Otherwise, being checked means that the checkbox or radio button's value corresponds to the model value\n element.checked = (checkedValue() === modelValue);\n }\n };\n\n var isCheckbox = element.type == \"checkbox\",\n isRadio = element.type == \"radio\";\n\n // Only bind to check boxes and radio buttons\n if (!isCheckbox && !isRadio) {\n return;\n }\n\n var rawValue = valueAccessor(),\n valueIsArray = isCheckbox && (ko.utils.unwrapObservable(rawValue) instanceof Array),\n rawValueIsNonArrayObservable = !(valueIsArray && rawValue.push && rawValue.splice),\n useElementValue = isRadio || valueIsArray,\n oldElemValue = valueIsArray ? checkedValue() : undefined;\n\n // IE 6 won't allow radio buttons to be selected unless they have a name\n if (isRadio && !element.name)\n ko.bindingHandlers['uniqueName']['init'](element, function() { return true });\n\n // Set up two computeds to update the binding:\n\n // The first responds to changes in the checkedValue value and to element clicks\n ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });\n ko.utils.registerEventHandler(element, \"click\", updateModel);\n\n // The second responds to changes in the model value (the one associated with the checked binding)\n ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });\n\n rawValue = undefined;\n }\n };\n ko.expressionRewriting.twoWayBindings['checked'] = true;\n\n ko.bindingHandlers['checkedValue'] = {\n 'update': function (element, valueAccessor) {\n element.value = ko.utils.unwrapObservable(valueAccessor());\n }\n };\n\n })();var classesWrittenByBindingKey = '__ko__cssValue';\n ko.bindingHandlers['class'] = {\n 'update': function (element, valueAccessor) {\n var value = ko.utils.stringTrim(ko.utils.unwrapObservable(valueAccessor()));\n ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);\n element[classesWrittenByBindingKey] = value;\n ko.utils.toggleDomNodeCssClass(element, value, true);\n }\n };\n\n ko.bindingHandlers['css'] = {\n 'update': function (element, valueAccessor) {\n var value = ko.utils.unwrapObservable(valueAccessor());\n if (value !== null && typeof value == \"object\") {\n ko.utils.objectForEach(value, function(className, shouldHaveClass) {\n shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);\n ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);\n });\n } else {\n ko.bindingHandlers['class']['update'](element, valueAccessor);\n }\n }\n };\n ko.bindingHandlers['enable'] = {\n 'update': function (element, valueAccessor) {\n var value = ko.utils.unwrapObservable(valueAccessor());\n if (value && element.disabled)\n element.removeAttribute(\"disabled\");\n else if ((!value) && (!element.disabled))\n element.disabled = true;\n }\n };\n\n ko.bindingHandlers['disable'] = {\n 'update': function (element, valueAccessor) {\n ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });\n }\n };\n// For certain common events (currently just 'click'), allow a simplified data-binding syntax\n// e.g. click:handler instead of the usual full-length event:{click:handler}\n function makeEventHandlerShortcut(eventName) {\n ko.bindingHandlers[eventName] = {\n 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {\n var newValueAccessor = function () {\n var result = {};\n result[eventName] = valueAccessor();\n return result;\n };\n return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);\n }\n }\n }\n\n ko.bindingHandlers['event'] = {\n 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {\n var eventsToHandle = valueAccessor() || {};\n ko.utils.objectForEach(eventsToHandle, function(eventName) {\n if (typeof eventName == \"string\") {\n ko.utils.registerEventHandler(element, eventName, function (event) {\n var handlerReturnValue;\n var handlerFunction = valueAccessor()[eventName];\n if (!handlerFunction)\n return;\n\n try {\n // Take all the event args, and prefix with the viewmodel\n var argsForHandler = ko.utils.makeArray(arguments);\n viewModel = bindingContext['$data'];\n argsForHandler.unshift(viewModel);\n handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);\n } finally {\n if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.\n if (event.preventDefault)\n event.preventDefault();\n else\n event.returnValue = false;\n }\n }\n\n var bubble = allBindings.get(eventName + 'Bubble') !== false;\n if (!bubble) {\n event.cancelBubble = true;\n if (event.stopPropagation)\n event.stopPropagation();\n }\n });\n }\n });\n }\n };\n// \"foreach: someExpression\" is equivalent to \"template: { foreach: someExpression }\"\n// \"foreach: { data: someExpression, afterAdd: myfn }\" is equivalent to \"template: { foreach: someExpression, afterAdd: myfn }\"\n ko.bindingHandlers['foreach'] = {\n makeTemplateValueAccessor: function(valueAccessor) {\n return function() {\n var modelValue = valueAccessor(),\n unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here\n\n // If unwrappedValue is the array, pass in the wrapped value on its own\n // The value will be unwrapped and tracked within the template binding\n // (See https://github.com/SteveSanderson/knockout/issues/523)\n if ((!unwrappedValue) || typeof unwrappedValue.length == \"number\")\n return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };\n\n // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates\n ko.utils.unwrapObservable(modelValue);\n return {\n 'foreach': unwrappedValue['data'],\n 'as': unwrappedValue['as'],\n 'noChildContext': unwrappedValue['noChildContext'],\n 'includeDestroyed': unwrappedValue['includeDestroyed'],\n 'afterAdd': unwrappedValue['afterAdd'],\n 'beforeRemove': unwrappedValue['beforeRemove'],\n 'afterRender': unwrappedValue['afterRender'],\n 'beforeMove': unwrappedValue['beforeMove'],\n 'afterMove': unwrappedValue['afterMove'],\n 'templateEngine': ko.nativeTemplateEngine.instance\n };\n };\n },\n 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {\n return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));\n },\n 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {\n return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);\n }\n };\n ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings\n ko.virtualElements.allowedBindings['foreach'] = true;\n var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';\n var hasfocusLastValue = '__ko_hasfocusLastValue';\n ko.bindingHandlers['hasfocus'] = {\n 'init': function(element, valueAccessor, allBindings) {\n var handleElementFocusChange = function(isFocused) {\n // Where possible, ignore which event was raised and determine focus state using activeElement,\n // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.\n // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,\n // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus\n // from calling 'blur()' on the element when it loses focus.\n // Discussion at https://github.com/SteveSanderson/knockout/pull/352\n element[hasfocusUpdatingProperty] = true;\n var ownerDoc = element.ownerDocument;\n if (\"activeElement\" in ownerDoc) {\n var active;\n try {\n active = ownerDoc.activeElement;\n } catch(e) {\n // IE9 throws if you access activeElement during page load (see issue #703)\n active = ownerDoc.body;\n }\n isFocused = (active === element);\n }\n var modelValue = valueAccessor();\n ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);\n\n //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function\n element[hasfocusLastValue] = isFocused;\n element[hasfocusUpdatingProperty] = false;\n };\n var handleElementFocusIn = handleElementFocusChange.bind(null, true);\n var handleElementFocusOut = handleElementFocusChange.bind(null, false);\n\n ko.utils.registerEventHandler(element, \"focus\", handleElementFocusIn);\n ko.utils.registerEventHandler(element, \"focusin\", handleElementFocusIn); // For IE\n ko.utils.registerEventHandler(element, \"blur\", handleElementFocusOut);\n ko.utils.registerEventHandler(element, \"focusout\", handleElementFocusOut); // For IE\n\n // Assume element is not focused (prevents \"blur\" being called initially)\n element[hasfocusLastValue] = false;\n },\n 'update': function(element, valueAccessor) {\n var value = !!ko.utils.unwrapObservable(valueAccessor());\n\n if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {\n value ? element.focus() : element.blur();\n\n // In IE, the blur method doesn't always cause the element to lose focus (for example, if the window is not in focus).\n // Setting focus to the body element does seem to be reliable in IE, but should only be used if we know that the current\n // element was focused already.\n if (!value && element[hasfocusLastValue]) {\n element.ownerDocument.body.focus();\n }\n\n // For IE, which doesn't reliably fire \"focus\" or \"blur\" events synchronously\n ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? \"focusin\" : \"focusout\"]);\n }\n }\n };\n ko.expressionRewriting.twoWayBindings['hasfocus'] = true;\n\n ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make \"hasFocus\" an alias\n ko.expressionRewriting.twoWayBindings['hasFocus'] = 'hasfocus';\n ko.bindingHandlers['html'] = {\n 'init': function() {\n // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)\n return { 'controlsDescendantBindings': true };\n },\n 'update': function (element, valueAccessor) {\n // setHtml will unwrap the value if needed\n ko.utils.setHtml(element, valueAccessor());\n }\n };\n (function () {\n\n// Makes a binding like with or if\n function makeWithIfBinding(bindingKey, isWith, isNot) {\n ko.bindingHandlers[bindingKey] = {\n 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {\n var didDisplayOnLastUpdate, savedNodes, contextOptions = {}, completeOnRender, needAsyncContext, renderOnEveryChange;\n\n if (isWith) {\n var as = allBindings.get('as'), noChildContext = allBindings.get('noChildContext');\n renderOnEveryChange = !(as && noChildContext);\n contextOptions = { 'as': as, 'noChildContext': noChildContext, 'exportDependencies': renderOnEveryChange };\n }\n\n completeOnRender = allBindings.get(\"completeOn\") == \"render\";\n needAsyncContext = completeOnRender || allBindings['has'](ko.bindingEvent.descendantsComplete);\n\n ko.computed(function() {\n var value = ko.utils.unwrapObservable(valueAccessor()),\n shouldDisplay = !isNot !== !value, // equivalent to isNot ? !value : !!value,\n isInitial = !savedNodes,\n childContext;\n\n if (!renderOnEveryChange && shouldDisplay === didDisplayOnLastUpdate) {\n return;\n }\n\n if (needAsyncContext) {\n bindingContext = ko.bindingEvent.startPossiblyAsyncContentBinding(element, bindingContext);\n }\n\n if (shouldDisplay) {\n if (!isWith || renderOnEveryChange) {\n contextOptions['dataDependency'] = ko.computedContext.computed();\n }\n\n if (isWith) {\n childContext = bindingContext['createChildContext'](typeof value == \"function\" ? value : valueAccessor, contextOptions);\n } else if (ko.computedContext.getDependenciesCount()) {\n childContext = bindingContext['extend'](null, contextOptions);\n } else {\n childContext = bindingContext;\n }\n }\n\n // Save a copy of the inner nodes on the initial update, but only if we have dependencies.\n if (isInitial && ko.computedContext.getDependenciesCount()) {\n savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);\n }\n\n if (shouldDisplay) {\n if (!isInitial) {\n ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));\n }\n\n ko.applyBindingsToDescendants(childContext, element);\n } else {\n ko.virtualElements.emptyNode(element);\n\n if (!completeOnRender) {\n ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete);\n }\n }\n\n didDisplayOnLastUpdate = shouldDisplay;\n\n }, null, { disposeWhenNodeIsRemoved: element });\n\n return { 'controlsDescendantBindings': true };\n }\n };\n ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings\n ko.virtualElements.allowedBindings[bindingKey] = true;\n }\n\n// Construct the actual binding handlers\n makeWithIfBinding('if');\n makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);\n makeWithIfBinding('with', true /* isWith */);\n\n })();ko.bindingHandlers['let'] = {\n 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {\n // Make a modified binding context, with extra properties, and apply it to descendant elements\n var innerContext = bindingContext['extend'](valueAccessor);\n ko.applyBindingsToDescendants(innerContext, element);\n\n return { 'controlsDescendantBindings': true };\n }\n };\n ko.virtualElements.allowedBindings['let'] = true;\n var captionPlaceholder = {};\n ko.bindingHandlers['options'] = {\n 'init': function(element) {\n if (ko.utils.tagNameLower(element) !== \"select\")\n throw new Error(\"options binding applies only to SELECT elements\");\n\n // Remove all existing <option>s.\n while (element.length > 0) {\n element.remove(0);\n }\n\n // Ensures that the binding processor doesn't try to bind the options\n return { 'controlsDescendantBindings': true };\n },\n 'update': function (element, valueAccessor, allBindings) {\n function selectedOptions() {\n return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });\n }\n\n var selectWasPreviouslyEmpty = element.length == 0,\n multiple = element.multiple,\n previousScrollTop = (!selectWasPreviouslyEmpty && multiple) ? element.scrollTop : null,\n unwrappedArray = ko.utils.unwrapObservable(valueAccessor()),\n valueAllowUnset = allBindings.get('valueAllowUnset') && allBindings['has']('value'),\n includeDestroyed = allBindings.get('optionsIncludeDestroyed'),\n arrayToDomNodeChildrenOptions = {},\n captionValue,\n filteredArray,\n previousSelectedValues = [];\n\n if (!valueAllowUnset) {\n if (multiple) {\n previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);\n } else if (element.selectedIndex >= 0) {\n previousSelectedValues.push(ko.selectExtensions.readValue(element.options[element.selectedIndex]));\n }\n }\n\n if (unwrappedArray) {\n if (typeof unwrappedArray.length == \"undefined\") // Coerce single value into array\n unwrappedArray = [unwrappedArray];\n\n // Filter out any entries marked as destroyed\n filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {\n return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);\n });\n\n // If caption is included, add it to the array\n if (allBindings['has']('optionsCaption')) {\n captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));\n // If caption value is null or undefined, don't show a caption\n if (captionValue !== null && captionValue !== undefined) {\n filteredArray.unshift(captionPlaceholder);\n }\n }\n } else {\n // If a falsy value is provided (e.g. null), we'll simply empty the select element\n }\n\n function applyToObject(object, predicate, defaultValue) {\n var predicateType = typeof predicate;\n if (predicateType == \"function\") // Given a function; run it against the data value\n return predicate(object);\n else if (predicateType == \"string\") // Given a string; treat it as a property name on the data value\n return object[predicate];\n else // Given no optionsText arg; use the data value itself\n return defaultValue;\n }\n\n // The following functions can run at two different times:\n // The first is when the whole array is being updated directly from this binding handler.\n // The second is when an observable value for a specific array entry is updated.\n // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.\n var itemUpdate = false;\n function optionForArrayItem(arrayEntry, index, oldOptions) {\n if (oldOptions.length) {\n previousSelectedValues = !valueAllowUnset && oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];\n itemUpdate = true;\n }\n var option = element.ownerDocument.createElement(\"option\");\n if (arrayEntry === captionPlaceholder) {\n ko.utils.setTextContent(option, allBindings.get('optionsCaption'));\n ko.selectExtensions.writeValue(option, undefined);\n } else {\n // Apply a value to the option element\n var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);\n ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));\n\n // Apply some text to the option element\n var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);\n ko.utils.setTextContent(option, optionText);\n }\n return [option];\n }\n\n // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection\n // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208\n arrayToDomNodeChildrenOptions['beforeRemove'] =\n function (option) {\n element.removeChild(option);\n };\n\n function setSelectionCallback(arrayEntry, newOptions) {\n if (itemUpdate && valueAllowUnset) {\n // The model value is authoritative, so make sure its value is the one selected\n ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete);\n } else if (previousSelectedValues.length) {\n // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.\n // That's why we first added them without selection. Now it's time to set the selection.\n var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;\n ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);\n\n // If this option was changed from being selected during a single-item update, notify the change\n if (itemUpdate && !isSelected) {\n ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, \"change\"]);\n }\n }\n }\n\n var callback = setSelectionCallback;\n if (allBindings['has']('optionsAfterRender') && typeof allBindings.get('optionsAfterRender') == \"function\") {\n callback = function(arrayEntry, newOptions) {\n setSelectionCallback(arrayEntry, newOptions);\n ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);\n }\n }\n\n ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);\n\n if (!valueAllowUnset) {\n // Determine if the selection has changed as a result of updating the options list\n var selectionChanged;\n if (multiple) {\n // For a multiple-select box, compare the new selection count to the previous one\n // But if nothing was selected before, the selection can't have changed\n selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;\n } else {\n // For a single-select box, compare the current value to the previous value\n // But if nothing was selected before or nothing is selected now, just look for a change in selection\n selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)\n ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])\n : (previousSelectedValues.length || element.selectedIndex >= 0);\n }\n\n // Ensure consistency between model value and selected option.\n // If the dropdown was changed so that selection is no longer the same,\n // notify the value or selectedOptions binding.\n if (selectionChanged) {\n ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, \"change\"]);\n }\n }\n\n if (valueAllowUnset || ko.computedContext.isInitial()) {\n ko.bindingEvent.notify(element, ko.bindingEvent.childrenComplete);\n }\n\n // Workaround for IE bug\n ko.utils.ensureSelectElementIsRenderedCorrectly(element);\n\n if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)\n element.scrollTop = previousScrollTop;\n }\n };\n ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();\n ko.bindingHandlers['selectedOptions'] = {\n 'init': function (element, valueAccessor, allBindings) {\n function updateFromView() {\n var value = valueAccessor(), valueToWrite = [];\n ko.utils.arrayForEach(element.getElementsByTagName(\"option\"), function(node) {\n if (node.selected)\n valueToWrite.push(ko.selectExtensions.readValue(node));\n });\n ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);\n }\n\n function updateFromModel() {\n var newValue = ko.utils.unwrapObservable(valueAccessor()),\n previousScrollTop = element.scrollTop;\n\n if (newValue && typeof newValue.length == \"number\") {\n ko.utils.arrayForEach(element.getElementsByTagName(\"option\"), function(node) {\n var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;\n if (node.selected != isSelected) { // This check prevents flashing of the select element in IE\n ko.utils.setOptionNodeSelectionState(node, isSelected);\n }\n });\n }\n\n element.scrollTop = previousScrollTop;\n }\n\n if (ko.utils.tagNameLower(element) != \"select\") {\n throw new Error(\"selectedOptions binding applies only to SELECT elements\");\n }\n\n var updateFromModelComputed;\n ko.bindingEvent.subscribe(element, ko.bindingEvent.childrenComplete, function () {\n if (!updateFromModelComputed) {\n ko.utils.registerEventHandler(element, \"change\", updateFromView);\n updateFromModelComputed = ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });\n } else {\n updateFromView();\n }\n }, null, { 'notifyImmediately': true });\n },\n 'update': function() {} // Keep for backwards compatibility with code that may have wrapped binding\n };\n ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;\n ko.bindingHandlers['style'] = {\n 'update': function (element, valueAccessor) {\n var value = ko.utils.unwrapObservable(valueAccessor() || {});\n ko.utils.objectForEach(value, function(styleName, styleValue) {\n styleValue = ko.utils.unwrapObservable(styleValue);\n\n if (styleValue === null || styleValue === undefined || styleValue === false) {\n // Empty string removes the value, whereas null/undefined have no effect\n styleValue = \"\";\n }\n\n if (jQueryInstance) {\n jQueryInstance(element)['css'](styleName, styleValue);\n } else if (/^--/.test(styleName)) {\n // Is styleName a custom CSS property?\n element.style.setProperty(styleName, styleValue);\n } else {\n styleName = styleName.replace(/-(\\w)/g, function (all, letter) {\n return letter.toUpperCase();\n });\n\n var previousStyle = element.style[styleName];\n element.style[styleName] = styleValue;\n\n if (styleValue !== previousStyle && element.style[styleName] == previousStyle && !isNaN(styleValue)) {\n element.style[styleName] = styleValue + \"px\";\n }\n }\n });\n }\n };\n ko.bindingHandlers['submit'] = {\n 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {\n if (typeof valueAccessor() != \"function\")\n throw new Error(\"The value for a submit binding must be a function\");\n ko.utils.registerEventHandler(element, \"submit\", function (event) {\n var handlerReturnValue;\n var value = valueAccessor();\n try { handlerReturnValue = value.call(bindingContext['$data'], element); }\n finally {\n if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.\n if (event.preventDefault)\n event.preventDefault();\n else\n event.returnValue = false;\n }\n }\n });\n }\n };\n ko.bindingHandlers['text'] = {\n 'init': function() {\n // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).\n // It should also make things faster, as we no longer have to consider whether the text node might be bindable.\n return { 'controlsDescendantBindings': true };\n },\n 'update': function (element, valueAccessor) {\n ko.utils.setTextContent(element, valueAccessor());\n }\n };\n ko.virtualElements.allowedBindings['text'] = true;\n (function () {\n\n if (window && window.navigator) {\n var parseVersion = function (matches) {\n if (matches) {\n return parseFloat(matches[1]);\n }\n };\n\n // Detect various browser versions because some old versions don't fully support the 'input' event\n var userAgent = window.navigator.userAgent,\n operaVersion, chromeVersion, safariVersion, firefoxVersion, ieVersion, edgeVersion;\n\n (operaVersion = window.opera && window.opera.version && parseInt(window.opera.version()))\n || (edgeVersion = parseVersion(userAgent.match(/Edge\\/([^ ]+)$/)))\n || (chromeVersion = parseVersion(userAgent.match(/Chrome\\/([^ ]+)/)))\n || (safariVersion = parseVersion(userAgent.match(/Version\\/([^ ]+) Safari/)))\n || (firefoxVersion = parseVersion(userAgent.match(/Firefox\\/([^ ]+)/)))\n || (ieVersion = ko.utils.ieVersion || parseVersion(userAgent.match(/MSIE ([^ ]+)/))) // Detects up to IE 10\n || (ieVersion = parseVersion(userAgent.match(/rv:([^ )]+)/))); // Detects IE 11\n }\n\n// IE 8 and 9 have bugs that prevent the normal events from firing when the value changes.\n// But it does fire the 'selectionchange' event on many of those, presumably because the\n// cursor is moving and that counts as the selection changing. The 'selectionchange' event is\n// fired at the document level only and doesn't directly indicate which element changed. We\n// set up just one event handler for the document and use 'activeElement' to determine which\n// element was changed.\n if (ieVersion >= 8 && ieVersion < 10) {\n var selectionChangeRegisteredName = ko.utils.domData.nextKey(),\n selectionChangeHandlerName = ko.utils.domData.nextKey();\n var selectionChangeHandler = function(event) {\n var target = this.activeElement,\n handler = target && ko.utils.domData.get(target, selectionChangeHandlerName);\n if (handler) {\n handler(event);\n }\n };\n var registerForSelectionChangeEvent = function (element, handler) {\n var ownerDoc = element.ownerDocument;\n if (!ko.utils.domData.get(ownerDoc, selectionChangeRegisteredName)) {\n ko.utils.domData.set(ownerDoc, selectionChangeRegisteredName, true);\n ko.utils.registerEventHandler(ownerDoc, 'selectionchange', selectionChangeHandler);\n }\n ko.utils.domData.set(element, selectionChangeHandlerName, handler);\n };\n }\n\n ko.bindingHandlers['textInput'] = {\n 'init': function (element, valueAccessor, allBindings) {\n\n var previousElementValue = element.value,\n timeoutHandle,\n elementValueBeforeEvent;\n\n var updateModel = function (event) {\n clearTimeout(timeoutHandle);\n elementValueBeforeEvent = timeoutHandle = undefined;\n\n var elementValue = element.value;\n if (previousElementValue !== elementValue) {\n // Provide a way for tests to know exactly which event was processed\n if (DEBUG && event) element['_ko_textInputProcessedEvent'] = event.type;\n previousElementValue = elementValue;\n ko.expressionRewriting.writeValueToProperty(valueAccessor(), allBindings, 'textInput', elementValue);\n }\n };\n\n var deferUpdateModel = function (event) {\n if (!timeoutHandle) {\n // The elementValueBeforeEvent variable is set *only* during the brief gap between an\n // event firing and the updateModel function running. This allows us to ignore model\n // updates that are from the previous state of the element, usually due to techniques\n // such as rateLimit. Such updates, if not ignored, can cause keystrokes to be lost.\n elementValueBeforeEvent = element.value;\n var handler = DEBUG ? updateModel.bind(element, {type: event.type}) : updateModel;\n timeoutHandle = ko.utils.setTimeout(handler, 4);\n }\n };\n\n // IE9 will mess up the DOM if you handle events synchronously which results in DOM changes (such as other bindings);\n // so we'll make sure all updates are asynchronous\n var ieUpdateModel = ko.utils.ieVersion == 9 ? deferUpdateModel : updateModel,\n ourUpdate = false;\n\n var updateView = function () {\n var modelValue = ko.utils.unwrapObservable(valueAccessor());\n\n if (modelValue === null || modelValue === undefined) {\n modelValue = '';\n }\n\n if (elementValueBeforeEvent !== undefined && modelValue === elementValueBeforeEvent) {\n ko.utils.setTimeout(updateView, 4);\n return;\n }\n\n // Update the element only if the element and model are different. On some browsers, updating the value\n // will move the cursor to the end of the input, which would be bad while the user is typing.\n if (element.value !== modelValue) {\n ourUpdate = true; // Make sure we ignore events (propertychange) that result from updating the value\n element.value = modelValue;\n ourUpdate = false;\n previousElementValue = element.value; // In case the browser changes the value (see #2281)\n }\n };\n\n var onEvent = function (event, handler) {\n ko.utils.registerEventHandler(element, event, handler);\n };\n\n if (DEBUG && ko.bindingHandlers['textInput']['_forceUpdateOn']) {\n // Provide a way for tests to specify exactly which events are bound\n ko.utils.arrayForEach(ko.bindingHandlers['textInput']['_forceUpdateOn'], function(eventName) {\n if (eventName.slice(0,5) == 'after') {\n onEvent(eventName.slice(5), deferUpdateModel);\n } else {\n onEvent(eventName, updateModel);\n }\n });\n } else {\n if (ieVersion) {\n // All versions (including 11) of Internet Explorer have a bug that they don't generate an input or propertychange event when ESC is pressed\n onEvent('keypress', updateModel);\n }\n if (ieVersion < 11) {\n // Internet Explorer <= 8 doesn't support the 'input' event, but does include 'propertychange' that fires whenever\n // any property of an element changes. Unlike 'input', it also fires if a property is changed from JavaScript code,\n // but that's an acceptable compromise for this binding. IE 9 and 10 support 'input', but since they don't always\n // fire it when using autocomplete, we'll use 'propertychange' for them also.\n onEvent('propertychange', function(event) {\n if (!ourUpdate && event.propertyName === 'value') {\n ieUpdateModel(event);\n }\n });\n }\n if (ieVersion == 8) {\n // IE 8 has a bug where it fails to fire 'propertychange' on the first update following a value change from\n // JavaScript code. It also doesn't fire if you clear the entire value. To fix this, we bind to the following\n // events too.\n onEvent('keyup', updateModel); // A single keystoke\n onEvent('keydown', updateModel); // The first character when a key is held down\n }\n if (registerForSelectionChangeEvent) {\n // Internet Explorer 9 doesn't fire the 'input' event when deleting text, including using\n // the backspace, delete, or ctrl-x keys, clicking the 'x' to clear the input, dragging text\n // out of the field, and cutting or deleting text using the context menu. 'selectionchange'\n // can detect all of those except dragging text out of the field, for which we use 'dragend'.\n // These are also needed in IE8 because of the bug described above.\n registerForSelectionChangeEvent(element, ieUpdateModel); // 'selectionchange' covers cut, paste, drop, delete, etc.\n onEvent('dragend', deferUpdateModel);\n }\n\n if (!ieVersion || ieVersion >= 9) {\n // All other supported browsers support the 'input' event, which fires whenever the content of the element is changed\n // through the user interface.\n onEvent('input', ieUpdateModel);\n }\n\n if (safariVersion < 5 && ko.utils.tagNameLower(element) === \"textarea\") {\n // Safari <5 doesn't fire the 'input' event for <textarea> elements (it does fire 'textInput'\n // but only when typing). So we'll just catch as much as we can with keydown, cut, and paste.\n onEvent('keydown', deferUpdateModel);\n onEvent('paste', deferUpdateModel);\n onEvent('cut', deferUpdateModel);\n } else if (operaVersion < 11) {\n // Opera 10 doesn't always fire the 'input' event for cut, paste, undo & drop operations.\n // We can try to catch some of those using 'keydown'.\n onEvent('keydown', deferUpdateModel);\n } else if (firefoxVersion < 4.0) {\n // Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete\n onEvent('DOMAutoComplete', updateModel);\n\n // Firefox <=3.5 doesn't fire the 'input' event when text is dropped into the input.\n onEvent('dragdrop', updateModel); // <3.5\n onEvent('drop', updateModel); // 3.5\n } else if (edgeVersion && element.type === \"number\") {\n // Microsoft Edge doesn't fire 'input' or 'change' events for number inputs when\n // the value is changed via the up / down arrow keys\n onEvent('keydown', deferUpdateModel);\n }\n }\n\n // Bind to the change event so that we can catch programmatic updates of the value that fire this event.\n onEvent('change', updateModel);\n\n // To deal with browsers that don't notify any kind of event for some changes (IE, Safari, etc.)\n onEvent('blur', updateModel);\n\n ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });\n }\n };\n ko.expressionRewriting.twoWayBindings['textInput'] = true;\n\n// textinput is an alias for textInput\n ko.bindingHandlers['textinput'] = {\n // preprocess is the only way to set up a full alias\n 'preprocess': function (value, name, addBinding) {\n addBinding('textInput', value);\n }\n };\n\n })();ko.bindingHandlers['uniqueName'] = {\n 'init': function (element, valueAccessor) {\n if (valueAccessor()) {\n var name = \"ko_unique_\" + (++ko.bindingHandlers['uniqueName'].currentIndex);\n ko.utils.setElementName(element, name);\n }\n }\n };\n ko.bindingHandlers['uniqueName'].currentIndex = 0;\n ko.bindingHandlers['using'] = {\n 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {\n var options;\n\n if (allBindings['has']('as')) {\n options = { 'as': allBindings.get('as'), 'noChildContext': allBindings.get('noChildContext') };\n }\n\n var innerContext = bindingContext['createChildContext'](valueAccessor, options);\n ko.applyBindingsToDescendants(innerContext, element);\n\n return { 'controlsDescendantBindings': true };\n }\n };\n ko.virtualElements.allowedBindings['using'] = true;\n ko.bindingHandlers['value'] = {\n 'init': function (element, valueAccessor, allBindings) {\n var tagName = ko.utils.tagNameLower(element),\n isInputElement = tagName == \"input\";\n\n // If the value binding is placed on a radio/checkbox, then just pass through to checkedValue and quit\n if (isInputElement && (element.type == \"checkbox\" || element.type == \"radio\")) {\n ko.applyBindingAccessorsToNode(element, { 'checkedValue': valueAccessor });\n return;\n }\n\n var eventsToCatch = [];\n var requestedEventsToCatch = allBindings.get(\"valueUpdate\");\n var propertyChangedFired = false;\n var elementValueBeforeEvent = null;\n\n if (requestedEventsToCatch) {\n // Allow both individual event names, and arrays of event names\n if (typeof requestedEventsToCatch == \"string\") {\n eventsToCatch = [requestedEventsToCatch];\n } else {\n eventsToCatch = ko.utils.arrayGetDistinctValues(requestedEventsToCatch);\n }\n ko.utils.arrayRemoveItem(eventsToCatch, \"change\"); // We'll subscribe to \"change\" events later\n }\n\n var valueUpdateHandler = function() {\n elementValueBeforeEvent = null;\n propertyChangedFired = false;\n var modelValue = valueAccessor();\n var elementValue = ko.selectExtensions.readValue(element);\n ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);\n }\n\n // Workaround for https://github.com/SteveSanderson/knockout/issues/122\n // IE doesn't fire \"change\" events on textboxes if the user selects a value from its autocomplete list\n var ieAutoCompleteHackNeeded = ko.utils.ieVersion && isInputElement && element.type == \"text\"\n && element.autocomplete != \"off\" && (!element.form || element.form.autocomplete != \"off\");\n if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, \"propertychange\") == -1) {\n ko.utils.registerEventHandler(element, \"propertychange\", function () { propertyChangedFired = true });\n ko.utils.registerEventHandler(element, \"focus\", function () { propertyChangedFired = false });\n ko.utils.registerEventHandler(element, \"blur\", function() {\n if (propertyChangedFired) {\n valueUpdateHandler();\n }\n });\n }\n\n ko.utils.arrayForEach(eventsToCatch, function(eventName) {\n // The syntax \"after<eventname>\" means \"run the handler asynchronously after the event\"\n // This is useful, for example, to catch \"keydown\" events after the browser has updated the control\n // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)\n var handler = valueUpdateHandler;\n if (ko.utils.stringStartsWith(eventName, \"after\")) {\n handler = function() {\n // The elementValueBeforeEvent variable is non-null *only* during the brief gap between\n // a keyX event firing and the valueUpdateHandler running, which is scheduled to happen\n // at the earliest asynchronous opportunity. We store this temporary information so that\n // if, between keyX and valueUpdateHandler, the underlying model value changes separately,\n // we can overwrite that model value change with the value the user just typed. Otherwise,\n // techniques like rateLimit can trigger model changes at critical moments that will\n // override the user's inputs, causing keystrokes to be lost.\n elementValueBeforeEvent = ko.selectExtensions.readValue(element);\n ko.utils.setTimeout(valueUpdateHandler, 0);\n };\n eventName = eventName.substring(\"after\".length);\n }\n ko.utils.registerEventHandler(element, eventName, handler);\n });\n\n var updateFromModel;\n\n if (isInputElement && element.type == \"file\") {\n // For file input elements, can only write the empty string\n updateFromModel = function () {\n var newValue = ko.utils.unwrapObservable(valueAccessor());\n if (newValue === null || newValue === undefined || newValue === \"\") {\n element.value = \"\";\n } else {\n ko.dependencyDetection.ignore(valueUpdateHandler); // reset the model to match the element\n }\n }\n } else {\n updateFromModel = function () {\n var newValue = ko.utils.unwrapObservable(valueAccessor());\n var elementValue = ko.selectExtensions.readValue(element);\n\n if (elementValueBeforeEvent !== null && newValue === elementValueBeforeEvent) {\n ko.utils.setTimeout(updateFromModel, 0);\n return;\n }\n\n var valueHasChanged = newValue !== elementValue;\n\n if (valueHasChanged || elementValue === undefined) {\n if (tagName === \"select\") {\n var allowUnset = allBindings.get('valueAllowUnset');\n ko.selectExtensions.writeValue(element, newValue, allowUnset);\n if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {\n // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,\n // because you're not allowed to have a model value that disagrees with a visible UI selection.\n ko.dependencyDetection.ignore(valueUpdateHandler);\n }\n } else {\n ko.selectExtensions.writeValue(element, newValue);\n }\n }\n };\n }\n\n if (tagName === \"select\") {\n var updateFromModelComputed;\n ko.bindingEvent.subscribe(element, ko.bindingEvent.childrenComplete, function () {\n if (!updateFromModelComputed) {\n ko.utils.registerEventHandler(element, \"change\", valueUpdateHandler);\n updateFromModelComputed = ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });\n } else if (allBindings.get('valueAllowUnset')) {\n updateFromModel();\n } else {\n valueUpdateHandler();\n }\n }, null, { 'notifyImmediately': true });\n } else {\n ko.utils.registerEventHandler(element, \"change\", valueUpdateHandler);\n ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });\n }\n },\n 'update': function() {} // Keep for backwards compatibility with code that may have wrapped value binding\n };\n ko.expressionRewriting.twoWayBindings['value'] = true;\n ko.bindingHandlers['visible'] = {\n 'update': function (element, valueAccessor) {\n var value = ko.utils.unwrapObservable(valueAccessor());\n var isCurrentlyVisible = !(element.style.display == \"none\");\n if (value && !isCurrentlyVisible)\n element.style.display = \"\";\n else if ((!value) && isCurrentlyVisible)\n element.style.display = \"none\";\n }\n };\n\n ko.bindingHandlers['hidden'] = {\n 'update': function (element, valueAccessor) {\n ko.bindingHandlers['visible']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });\n }\n };\n// 'click' is just a shorthand for the usual full-length event:{click:handler}\n makeEventHandlerShortcut('click');\n// If you want to make a custom template engine,\n//\n// [1] Inherit from this class (like ko.nativeTemplateEngine does)\n// [2] Override 'renderTemplateSource', supplying a function with this signature:\n//\n// function (templateSource, bindingContext, options) {\n// // - templateSource.text() is the text of the template you should render\n// // - bindingContext.$data is the data you should pass into the template\n// // - you might also want to make bindingContext.$parent, bindingContext.$parents,\n// // and bindingContext.$root available in the template too\n// // - options gives you access to any other properties set on \"data-bind: { template: options }\"\n// // - templateDocument is the document object of the template\n// //\n// // Return value: an array of DOM nodes\n// }\n//\n// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:\n//\n// function (script) {\n// // Return value: Whatever syntax means \"Evaluate the JavaScript statement 'script' and output the result\"\n// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'\n// }\n//\n// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.\n// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)\n// and then you don't need to override 'createJavaScriptEvaluatorBlock'.\n\n ko.templateEngine = function () { };\n\n ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {\n throw new Error(\"Override renderTemplateSource\");\n };\n\n ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {\n throw new Error(\"Override createJavaScriptEvaluatorBlock\");\n };\n\n ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {\n // Named template\n if (typeof template == \"string\") {\n templateDocument = templateDocument || document;\n var elem = templateDocument.getElementById(template);\n if (!elem)\n throw new Error(\"Cannot find template with ID \" + template);\n return new ko.templateSources.domElement(elem);\n } else if ((template.nodeType == 1) || (template.nodeType == 8)) {\n // Anonymous template\n return new ko.templateSources.anonymousTemplate(template);\n } else\n throw new Error(\"Unknown template type: \" + template);\n };\n\n ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {\n var templateSource = this['makeTemplateSource'](template, templateDocument);\n return this['renderTemplateSource'](templateSource, bindingContext, options, templateDocument);\n };\n\n ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {\n // Skip rewriting if requested\n if (this['allowTemplateRewriting'] === false)\n return true;\n return this['makeTemplateSource'](template, templateDocument)['data'](\"isRewritten\");\n };\n\n ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {\n var templateSource = this['makeTemplateSource'](template, templateDocument);\n var rewritten = rewriterCallback(templateSource['text']());\n templateSource['text'](rewritten);\n templateSource['data'](\"isRewritten\", true);\n };\n\n ko.exportSymbol('templateEngine', ko.templateEngine);\n\n ko.templateRewriting = (function () {\n var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\\d*)(?:\\s+(?!data-bind\\s*=\\s*)[a-z0-9\\-]+(?:=(?:\\\"[^\\\"]*\\\"|\\'[^\\']*\\'|[^>]*))?)*\\s+)data-bind\\s*=\\s*([\"'])([\\s\\S]*?)\\3/gi;\n var memoizeVirtualContainerBindingSyntaxRegex = /<!--\\s*ko\\b\\s*([\\s\\S]*?)\\s*-->/g;\n\n function validateDataBindValuesForRewriting(keyValueArray) {\n var allValidators = ko.expressionRewriting.bindingRewriteValidators;\n for (var i = 0; i < keyValueArray.length; i++) {\n var key = keyValueArray[i]['key'];\n if (Object.prototype.hasOwnProperty.call(allValidators, key)) {\n var validator = allValidators[key];\n\n if (typeof validator === \"function\") {\n var possibleErrorMessage = validator(keyValueArray[i]['value']);\n if (possibleErrorMessage)\n throw new Error(possibleErrorMessage);\n } else if (!validator) {\n throw new Error(\"This template engine does not support the '\" + key + \"' binding within its templates\");\n }\n }\n }\n }\n\n function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {\n var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);\n validateDataBindValuesForRewriting(dataBindKeyValueArray);\n var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});\n\n // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional\n // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this\n // extra indirection.\n var applyBindingsToNextSiblingScript =\n \"ko.__tr_ambtns(function($context,$element){return(function(){return{ \" + rewrittenDataBindAttributeValue + \" } })()},'\" + nodeName.toLowerCase() + \"')\";\n return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;\n }\n\n return {\n ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {\n if (!templateEngine['isTemplateRewritten'](template, templateDocument))\n templateEngine['rewriteTemplate'](template, function (htmlString) {\n return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);\n }, templateDocument);\n },\n\n memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {\n return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {\n return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);\n }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {\n return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ \"<!-- ko -->\", /* nodeName: */ \"#comment\", templateEngine);\n });\n },\n\n applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {\n return ko.memoization.memoize(function (domNode, bindingContext) {\n var nodeToBind = domNode.nextSibling;\n if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {\n ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);\n }\n });\n }\n }\n })();\n\n\n// Exported only because it has to be referenced by string lookup from within rewritten template\n ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);\n (function() {\n // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving\n // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)\n //\n // Two are provided by default:\n // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element\n // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but\n // without reading/writing the actual element text content, since it will be overwritten\n // with the rendered template output.\n // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.\n // Template sources need to have the following functions:\n // text() \t\t\t- returns the template text from your storage location\n // text(value)\t\t- writes the supplied template text to your storage location\n // data(key)\t\t\t- reads values stored using data(key, value) - see below\n // data(key, value)\t- associates \"value\" with this template and the key \"key\". Is used to store information like \"isRewritten\".\n //\n // Optionally, template sources can also have the following functions:\n // nodes() - returns a DOM element containing the nodes of this template, where available\n // nodes(value) - writes the given DOM element to your storage location\n // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()\n // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().\n //\n // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were\n // using and overriding \"makeTemplateSource\" to return an instance of your custom template source.\n\n ko.templateSources = {};\n\n // ---- ko.templateSources.domElement -----\n\n // template types\n var templateScript = 1,\n templateTextArea = 2,\n templateTemplate = 3,\n templateElement = 4;\n\n ko.templateSources.domElement = function(element) {\n this.domElement = element;\n\n if (element) {\n var tagNameLower = ko.utils.tagNameLower(element);\n this.templateType =\n tagNameLower === \"script\" ? templateScript :\n tagNameLower === \"textarea\" ? templateTextArea :\n // For browsers with proper <template> element support, where the .content property gives a document fragment\n tagNameLower == \"template\" && element.content && element.content.nodeType === 11 ? templateTemplate :\n templateElement;\n }\n }\n\n ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {\n var elemContentsProperty = this.templateType === templateScript ? \"text\"\n : this.templateType === templateTextArea ? \"value\"\n : \"innerHTML\";\n\n if (arguments.length == 0) {\n return this.domElement[elemContentsProperty];\n } else {\n var valueToWrite = arguments[0];\n if (elemContentsProperty === \"innerHTML\")\n ko.utils.setHtml(this.domElement, valueToWrite);\n else\n this.domElement[elemContentsProperty] = valueToWrite;\n }\n };\n\n var dataDomDataPrefix = ko.utils.domData.nextKey() + \"_\";\n ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {\n if (arguments.length === 1) {\n return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);\n } else {\n ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);\n }\n };\n\n var templatesDomDataKey = ko.utils.domData.nextKey();\n function getTemplateDomData(element) {\n return ko.utils.domData.get(element, templatesDomDataKey) || {};\n }\n function setTemplateDomData(element, data) {\n ko.utils.domData.set(element, templatesDomDataKey, data);\n }\n\n ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {\n var element = this.domElement;\n if (arguments.length == 0) {\n var templateData = getTemplateDomData(element),\n nodes = templateData.containerData || (\n this.templateType === templateTemplate ? element.content :\n this.templateType === templateElement ? element :\n undefined);\n if (!nodes || templateData.alwaysCheckText) {\n // If the template is associated with an element that stores the template as text,\n // parse and cache the nodes whenever there's new text content available. This allows\n // the user to update the template content by updating the text of template node.\n var text = this['text']();\n if (text && text !== templateData.textData) {\n nodes = ko.utils.parseHtmlForTemplateNodes(text, element.ownerDocument);\n setTemplateDomData(element, {containerData: nodes, textData: text, alwaysCheckText: true});\n }\n }\n return nodes;\n } else {\n var valueToWrite = arguments[0];\n if (this.templateType !== undefined) {\n this['text'](\"\"); // clear the text from the node\n }\n setTemplateDomData(element, {containerData: valueToWrite});\n }\n };\n\n // ---- ko.templateSources.anonymousTemplate -----\n // Anonymous templates are normally saved/retrieved as DOM nodes through \"nodes\".\n // For compatibility, you can also read \"text\"; it will be serialized from the nodes on demand.\n // Writing to \"text\" is still supported, but then the template data will not be available as DOM nodes.\n\n ko.templateSources.anonymousTemplate = function(element) {\n this.domElement = element;\n }\n ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();\n ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;\n ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {\n if (arguments.length == 0) {\n var templateData = getTemplateDomData(this.domElement);\n if (templateData.textData === undefined && templateData.containerData)\n templateData.textData = templateData.containerData.innerHTML;\n return templateData.textData;\n } else {\n var valueToWrite = arguments[0];\n setTemplateDomData(this.domElement, {textData: valueToWrite});\n }\n };\n\n ko.exportSymbol('templateSources', ko.templateSources);\n ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);\n ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);\n })();\n (function () {\n var _templateEngine;\n ko.setTemplateEngine = function (templateEngine) {\n if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))\n throw new Error(\"templateEngine must inherit from ko.templateEngine\");\n _templateEngine = templateEngine;\n }\n\n function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {\n var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);\n while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {\n nextInQueue = ko.virtualElements.nextSibling(node);\n action(node, nextInQueue);\n }\n }\n\n function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {\n // To be used on any nodes that have been rendered by a template and have been inserted into some parent element\n // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because\n // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,\n // (1) Does a regular \"applyBindings\" to associate bindingContext with this node and to activate any non-memoized bindings\n // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)\n\n if (continuousNodeArray.length) {\n var firstNode = continuousNodeArray[0],\n lastNode = continuousNodeArray[continuousNodeArray.length - 1],\n parentNode = firstNode.parentNode,\n provider = ko.bindingProvider['instance'],\n preprocessNode = provider['preprocessNode'];\n\n if (preprocessNode) {\n invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {\n var nodePreviousSibling = node.previousSibling;\n var newNodes = preprocessNode.call(provider, node);\n if (newNodes) {\n if (node === firstNode)\n firstNode = newNodes[0] || nextNodeInRange;\n if (node === lastNode)\n lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;\n }\n });\n\n // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.\n // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real\n // first node needs to be in the array).\n continuousNodeArray.length = 0;\n if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do\n return;\n }\n if (firstNode === lastNode) {\n continuousNodeArray.push(firstNode);\n } else {\n continuousNodeArray.push(firstNode, lastNode);\n ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);\n }\n }\n\n // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)\n // whereas a regular applyBindings won't introduce new memoized nodes\n invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {\n if (node.nodeType === 1 || node.nodeType === 8)\n ko.applyBindings(bindingContext, node);\n });\n invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {\n if (node.nodeType === 1 || node.nodeType === 8)\n ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);\n });\n\n // Make sure any changes done by applyBindings or unmemoize are reflected in the array\n ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);\n }\n }\n\n function getFirstNodeFromPossibleArray(nodeOrNodeArray) {\n return nodeOrNodeArray.nodeType ? nodeOrNodeArray\n : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]\n : null;\n }\n\n function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {\n options = options || {};\n var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);\n var templateDocument = (firstTargetNode || template || {}).ownerDocument;\n var templateEngineToUse = (options['templateEngine'] || _templateEngine);\n ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);\n var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);\n\n // Loosely check result is an array of DOM nodes\n if ((typeof renderedNodesArray.length != \"number\") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != \"number\"))\n throw new Error(\"Template engine must return an array of DOM nodes\");\n\n var haveAddedNodesToParent = false;\n switch (renderMode) {\n case \"replaceChildren\":\n ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);\n haveAddedNodesToParent = true;\n break;\n case \"replaceNode\":\n ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);\n haveAddedNodesToParent = true;\n break;\n case \"ignoreTargetNode\": break;\n default:\n throw new Error(\"Unknown renderMode: \" + renderMode);\n }\n\n if (haveAddedNodesToParent) {\n activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);\n if (options['afterRender']) {\n ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext[options['as'] || '$data']]);\n }\n if (renderMode == \"replaceChildren\") {\n ko.bindingEvent.notify(targetNodeOrNodeArray, ko.bindingEvent.childrenComplete);\n }\n }\n\n return renderedNodesArray;\n }\n\n function resolveTemplateName(template, data, context) {\n // The template can be specified as:\n if (ko.isObservable(template)) {\n // 1. An observable, with string value\n return template();\n } else if (typeof template === 'function') {\n // 2. A function of (data, context) returning a string\n return template(data, context);\n } else {\n // 3. A string\n return template;\n }\n }\n\n ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {\n options = options || {};\n if ((options['templateEngine'] || _templateEngine) == undefined)\n throw new Error(\"Set a template engine before calling renderTemplate\");\n renderMode = renderMode || \"replaceChildren\";\n\n if (targetNodeOrNodeArray) {\n var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);\n\n var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)\n var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == \"replaceNode\") ? firstTargetNode.parentNode : firstTargetNode;\n\n return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes\n function () {\n // Ensure we've got a proper binding context to work with\n var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))\n ? dataOrBindingContext\n : new ko.bindingContext(dataOrBindingContext, null, null, null, { \"exportDependencies\": true });\n\n var templateName = resolveTemplateName(template, bindingContext['$data'], bindingContext),\n renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);\n\n if (renderMode == \"replaceNode\") {\n targetNodeOrNodeArray = renderedNodesArray;\n firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);\n }\n },\n null,\n { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }\n );\n } else {\n // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node\n return ko.memoization.memoize(function (domNode) {\n ko.renderTemplate(template, dataOrBindingContext, options, domNode, \"replaceNode\");\n });\n }\n };\n\n ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {\n // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then\n // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.\n var arrayItemContext, asName = options['as'];\n\n // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode\n var executeTemplateForArrayItem = function (arrayValue, index) {\n // Support selecting template as a function of the data being rendered\n arrayItemContext = parentBindingContext['createChildContext'](arrayValue, {\n 'as': asName,\n 'noChildContext': options['noChildContext'],\n 'extend': function(context) {\n context['$index'] = index;\n if (asName) {\n context[asName + \"Index\"] = index;\n }\n }\n });\n\n var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);\n return executeTemplate(targetNode, \"ignoreTargetNode\", templateName, arrayItemContext, options);\n };\n\n // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode\n var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {\n activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);\n if (options['afterRender'])\n options['afterRender'](addedNodesArray, arrayValue);\n\n // release the \"cache\" variable, so that it can be collected by\n // the GC when its value isn't used from within the bindings anymore.\n arrayItemContext = null;\n };\n\n var setDomNodeChildrenFromArrayMapping = function (newArray, changeList) {\n // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).\n // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.\n ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, newArray, executeTemplateForArrayItem, options, activateBindingsCallback, changeList]);\n ko.bindingEvent.notify(targetNode, ko.bindingEvent.childrenComplete);\n };\n\n var shouldHideDestroyed = (options['includeDestroyed'] === false) || (ko.options['foreachHidesDestroyed'] && !options['includeDestroyed']);\n\n if (!shouldHideDestroyed && !options['beforeRemove'] && ko.isObservableArray(arrayOrObservableArray)) {\n setDomNodeChildrenFromArrayMapping(arrayOrObservableArray.peek());\n\n var subscription = arrayOrObservableArray.subscribe(function (changeList) {\n setDomNodeChildrenFromArrayMapping(arrayOrObservableArray(), changeList);\n }, null, \"arrayChange\");\n subscription.disposeWhenNodeIsRemoved(targetNode);\n\n return subscription;\n } else {\n return ko.dependentObservable(function () {\n var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];\n if (typeof unwrappedArray.length == \"undefined\") // Coerce single value into array\n unwrappedArray = [unwrappedArray];\n\n if (shouldHideDestroyed) {\n // Filter out any entries marked as destroyed\n unwrappedArray = ko.utils.arrayFilter(unwrappedArray, function(item) {\n return item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);\n });\n }\n setDomNodeChildrenFromArrayMapping(unwrappedArray);\n\n }, null, { disposeWhenNodeIsRemoved: targetNode });\n }\n };\n\n var templateComputedDomDataKey = ko.utils.domData.nextKey();\n function disposeOldComputedAndStoreNewOne(element, newComputed) {\n var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);\n if (oldComputed && (typeof(oldComputed.dispose) == 'function'))\n oldComputed.dispose();\n ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && (!newComputed.isActive || newComputed.isActive())) ? newComputed : undefined);\n }\n\n var cleanContainerDomDataKey = ko.utils.domData.nextKey();\n ko.bindingHandlers['template'] = {\n 'init': function(element, valueAccessor) {\n // Support anonymous templates\n var bindingValue = ko.utils.unwrapObservable(valueAccessor());\n if (typeof bindingValue == \"string\" || 'name' in bindingValue) {\n // It's a named template - clear the element\n ko.virtualElements.emptyNode(element);\n } else if ('nodes' in bindingValue) {\n // We've been given an array of DOM nodes. Save them as the template source.\n // There is no known use case for the node array being an observable array (if the output\n // varies, put that behavior *into* your template - that's what templates are for), and\n // the implementation would be a mess, so assert that it's not observable.\n var nodes = bindingValue['nodes'] || [];\n if (ko.isObservable(nodes)) {\n throw new Error('The \"nodes\" option must be a plain, non-observable array.');\n }\n\n // If the nodes are already attached to a KO-generated container, we reuse that container without moving the\n // elements to a new one (we check only the first node, as the nodes are always moved together)\n var container = nodes[0] && nodes[0].parentNode;\n if (!container || !ko.utils.domData.get(container, cleanContainerDomDataKey)) {\n container = ko.utils.moveCleanedNodesToContainerElement(nodes);\n ko.utils.domData.set(container, cleanContainerDomDataKey, true);\n }\n\n new ko.templateSources.anonymousTemplate(element)['nodes'](container);\n } else {\n // It's an anonymous template - store the element contents, then clear the element\n var templateNodes = ko.virtualElements.childNodes(element);\n if (templateNodes.length > 0) {\n var container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent\n new ko.templateSources.anonymousTemplate(element)['nodes'](container);\n } else {\n throw new Error(\"Anonymous template defined, but no template content was provided\");\n }\n }\n return { 'controlsDescendantBindings': true };\n },\n 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {\n var value = valueAccessor(),\n options = ko.utils.unwrapObservable(value),\n shouldDisplay = true,\n templateComputed = null,\n template;\n\n if (typeof options == \"string\") {\n template = value;\n options = {};\n } else {\n template = 'name' in options ? options['name'] : element;\n\n // Support \"if\"/\"ifnot\" conditions\n if ('if' in options)\n shouldDisplay = ko.utils.unwrapObservable(options['if']);\n if (shouldDisplay && 'ifnot' in options)\n shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);\n\n // Don't show anything if an empty name is given (see #2446)\n if (shouldDisplay && !template) {\n shouldDisplay = false;\n }\n }\n\n if ('foreach' in options) {\n // Render once for each data point (treating data set as empty if shouldDisplay==false)\n var dataArray = (shouldDisplay && options['foreach']) || [];\n templateComputed = ko.renderTemplateForEach(template, dataArray, options, element, bindingContext);\n } else if (!shouldDisplay) {\n ko.virtualElements.emptyNode(element);\n } else {\n // Render once for this single data point (or use the viewModel if no data was provided)\n var innerBindingContext = bindingContext;\n if ('data' in options) {\n innerBindingContext = bindingContext['createChildContext'](options['data'], {\n 'as': options['as'],\n 'noChildContext': options['noChildContext'],\n 'exportDependencies': true\n });\n }\n templateComputed = ko.renderTemplate(template, innerBindingContext, options, element);\n }\n\n // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)\n disposeOldComputedAndStoreNewOne(element, templateComputed);\n }\n };\n\n // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.\n ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {\n var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);\n\n if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])\n return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)\n\n if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, \"name\"))\n return null; // Named templates can be rewritten, so return \"no error\"\n return \"This template engine does not support anonymous templates nested within its templates\";\n };\n\n ko.virtualElements.allowedBindings['template'] = true;\n })();\n\n ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);\n ko.exportSymbol('renderTemplate', ko.renderTemplate);\n// Go through the items that have been added and deleted and try to find matches between them.\n ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {\n if (left.length && right.length) {\n var failedCompares, l, r, leftItem, rightItem;\n for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) {\n for (r = 0; rightItem = right[r]; ++r) {\n if (leftItem['value'] === rightItem['value']) {\n leftItem['moved'] = rightItem['index'];\n rightItem['moved'] = leftItem['index'];\n right.splice(r, 1); // This item is marked as moved; so remove it from right list\n failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures\n break;\n }\n }\n failedCompares += r;\n }\n }\n };\n\n ko.utils.compareArrays = (function () {\n var statusNotInOld = 'added', statusNotInNew = 'deleted';\n\n // Simple calculation based on Levenshtein distance.\n function compareArrays(oldArray, newArray, options) {\n // For backward compatibility, if the third arg is actually a bool, interpret\n // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.\n options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});\n oldArray = oldArray || [];\n newArray = newArray || [];\n\n if (oldArray.length < newArray.length)\n return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);\n else\n return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);\n }\n\n function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {\n var myMin = Math.min,\n myMax = Math.max,\n editDistanceMatrix = [],\n smlIndex, smlIndexMax = smlArray.length,\n bigIndex, bigIndexMax = bigArray.length,\n compareRange = (bigIndexMax - smlIndexMax) || 1,\n maxDistance = smlIndexMax + bigIndexMax + 1,\n thisRow, lastRow,\n bigIndexMaxForRow, bigIndexMinForRow;\n\n for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {\n lastRow = thisRow;\n editDistanceMatrix.push(thisRow = []);\n bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);\n bigIndexMinForRow = myMax(0, smlIndex - 1);\n for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {\n if (!bigIndex)\n thisRow[bigIndex] = smlIndex + 1;\n else if (!smlIndex) // Top row - transform empty array into new array via additions\n thisRow[bigIndex] = bigIndex + 1;\n else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])\n thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)\n else {\n var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)\n var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)\n thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;\n }\n }\n }\n\n var editScript = [], meMinusOne, notInSml = [], notInBig = [];\n for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {\n meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;\n if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {\n notInSml.push(editScript[editScript.length] = { // added\n 'status': statusNotInSml,\n 'value': bigArray[--bigIndex],\n 'index': bigIndex });\n } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {\n notInBig.push(editScript[editScript.length] = { // deleted\n 'status': statusNotInBig,\n 'value': smlArray[--smlIndex],\n 'index': smlIndex });\n } else {\n --bigIndex;\n --smlIndex;\n if (!options['sparse']) {\n editScript.push({\n 'status': \"retained\",\n 'value': bigArray[bigIndex] });\n }\n }\n }\n\n // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of\n // smlIndexMax keeps the time complexity of this algorithm linear.\n ko.utils.findMovesInArrayComparison(notInBig, notInSml, !options['dontLimitMoves'] && smlIndexMax * 10);\n\n return editScript.reverse();\n }\n\n return compareArrays;\n })();\n\n ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);\n (function () {\n // Objective:\n // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,\n // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node\n // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node\n // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we\n // previously mapped - retain those nodes, and just insert/delete other ones\n\n // \"callbackAfterAddingNodes\" will be invoked after any \"mapping\"-generated nodes are inserted into the container node\n // You can use this, for example, to activate bindings on those nodes.\n\n function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {\n // Map this array value inside a dependentObservable so we re-map when any dependency changes\n var mappedNodes = [];\n var dependentObservable = ko.dependentObservable(function() {\n var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];\n\n // On subsequent evaluations, just replace the previously-inserted DOM nodes\n if (mappedNodes.length > 0) {\n ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);\n if (callbackAfterAddingNodes)\n ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);\n }\n\n // Replace the contents of the mappedNodes array, thereby updating the record\n // of which nodes would be deleted if valueToMap was itself later removed\n mappedNodes.length = 0;\n ko.utils.arrayPushAll(mappedNodes, newMappedNodes);\n }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });\n return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };\n }\n\n var lastMappingResultDomDataKey = ko.utils.domData.nextKey(),\n deletedItemDummyValue = ko.utils.domData.nextKey();\n\n ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes, editScript) {\n array = array || [];\n if (typeof array.length == \"undefined\") // Coerce single value into array\n array = [array];\n\n options = options || {};\n var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey);\n var isFirstExecution = !lastMappingResult;\n\n // Build the new mapping result\n var newMappingResult = [];\n var lastMappingResultIndex = 0;\n var currentArrayIndex = 0;\n\n var nodesToDelete = [];\n var itemsToMoveFirstIndexes = [];\n var itemsForBeforeRemoveCallbacks = [];\n var itemsForMoveCallbacks = [];\n var itemsForAfterAddCallbacks = [];\n var mapData;\n var countWaitingForRemove = 0;\n\n function itemAdded(value) {\n mapData = { arrayEntry: value, indexObservable: ko.observable(currentArrayIndex++) };\n newMappingResult.push(mapData);\n if (!isFirstExecution) {\n itemsForAfterAddCallbacks.push(mapData);\n }\n }\n\n function itemMovedOrRetained(oldPosition) {\n mapData = lastMappingResult[oldPosition];\n if (currentArrayIndex !== mapData.indexObservable.peek())\n itemsForMoveCallbacks.push(mapData);\n // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray\n mapData.indexObservable(currentArrayIndex++);\n ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);\n newMappingResult.push(mapData);\n }\n\n function callCallback(callback, items) {\n if (callback) {\n for (var i = 0, n = items.length; i < n; i++) {\n ko.utils.arrayForEach(items[i].mappedNodes, function(node) {\n callback(node, i, items[i].arrayEntry);\n });\n }\n }\n }\n\n if (isFirstExecution) {\n ko.utils.arrayForEach(array, itemAdded);\n } else {\n if (!editScript || (lastMappingResult && lastMappingResult['_countWaitingForRemove'])) {\n // Compare the provided array against the previous one\n var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; }),\n compareOptions = {\n 'dontLimitMoves': options['dontLimitMoves'],\n 'sparse': true\n };\n editScript = ko.utils.compareArrays(lastArray, array, compareOptions);\n }\n\n for (var i = 0, editScriptItem, movedIndex, itemIndex; editScriptItem = editScript[i]; i++) {\n movedIndex = editScriptItem['moved'];\n itemIndex = editScriptItem['index'];\n switch (editScriptItem['status']) {\n case \"deleted\":\n while (lastMappingResultIndex < itemIndex) {\n itemMovedOrRetained(lastMappingResultIndex++);\n }\n if (movedIndex === undefined) {\n mapData = lastMappingResult[lastMappingResultIndex];\n\n // Stop tracking changes to the mapping for these nodes\n if (mapData.dependentObservable) {\n mapData.dependentObservable.dispose();\n mapData.dependentObservable = undefined;\n }\n\n // Queue these nodes for later removal\n if (ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode).length) {\n if (options['beforeRemove']) {\n newMappingResult.push(mapData);\n countWaitingForRemove++;\n if (mapData.arrayEntry === deletedItemDummyValue) {\n mapData = null;\n } else {\n itemsForBeforeRemoveCallbacks.push(mapData);\n }\n }\n if (mapData) {\n nodesToDelete.push.apply(nodesToDelete, mapData.mappedNodes);\n }\n }\n }\n lastMappingResultIndex++;\n break;\n\n case \"added\":\n while (currentArrayIndex < itemIndex) {\n itemMovedOrRetained(lastMappingResultIndex++);\n }\n if (movedIndex !== undefined) {\n itemsToMoveFirstIndexes.push(newMappingResult.length);\n itemMovedOrRetained(movedIndex);\n } else {\n itemAdded(editScriptItem['value']);\n }\n break;\n }\n }\n\n while (currentArrayIndex < array.length) {\n itemMovedOrRetained(lastMappingResultIndex++);\n }\n\n // Record that the current view may still contain deleted items\n // because it means we won't be able to use a provided editScript.\n newMappingResult['_countWaitingForRemove'] = countWaitingForRemove;\n }\n\n // Store a copy of the array items we just considered so we can difference it next time\n ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);\n\n // Call beforeMove first before any changes have been made to the DOM\n callCallback(options['beforeMove'], itemsForMoveCallbacks);\n\n // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)\n ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);\n\n var i, j, lastNode, nodeToInsert, mappedNodes, activeElement;\n\n // Since most browsers remove the focus from an element when it's moved to another location,\n // save the focused element and try to restore it later.\n try {\n activeElement = domNode.ownerDocument.activeElement;\n } catch(e) {\n // IE9 throws if you access activeElement during page load (see issue #703)\n }\n\n // Try to reduce overall moved nodes by first moving the ones that were marked as moved by the edit script\n if (itemsToMoveFirstIndexes.length) {\n while ((i = itemsToMoveFirstIndexes.shift()) != undefined) {\n mapData = newMappingResult[i];\n for (lastNode = undefined; i; ) {\n if ((mappedNodes = newMappingResult[--i].mappedNodes) && mappedNodes.length) {\n lastNode = mappedNodes[mappedNodes.length-1];\n break;\n }\n }\n for (j = 0; nodeToInsert = mapData.mappedNodes[j]; lastNode = nodeToInsert, j++) {\n ko.virtualElements.insertAfter(domNode, nodeToInsert, lastNode);\n }\n }\n }\n\n // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)\n for (i = 0; mapData = newMappingResult[i]; i++) {\n // Get nodes for newly added items\n if (!mapData.mappedNodes)\n ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));\n\n // Put nodes in the right place if they aren't there already\n for (j = 0; nodeToInsert = mapData.mappedNodes[j]; lastNode = nodeToInsert, j++) {\n ko.virtualElements.insertAfter(domNode, nodeToInsert, lastNode);\n }\n\n // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)\n if (!mapData.initialized && callbackAfterAddingNodes) {\n callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);\n mapData.initialized = true;\n lastNode = mapData.mappedNodes[mapData.mappedNodes.length - 1]; // get the last node again since it may have been changed by a preprocessor\n }\n }\n\n // Restore the focused element if it had lost focus\n if (activeElement && domNode.ownerDocument.activeElement != activeElement) {\n activeElement.focus();\n }\n\n // If there's a beforeRemove callback, call it after reordering.\n // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using\n // some sort of animation, which is why we first reorder the nodes that will be removed. If the\n // callback instead removes the nodes right away, it would be more efficient to skip reordering them.\n // Perhaps we'll make that change in the future if this scenario becomes more common.\n callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);\n\n // Replace the stored values of deleted items with a dummy value. This provides two benefits: it marks this item\n // as already \"removed\" so we won't call beforeRemove for it again, and it ensures that the item won't match up\n // with an actual item in the array and appear as \"retained\" or \"moved\".\n for (i = 0; i < itemsForBeforeRemoveCallbacks.length; ++i) {\n itemsForBeforeRemoveCallbacks[i].arrayEntry = deletedItemDummyValue;\n }\n\n // Finally call afterMove and afterAdd callbacks\n callCallback(options['afterMove'], itemsForMoveCallbacks);\n callCallback(options['afterAdd'], itemsForAfterAddCallbacks);\n }\n })();\n\n ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);\n ko.nativeTemplateEngine = function () {\n this['allowTemplateRewriting'] = false;\n }\n\n ko.nativeTemplateEngine.prototype = new ko.templateEngine();\n ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;\n ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {\n var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly\n templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,\n templateNodes = templateNodesFunc ? templateSource['nodes']() : null;\n\n if (templateNodes) {\n return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);\n } else {\n var templateText = templateSource['text']();\n return ko.utils.parseHtmlFragment(templateText, templateDocument);\n }\n };\n\n ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();\n ko.setTemplateEngine(ko.nativeTemplateEngine.instance);\n\n ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);\n (function() {\n ko.jqueryTmplTemplateEngine = function () {\n // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl\n // doesn't expose a version number, so we have to infer it.\n // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,\n // which KO internally refers to as version \"2\", so older versions are no longer detected.\n var jQueryTmplVersion = this.jQueryTmplVersion = (function() {\n if (!jQueryInstance || !(jQueryInstance['tmpl']))\n return 0;\n // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.\n try {\n if (jQueryInstance['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {\n // Since 1.0.0pre, custom tags should append markup to an array called \"__\"\n return 2; // Final version of jquery.tmpl\n }\n } catch(ex) { /* Apparently not the version we were looking for */ }\n\n return 1; // Any older version that we don't support\n })();\n\n function ensureHasReferencedJQueryTemplates() {\n if (jQueryTmplVersion < 2)\n throw new Error(\"Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.\");\n }\n\n function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {\n return jQueryInstance['tmpl'](compiledTemplate, data, jQueryTemplateOptions);\n }\n\n this['renderTemplateSource'] = function(templateSource, bindingContext, options, templateDocument) {\n templateDocument = templateDocument || document;\n options = options || {};\n ensureHasReferencedJQueryTemplates();\n\n // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)\n var precompiled = templateSource['data']('precompiled');\n if (!precompiled) {\n var templateText = templateSource['text']() || \"\";\n // Wrap in \"with($whatever.koBindingContext) { ... }\"\n templateText = \"{{ko_with $item.koBindingContext}}\" + templateText + \"{{/ko_with}}\";\n\n precompiled = jQueryInstance['template'](null, templateText);\n templateSource['data']('precompiled', precompiled);\n }\n\n var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays\n var jQueryTemplateOptions = jQueryInstance['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);\n\n var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);\n resultNodes['appendTo'](templateDocument.createElement(\"div\")); // Using \"appendTo\" forces jQuery/jQuery.tmpl to perform necessary cleanup work\n\n jQueryInstance['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders\n return resultNodes;\n };\n\n this['createJavaScriptEvaluatorBlock'] = function(script) {\n return \"{{ko_code ((function() { return \" + script + \" })()) }}\";\n };\n\n this['addTemplate'] = function(templateName, templateMarkup) {\n document.write(\"<script type='text/html' id='\" + templateName + \"'>\" + templateMarkup + \"<\" + \"/script>\");\n };\n\n if (jQueryTmplVersion > 0) {\n jQueryInstance['tmpl']['tag']['ko_code'] = {\n open: \"__.push($1 || '');\"\n };\n jQueryInstance['tmpl']['tag']['ko_with'] = {\n open: \"with($1) {\",\n close: \"} \"\n };\n }\n };\n\n ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();\n ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;\n\n // Use this one by default *only if jquery.tmpl is referenced*\n var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();\n if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)\n ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);\n\n ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);\n })();\n }));\n }());\n})();\n","WebShopApps_MatrixRate/js/view/shipping-rates-validation.js":"/**\n * Copyright \u00a9 2015 Magento. All rights reserved.\n * See COPYING.txt for license details.\n */\n/*browser:true*/\n/*global define*/\ndefine(\n [\n 'uiComponent',\n 'Magento_Checkout/js/model/shipping-rates-validator',\n 'Magento_Checkout/js/model/shipping-rates-validation-rules',\n '../model/shipping-rates-validator',\n '../model/shipping-rates-validation-rules'\n ],\n function (\n Component,\n defaultShippingRatesValidator,\n defaultShippingRatesValidationRules,\n matrixrateShippingRatesValidator,\n matrixrateShippingRatesValidationRules\n ) {\n \"use strict\";\n defaultShippingRatesValidator.registerValidator('matrixrate', matrixrateShippingRatesValidator);\n defaultShippingRatesValidationRules.registerRules('matrixrate', matrixrateShippingRatesValidationRules);\n return Component;\n }\n);\n","WebShopApps_MatrixRate/js/model/shipping-rates-validator.js":"define(\n [\n 'jquery',\n 'mageUtils',\n './shipping-rates-validation-rules',\n 'mage/translate'\n ],\n function ($, utils, validationRules, $t) {\n \"use strict\";\n return {\n validationErrors: [],\n validate: function (address) {\n var self = this;\n this.validationErrors = [];\n $.each(validationRules.getRules(), function (field, rule) {\n if (rule.required && utils.isEmpty(address[field])) {\n var message = $t('Field ') + field + $t(' is required.');\n self.validationErrors.push(message);\n }\n });\n return !Boolean(this.validationErrors.length);\n }\n };\n }\n);","WebShopApps_MatrixRate/js/model/shipping-rates-validation-rules.js":"/**\n * Copyright \u00a9 2015 Magento. All rights reserved.\n * See COPYING.txt for license details.\n */\n/*global define*/\ndefine(\n [],\n function () {\n \"use strict\";\n return {\n getRules: function () {\n return {\n 'postcode': {\n 'required': true\n },\n 'country_id': {\n 'required': true\n },\n 'region_id' : {\n 'required': false\n },\n 'city' : {\n 'required': false\n }\n };\n }\n };\n }\n);\n","Magento_Paypal/js/paypal-checkout.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'Magento_Ui/js/modal/confirm',\n 'Magento_Customer/js/customer-data',\n 'jquery-ui-modules/widget',\n 'mage/mage'\n], function ($, confirm, customerData) {\n 'use strict';\n\n $.widget('mage.paypalCheckout', {\n options: {\n originalForm:\n 'form:not(#product_addtocart_form_from_popup):has(input[name=\"product\"][value=%1])',\n productId: 'input[type=\"hidden\"][name=\"product\"]',\n ppCheckoutSelector: '[data-role=pp-checkout-url]',\n ppCheckoutInput: '<input type=\"hidden\" data-role=\"pp-checkout-url\" name=\"return_url\" value=\"\"/>'\n },\n\n /**\n * Initialize store credit events\n * @private\n */\n _create: function () {\n this.element.on('click', '[data-action=\"checkout-form-submit\"]', $.proxy(function (e) {\n var $target = $(e.target),\n returnUrl = $target.data('checkout-url'),\n productId = $target.closest('form').find(this.options.productId).val(),\n originalForm = this.options.originalForm.replace('%1', productId),\n self = this,\n billingAgreement = customerData.get('paypal-billing-agreement');\n\n e.preventDefault();\n\n if (billingAgreement().askToCreate) {\n confirm({\n content: billingAgreement().confirmMessage,\n actions: {\n\n /**\n * Confirmation handler\n *\n */\n confirm: function () {\n returnUrl = billingAgreement().confirmUrl;\n self._redirect(returnUrl, originalForm);\n },\n\n /**\n * Cancel confirmation handler\n *\n */\n cancel: function (event) {\n if (event && !$(event.target).hasClass('action-close')) {\n self._redirect(returnUrl);\n }\n }\n }\n });\n } else {\n this._redirect(returnUrl, originalForm);\n }\n }, this));\n },\n\n /**\n * Redirect to certain url, with optional form\n * @param {String} returnUrl\n * @param {HTMLElement} originalForm\n *\n */\n _redirect: function (returnUrl, originalForm) {\n var $form,\n ppCheckoutInput;\n\n if (this.options.isCatalogProduct) {\n // find the form from which the button was clicked\n $form = originalForm ? $(originalForm) : $($(this.options.shortcutContainerClass).closest('form'));\n\n ppCheckoutInput = $form.find(this.options.ppCheckoutSelector)[0];\n\n if (!ppCheckoutInput) {\n ppCheckoutInput = $(this.options.ppCheckoutInput);\n ppCheckoutInput.appendTo($form);\n }\n $(ppCheckoutInput).val(returnUrl);\n\n $form.trigger('submit');\n } else {\n $.mage.redirect(returnUrl);\n }\n }\n });\n\n return $.mage.paypalCheckout;\n});\n","Magento_Paypal/js/order-review.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'Magento_Ui/js/modal/alert',\n 'jquery-ui-modules/widget',\n 'mage/translate',\n 'mage/mage',\n 'mage/validation'\n], function ($, alert) {\n 'use strict';\n\n $.widget('mage.orderReview', {\n options: {\n orderReviewSubmitSelector: '#review-button',\n shippingSelector: '#shipping_method',\n shippingSubmitFormSelector: null,\n updateOrderSelector: '#update-order',\n billingAsShippingSelector: '#billing\\\\:as_shipping',\n updateContainerSelector: '#details-reload',\n waitLoadingContainer: '#review-please-wait',\n shippingMethodContainer: '#shipping-method-container',\n agreementSelector: 'div.checkout-agreements input',\n isAjax: false,\n shippingMethodUpdateUrl: null,\n updateOrderSubmitUrl: null,\n canEditShippingMethod: false\n },\n\n /**\n * Widget instance properties\n */\n triggerPropertyChange: true,\n isShippingSubmitForm: false,\n\n /** @inheritdoc */\n _create: function () {\n var isDisable;\n\n //change handler for ajaxEnabled\n if (this.options.isAjax) {\n this._submitOrder = this._ajaxSubmitOrder;\n }\n\n this.element.on('click', this.options.orderReviewSubmitSelector, $.proxy(this._submitOrder, this))\n .on('click', this.options.billingAsShippingSelector, $.proxy(this._shippingTobilling, this))\n .on('change',\n this.options.shippingSelector,\n $.proxy(this._submitUpdateOrder,\n this,\n this.options.updateOrderSubmitUrl,\n this.options.updateContainerSelector\n )\n ).find(this.options.updateOrderSelector).on('click', $.proxy(this._updateOrderHandler, this)).end();\n this._shippingTobilling();\n\n if ($(this.options.shippingSubmitFormSelector).length && this.options.canEditShippingMethod) {\n this.isShippingSubmitForm = true;\n $(this.options.shippingSubmitFormSelector)\n .on('change',\n this.options.shippingSelector,\n $.proxy(\n this._submitUpdateOrder,\n this,\n $(this.options.shippingSubmitFormSelector).prop('action'),\n this.options.updateContainerSelector\n )\n );\n this._updateOrderSubmit(!$(this.options.shippingSubmitFormSelector)\n .find(this.options.shippingSelector).val());\n } else {\n isDisable = this.isShippingSubmitForm && this.element.find(this.options.shippingSelector).val();\n this.element\n .on('input propertychange', ':input[name]',\n $.proxy(this._updateOrderSubmit, this, isDisable, this._onShippingChange)\n ).find('select').not(this.options.shippingSelector).on('change', this._propertyChange);\n this._updateOrderSubmit(isDisable);\n }\n },\n\n /**\n * show ajax loader\n */\n _ajaxBeforeSend: function () {\n this.element.find(this.options.waitLoadingContainer).show();\n },\n\n /**\n * hide ajax loader\n */\n _ajaxComplete: function () {\n this.element.find(this.options.waitLoadingContainer).hide();\n },\n\n /**\n * trigger propertychange for input type select\n */\n _propertyChange: function () {\n $(this).trigger('propertychange');\n },\n\n /**\n * trigger change for the update of shipping methods from server\n */\n _updateOrderHandler: function () {\n $(this.options.shippingSelector).trigger('change');\n },\n\n /**\n * Attempt to submit order\n */\n _submitOrder: function () {\n if (this._validateForm()) {\n this.element.find(this.options.updateOrderSelector).fadeTo(0, 0.5)\n .end().find(this.options.waitLoadingContainer).show()\n .end().trigger('submit');\n this._updateOrderSubmit(true);\n }\n },\n\n /**\n * Attempt to ajax submit order\n */\n _ajaxSubmitOrder: function () {\n if (this.element.find(this.options.waitLoadingContainer).is(':visible')) {\n return false;\n }\n $.ajax({\n url: this.element.prop('action'),\n type: 'post',\n context: this,\n data: {\n isAjax: 1\n },\n dataType: 'json',\n beforeSend: this._ajaxBeforeSend,\n complete: this._ajaxComplete,\n\n /** @inheritdoc */\n success: function (response) {\n var msg;\n\n if (typeof response === 'object' && !$.isEmptyObject(response)) {\n if (response['error_messages']) {\n this._ajaxComplete();\n msg = response['error_messages'];\n\n /* eslint-disable max-depth */\n if (msg) {\n if (Array.isArray(msg)) {\n msg = msg.join('\\n');\n }\n }\n\n /* eslint-enablemax-depth */\n alert({\n content: msg\n });\n\n return false;\n }\n\n if (response.redirect) {\n $.mage.redirect(response.redirect);\n\n return false;\n } else if (response.success) {\n $.mage.redirect(this.options.successUrl);\n\n return false;\n }\n this._ajaxComplete();\n alert({\n content: $.mage.__('Sorry, something went wrong.')\n });\n }\n },\n\n /** @inheritdoc */\n error: function () {\n alert({\n content: $.mage.__('Sorry, something went wrong. Please try again later.')\n });\n this._ajaxComplete();\n }\n });\n },\n\n /**\n * Validate Order form\n */\n _validateForm: function () {\n this.element.find(this.options.agreementSelector).off('change').on('change', $.proxy(function () {\n var isValid = this._validateForm();\n\n this._updateOrderSubmit(!isValid);\n }, this));\n\n if (this.element.data('mageValidation')) {\n return this.element.validation().valid();\n }\n\n return true;\n },\n\n /**\n * Check/Set whether order can be submitted\n * Also disables form submission element, if any\n * @param {*} shouldDisable - whether should prevent order submission explicitly\n * @param {Function} [fn] - function for shipping change handler\n * @param {*} [*] - if true the property change will be set to true\n */\n _updateOrderSubmit: function (shouldDisable, fn) {\n this._toggleButton(this.options.orderReviewSubmitSelector, shouldDisable);\n\n if (typeof fn === 'function') {\n fn.call(this);\n }\n },\n\n /**\n * Enable/Disable button\n * @param {jQuery} button - button selector to be toggled\n * @param {*} disable - boolean for toggling\n */\n _toggleButton: function (button, disable) {\n $(button).prop({\n 'disabled': disable\n }).toggleClass('no-checkout', disable).fadeTo(0, disable ? 0.5 : 1);\n },\n\n /**\n * Copy element value from shipping to billing address\n * @param {jQuery.Event} e - optional\n */\n _shippingTobilling: function (e) {\n var isChecked, opacity;\n\n if (this.options.shippingSubmitFormSelector) {\n return false;\n }\n isChecked = $(this.options.billingAsShippingSelector).is(':checked');\n opacity = isChecked ? 0.5 : 1;\n\n if (isChecked) {\n this.element.validation('clearError', ':input[name^=\"billing\"]');\n }\n $(':input[name^=\"shipping\"]', this.element).each($.proxy(function (key, value) {\n var fieldObj = $(value.id.replace('shipping:', '#billing\\\\:'));\n\n if (isChecked) {\n fieldObj = fieldObj.val($(value).val());\n }\n fieldObj.prop({\n 'readonly': isChecked,\n 'disabled': isChecked\n }).fadeTo(0, opacity);\n\n if (fieldObj.is('select')) {\n this.triggerPropertyChange = false;\n fieldObj.trigger('change');\n }\n }, this));\n\n if (isChecked || e) {\n this._updateOrderSubmit(true);\n }\n this.triggerPropertyChange = true;\n },\n\n /**\n * Dispatch an ajax request of Update Order submission\n * @param {*} url - url where to submit shipping method\n * @param {*} resultId - id of element to be updated\n */\n _submitUpdateOrder: function (url, resultId) {\n var isChecked, formData, callBackResponseHandler, shippingMethod;\n\n if (this.element.find(this.options.waitLoadingContainer).is(':visible')) {\n return false;\n }\n isChecked = $(this.options.billingAsShippingSelector).is(':checked');\n formData = null;\n callBackResponseHandler = null;\n let val = $(this.options.shippingSelector).val();\n\n shippingMethod = val.trim();\n this._shippingTobilling();\n\n if (url && resultId && shippingMethod) {\n this._updateOrderSubmit(true);\n this._toggleButton(this.options.updateOrderSelector, true);\n\n // form data and callBack updated based on the shipping Form element\n if (this.isShippingSubmitForm) {\n formData = $(this.options.shippingSubmitFormSelector).serialize() + '&isAjax=true';\n\n /**\n * @param {Object} response\n */\n callBackResponseHandler = function (response) {\n $(resultId).html(response);\n this._updateOrderSubmit(false);\n this._ajaxComplete();\n };\n } else {\n formData = this.element.serialize() + '&isAjax=true';\n\n /**\n * @param {Object} response\n */\n callBackResponseHandler = function (response) {\n $(resultId).html(response);\n this._ajaxShippingUpdate(shippingMethod);\n };\n }\n\n if (isChecked) {\n $(this.options.shippingSelect).prop('disabled', true);\n }\n $.ajax({\n url: url,\n type: 'post',\n context: this,\n beforeSend: this._ajaxBeforeSend,\n data: formData,\n success: callBackResponseHandler\n });\n }\n },\n\n /**\n * Update Shipping Methods Element from server\n * @param {*} shippingMethod\n */\n _ajaxShippingUpdate: function (shippingMethod) {\n $.ajax({\n url: this.options.shippingMethodUpdateUrl,\n data: {\n isAjax: true,\n 'shipping_method': shippingMethod\n },\n type: 'post',\n context: this,\n\n /** @inheritdoc */\n success: function (response) {\n $(this.options.shippingMethodContainer).parent().html(response);\n this._toggleButton(this.options.updateOrderSelector, false);\n this._updateOrderSubmit(false);\n },\n complete: this._ajaxComplete\n });\n },\n\n /**\n * Actions on change Shipping Address data\n */\n _onShippingChange: function () {\n let val = $(this.options.shippingSelector).val();\n\n if (this.triggerPropertyChange && val.trim()) {\n this.element.find(this.options.shippingSelector).hide().end()\n .find(this.options.shippingSelector + '_update').show();\n }\n }\n });\n\n return $.mage.orderReview;\n});\n","Magento_Paypal/js/action/set-payment-method.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'Magento_Checkout/js/model/quote',\n 'Magento_Checkout/js/action/set-payment-information'\n], function (quote, setPaymentInformation) {\n 'use strict';\n\n return function (messageContainer) {\n return setPaymentInformation(messageContainer, quote.paymentMethod());\n };\n});\n","Magento_Paypal/js/in-context/button.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'uiComponent',\n 'jquery',\n 'Magento_Paypal/js/in-context/express-checkout-wrapper',\n 'Magento_Customer/js/customer-data'\n], function (Component, $, Wrapper, customerData) {\n 'use strict';\n\n return Component.extend(Wrapper).extend({\n defaults: {\n declinePayment: false\n },\n\n /** @inheritdoc */\n initialize: function (config, element) {\n var cart = customerData.get('cart'),\n customer = customerData.get('customer');\n\n this._super();\n this.renderPayPalButtons(element);\n\n if (cart().isGuestCheckoutAllowed === undefined) {\n cart.subscribe(function (updatedCart) {\n this.declinePayment = !customer().firstname && !cart().isGuestCheckoutAllowed;\n\n return updatedCart;\n }.bind(this));\n }\n\n return this;\n },\n\n /** @inheritdoc */\n beforePayment: function (resolve, reject) {\n var promise = $.Deferred();\n\n if (this.declinePayment) {\n this.addError(this.signInMessage, 'warning');\n\n reject();\n } else {\n promise.resolve();\n }\n\n return promise;\n },\n\n /** @inheritdoc */\n prepareClientConfig: function () {\n this._super();\n\n return this.clientConfig;\n }\n });\n});\n","Magento_Paypal/js/in-context/express-checkout-wrapper.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'jquery',\n 'mage/translate',\n 'Magento_Customer/js/customer-data',\n 'Magento_Paypal/js/in-context/express-checkout-smart-buttons',\n 'Magento_Ui/js/modal/alert',\n 'mage/cookies'\n], function ($, $t, customerData, checkoutSmartButtons, alert) {\n 'use strict';\n\n return {\n defaults: {\n paymentActionError: $t('Something went wrong with your request. Please try again later.'),\n signInMessage: $t('To check out, please sign in with your email address.')\n },\n\n /**\n * Render PayPal buttons using checkout.js\n */\n renderPayPalButtons: function (element) {\n checkoutSmartButtons(this.prepareClientConfig(), element);\n },\n\n /**\n * Validate payment method\n *\n * @param {Object} actions\n */\n validate: function (actions) {\n this.actions = actions || this.actions;\n },\n\n /**\n * Execute logic on Paypal button click\n */\n onClick: function () {},\n\n /**\n * Before payment execute\n *\n * @param {Function} resolve\n * @param {Function} reject\n * @return {*}\n */\n beforePayment: function (resolve, reject) { //eslint-disable-line no-unused-vars\n return $.Deferred().resolve();\n },\n\n /**\n * After payment execute\n *\n * @param {Object} res\n * @param {Function} resolve\n * @param {Function} reject\n *\n * @return {*}\n */\n afterPayment: function (res, resolve, reject) {\n\n if (res.success) {\n return resolve(res.token);\n }\n\n return reject(new Error(res['error_message']));\n },\n\n /**\n * Catch payment\n *\n * @param {Error} err\n * @param {Function} resolve\n * @param {Function} reject\n */\n catchPayment: function (err, resolve, reject) {\n this.addAlert(this.paymentActionError);\n reject(err);\n },\n\n /**\n * Before onAuthorize execute\n *\n * @param {Function} resolve\n * @param {Function} reject\n * @param {Object} actions\n *\n * @return {jQuery.Deferred}\n */\n beforeOnAuthorize: function (resolve, reject, actions) { //eslint-disable-line no-unused-vars\n //display loading widget.\n $('body').trigger('processStart');\n\n return $.Deferred().resolve();\n },\n\n /**\n * After onAuthorize execute\n *\n * @param {Object} res\n * @param {Function} resolve\n * @param {Function} reject\n * @param {Object} actions\n *\n * @return {*}\n */\n afterOnAuthorize: function (res, resolve, reject, actions) {\n $('body').trigger('processStop');\n\n if (res.success) {\n resolve();\n\n return actions.redirect(res.redirectUrl);\n }\n\n return reject(new Error(res['error_message']));\n },\n\n /**\n * Catch payment\n *\n * @param {Error} err\n * @param {Function} resolve\n * @param {Function} reject\n */\n catchOnAuthorize: function (err, resolve, reject) {\n $('body').trigger('processStop');\n this.addAlert(this.paymentActionError);\n reject(err);\n },\n\n /**\n * Process cancel action\n *\n * @param {Object} data\n * @param {Object} actions\n */\n onCancel: function (data, actions) {\n $('body').trigger('processStop');\n actions.redirect(this.clientConfig.onCancelUrl);\n },\n\n /**\n * Process errors\n *\n * @param {Error} err\n */\n onError: function (err) { //eslint-disable-line no-unused-vars\n // Uncaught error isn't displayed in the console\n },\n\n /**\n * Adds error message\n *\n * @param {String} message\n * @param {String} [type]\n */\n addError: function (message, type) {\n type = type || 'error';\n customerData.set('messages', {\n messages: [{\n type: type,\n text: message\n }],\n 'data_id': Math.floor(Date.now() / 1000)\n });\n },\n\n /**\n * Add alert message\n *\n * @param {String} message\n */\n addAlert: function (message) {\n alert({\n content: message\n });\n },\n\n /**\n * @returns {String}\n */\n getButtonId: function () {\n return this.inContextId;\n },\n\n /**\n * Populate client config with all required data\n *\n * @return {Object}\n */\n prepareClientConfig: function () {\n this.clientConfig.rendererComponent = this;\n this.clientConfig.formKey = $.mage.cookies.get('form_key');\n\n return this.clientConfig;\n }\n };\n});\n","Magento_Paypal/js/in-context/express-checkout-smart-buttons.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n/* eslint-disable max-nested-callbacks */\ndefine([\n 'underscore',\n 'jquery',\n 'Magento_Paypal/js/in-context/paypal-sdk',\n 'Magento_Customer/js/customer-data',\n 'domReady!'\n], function (_, $, paypalSdk, customerData) {\n 'use strict';\n\n /**\n * Triggers beforePayment action on PayPal buttons\n *\n * @param {Object} clientConfig\n * @returns {Object} jQuery promise\n */\n function performCreateOrder(clientConfig) {\n var params = {\n 'quote_id': clientConfig.quoteId,\n 'customer_id': clientConfig.customerId || '',\n 'form_key': clientConfig.formKey,\n button: clientConfig.button\n };\n\n return $.Deferred(function (deferred) {\n clientConfig.rendererComponent.beforePayment(deferred.resolve, deferred.reject).then(function () {\n $.post(clientConfig.getTokenUrl, params).done(function (res) {\n clientConfig.rendererComponent.afterPayment(res, deferred.resolve, deferred.reject);\n }).fail(function (jqXHR, textStatus, err) {\n clientConfig.rendererComponent.catchPayment(err, deferred.resolve, deferred.reject);\n });\n });\n }).promise();\n }\n\n /**\n * Triggers beforeOnAuthorize action on PayPal buttons\n * @param {Object} clientConfig\n * @param {Object} data\n * @param {Object} actions\n * @returns {Object} jQuery promise\n */\n function performOnApprove(clientConfig, data, actions) {\n var params = {\n paymentToken: data.orderID,\n payerId: data.payerID,\n paypalFundingSource: customerData.get('paypal-funding-source'),\n 'form_key': clientConfig.formKey\n };\n\n return $.Deferred(function (deferred) {\n clientConfig.rendererComponent.beforeOnAuthorize(deferred.resolve, deferred.reject, actions)\n .then(function () {\n $.post(clientConfig.onAuthorizeUrl, params).done(function (res) {\n if (res.success === false) {\n clientConfig.rendererComponent.catchOnAuthorize(res, deferred.resolve, deferred.reject);\n return;\n }\n clientConfig.rendererComponent\n .afterOnAuthorize(res, deferred.resolve, deferred.reject, actions);\n customerData.set('paypal-funding-source', '');\n }).fail(function (jqXHR, textStatus, err) {\n clientConfig.rendererComponent.catchOnAuthorize(err, deferred.resolve, deferred.reject);\n customerData.set('paypal-funding-source', '');\n });\n });\n }).promise();\n }\n\n return function (clientConfig, element) {\n paypalSdk(clientConfig.sdkUrl, clientConfig.dataAttributes).done(function (paypal) {\n paypal.Buttons({\n style: clientConfig.styles,\n\n /**\n * onInit is called when the button first renders\n * @param {Object} data\n * @param {Object} actions\n */\n onInit: function (data, actions) {\n clientConfig.rendererComponent.validate(actions);\n },\n\n /**\n * Triggers beforePayment action on PayPal buttons\n * @returns {Object} jQuery promise\n */\n createOrder: function () {\n return performCreateOrder(clientConfig);\n },\n\n /**\n * Triggers beforeOnAuthorize action on PayPal buttons\n * @param {Object} data\n * @param {Object} actions\n */\n onApprove: function (data, actions) {\n performOnApprove(clientConfig, data, actions);\n },\n\n /**\n * Execute logic on Paypal button click\n */\n onClick: function (data) {\n customerData.set('paypal-funding-source', data.fundingSource);\n clientConfig.rendererComponent.validate();\n clientConfig.rendererComponent.onClick();\n },\n\n /**\n * Process cancel action\n * @param {Object} data\n * @param {Object} actions\n */\n onCancel: function (data, actions) {\n clientConfig.rendererComponent.onCancel(data, actions);\n },\n\n /**\n * Process errors\n *\n * @param {Error} err\n */\n onError: function (err) {\n clientConfig.rendererComponent.onError(err);\n }\n }).render(element);\n });\n };\n});\n","Magento_Paypal/js/in-context/paypal-sdk.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'jquery'\n], function ($) {\n 'use strict';\n\n var dfd = $.Deferred();\n\n /**\n * Loads the PayPal SDK object\n * @param {String} paypalUrl - the url of the PayPal SDK\n * @param {Array} dataAttributes - Array of the Attributes for PayPal SDK Script tag\n */\n return function loadPaypalScript(paypalUrl, dataAttributes) {\n //configuration for loaded PayPal script\n require.config({\n paths: {\n paypalSdk: paypalUrl\n },\n shim: {\n paypalSdk: {\n exports: 'paypal'\n }\n },\n attributes: {\n 'paypalSdk': dataAttributes\n },\n\n /**\n * Add attributes under Paypal SDK Script tag\n */\n onNodeCreated: function (node, config, name) {\n if (config.attributes && config.attributes[name]) {\n $.each(dataAttributes, function (index, elem) {\n node.setAttribute(index, elem);\n });\n }\n }\n });\n\n if (dfd.state() !== 'resolved') {\n require(['paypalSdk'], function (paypalObject) {\n dfd.resolve(paypalObject);\n });\n }\n\n return dfd.promise();\n };\n});\n","Magento_Paypal/js/in-context/product-express-checkout.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'underscore',\n 'jquery',\n 'uiComponent',\n 'Magento_Paypal/js/in-context/express-checkout-wrapper',\n 'Magento_Customer/js/customer-data'\n], function (_, $, Component, Wrapper, customerData) {\n 'use strict';\n\n return Component.extend(Wrapper).extend({\n defaults: {\n productFormSelector: '#product_addtocart_form',\n declinePayment: false,\n formInvalid: false,\n productAddedToCart: false\n },\n\n /** @inheritdoc */\n initialize: function (config, element) {\n var cart = customerData.get('cart'),\n customer = customerData.get('customer'),\n isGuestCheckoutAllowed;\n\n this._super();\n\n isGuestCheckoutAllowed = cart().isGuestCheckoutAllowed;\n\n if (typeof isGuestCheckoutAllowed === 'undefined') {\n isGuestCheckoutAllowed = config.clientConfig.isGuestCheckoutAllowed;\n }\n\n if (config.clientConfig.isVisibleOnProductPage) {\n this.renderPayPalButtons(element);\n }\n\n this.declinePayment = !customer().firstname && !isGuestCheckoutAllowed;\n\n return this;\n },\n\n /** @inheritdoc */\n onClick: function () {\n var $form = $(this.productFormSelector);\n\n if (!this.declinePayment && !this.productAddedToCart) {\n $form.trigger('submit');\n this.formInvalid = !$form.validation('isValid');\n this.productAddedToCart = true;\n }\n },\n\n /** @inheritdoc */\n beforePayment: function (resolve, reject) {\n var promise = $.Deferred();\n\n if (this.declinePayment) {\n this.addError(this.signInMessage, 'warning');\n reject();\n } else if (this.formInvalid) {\n reject();\n } else {\n $(document).on('ajax:addToCart', function (e, data) {\n if (_.isEmpty(data.response)) {\n return promise.resolve();\n }\n\n return reject();\n });\n $(document).on('ajax:addToCart:error', reject);\n }\n\n return promise;\n },\n\n /**\n * After payment execute\n *\n * @param {Object} res\n * @param {Function} resolve\n * @param {Function} reject\n *\n * @return {*}\n */\n afterPayment: function (res, resolve, reject) {\n if (res.success) {\n return resolve(res.token);\n }\n\n this.addAlert(res['error_message']);\n\n return reject(new Error(res['error_message']));\n },\n\n /** @inheritdoc */\n prepareClientConfig: function () {\n this._super();\n this.clientConfig.quoteId = '';\n this.clientConfig.customerId = '';\n\n return this.clientConfig;\n },\n\n /** @inheritdoc */\n onError: function (err) {\n this.productAddedToCart = false;\n this._super(err);\n },\n\n /** @inheritdoc */\n onCancel: function (data, actions) {\n this.productAddedToCart = false;\n this._super(data, actions);\n },\n\n /** @inheritdoc */\n afterOnAuthorize: function (res, resolve, reject, actions) {\n this.productAddedToCart = false;\n\n return this._super(res, resolve, reject, actions);\n }\n });\n});\n","Magento_Paypal/js/in-context/billing-agreement.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'jquery',\n 'Magento_Ui/js/modal/confirm',\n 'Magento_Customer/js/customer-data'\n], function ($, confirm, customerData) {\n 'use strict';\n\n $.widget('mage.billingAgreement', {\n options: {\n invalidateOnLoad: false,\n cancelButtonSelector: '.block-billing-agreements-view button.cancel',\n cancelMessage: '',\n cancelUrl: ''\n },\n\n /**\n * Initialize billing agreements events\n * @private\n */\n _create: function () {\n var self = this;\n\n if (this.options.invalidateOnLoad) {\n this.invalidate();\n }\n $(this.options.cancelButtonSelector).on('click', function () {\n confirm({\n content: self.options.cancelMessage,\n actions: {\n /**\n * 'Confirm' action handler.\n */\n confirm: function () {\n self.invalidate();\n window.location.href = self.options.cancelUrl;\n }\n }\n });\n\n return false;\n });\n },\n\n /**\n * clear paypal billing agreement customer data\n * @returns void\n */\n invalidate: function () {\n customerData.invalidate(['paypal-billing-agreement']);\n }\n });\n\n return $.mage.billingAgreement;\n});\n","Magento_Paypal/js/view/paylater.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'ko',\n 'uiElement',\n 'uiLayout',\n 'Magento_Paypal/js/in-context/paypal-sdk',\n 'domReady!'\n], function (\n $,\n ko,\n Component,\n layout,\n paypalSdk\n) {\n 'use strict';\n\n return Component.extend({\n\n defaults: {\n template: 'Magento_Paypal/paylater',\n sdkUrl: '',\n attributes: {\n class: 'pay-later-message'\n },\n dataAttributes: {},\n refreshSelector: '',\n displayAmount: false,\n amountComponentConfig: {\n name: '${ $.name }.amountProvider',\n component: ''\n }\n },\n paypal: null,\n amount: null,\n\n /**\n * Initialize\n *\n * @returns {*}\n */\n initialize: function () {\n this._super()\n .observe(['amount']);\n\n if (this.displayAmount) {\n layout([this.amountComponentConfig]);\n }\n\n if (this.sdkUrl !== '') {\n this.loadPayPalSdk(this.sdkUrl, this.dataAttributes)\n .then(this._setPayPalObject.bind(this));\n }\n\n if (this.refreshSelector) {\n $(this.refreshSelector).on('click', this._refreshMessages.bind(this));\n }\n\n return this;\n },\n\n /**\n * Get attribute value from configuration\n *\n * @param {String} attributeName\n * @returns {*|null}\n */\n getAttribute: function (attributeName) {\n return typeof this.attributes[attributeName] !== 'undefined' ?\n this.attributes[attributeName] : null;\n },\n\n /**\n * Load PP SDK with preconfigured options\n *\n * @param {String} sdkUrl - the url of the PayPal SDK\n * @param {Array} dataAttributes - Array of the Attributes for PayPal SDK Script tag\n */\n loadPayPalSdk: function (sdkUrl, dataAttributes) {\n return paypalSdk(sdkUrl, dataAttributes);\n },\n\n /**\n * Set reference to paypal Sdk object\n *\n * @param {Object} paypal\n * @private\n */\n _setPayPalObject: function (paypal) {\n this.paypal = paypal;\n },\n\n /**\n * Render messages\n *\n * @private\n */\n _refreshMessages: function () {\n if (this.paypal) {\n this.paypal.Messages.render();\n }\n }\n });\n});\n","Magento_Paypal/js/view/payment/paypal-payments.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'uiComponent',\n 'Magento_Checkout/js/model/payment/renderer-list'\n], function (Component, rendererList) {\n 'use strict';\n\n var isContextCheckout = window.checkoutConfig.payment.paypalExpress.isContextCheckout,\n paypalExpress = 'Magento_Paypal/js/view/payment/method-renderer' +\n (isContextCheckout ? '/in-context/checkout-express' : '/paypal-express');\n\n rendererList.push(\n {\n type: 'paypal_express',\n component: paypalExpress,\n config: window.checkoutConfig.payment.paypalExpress.inContextConfig\n },\n {\n type: 'payflow_express',\n component: 'Magento_Paypal/js/view/payment/method-renderer/payflow-express'\n },\n {\n type: 'payflow_express_bml',\n component: 'Magento_Paypal/js/view/payment/method-renderer/payflow-express-bml'\n },\n {\n type: 'payflowpro',\n component: 'Magento_Paypal/js/view/payment/method-renderer/payflowpro-method'\n },\n {\n type: 'payflow_link',\n component: 'Magento_Paypal/js/view/payment/method-renderer/iframe-methods'\n },\n {\n type: 'payflow_advanced',\n component: 'Magento_Paypal/js/view/payment/method-renderer/iframe-methods'\n },\n {\n type: 'hosted_pro',\n component: 'Magento_Paypal/js/view/payment/method-renderer/iframe-methods'\n },\n {\n type: 'paypal_billing_agreement',\n component: 'Magento_Paypal/js/view/payment/method-renderer/paypal-billing-agreement'\n }\n );\n\n /**\n * Add view logic here if needed\n **/\n return Component.extend({});\n});\n","Magento_Paypal/js/view/payment/method-renderer/payflowpro-method.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'Magento_Payment/js/view/payment/iframe',\n 'Magento_Checkout/js/model/payment/additional-validators',\n 'Magento_Checkout/js/action/set-payment-information',\n 'Magento_Checkout/js/model/full-screen-loader',\n 'Magento_Vault/js/view/payment/vault-enabler'\n], function ($, Component, additionalValidators, setPaymentInformationAction, fullScreenLoader, VaultEnabler) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Paypal/payment/payflowpro-form'\n },\n placeOrderHandler: null,\n validateHandler: null,\n\n /**\n * @returns {exports.initialize}\n */\n initialize: function () {\n this._super();\n this.vaultEnabler = new VaultEnabler();\n this.vaultEnabler.setPaymentCode(this.getVaultCode());\n\n return this;\n },\n\n /**\n * @param {Function} handler\n */\n setPlaceOrderHandler: function (handler) {\n this.placeOrderHandler = handler;\n },\n\n /**\n * @param {Function} handler\n */\n setValidateHandler: function (handler) {\n this.validateHandler = handler;\n },\n\n /**\n * @returns {Object}\n */\n context: function () {\n return this;\n },\n\n /**\n * @returns {Boolean}\n */\n isShowLegend: function () {\n return true;\n },\n\n /**\n * @returns {String}\n */\n getCode: function () {\n return 'payflowpro';\n },\n\n /**\n * @returns {Boolean}\n */\n isActive: function () {\n return true;\n },\n\n /**\n * @override\n */\n placeOrder: function () {\n var self = this;\n\n if (this.validateHandler() &&\n additionalValidators.validate() &&\n this.isPlaceOrderActionAllowed() === true\n ) {\n this.isPlaceOrderActionAllowed(false);\n fullScreenLoader.startLoader();\n $.when(\n setPaymentInformationAction(this.messageContainer, self.getData())\n ).done(\n function () {\n self.placeOrderHandler().fail(\n function () {\n fullScreenLoader.stopLoader();\n }\n );\n }\n ).always(\n function () {\n self.isPlaceOrderActionAllowed(true);\n fullScreenLoader.stopLoader();\n }\n );\n }\n },\n\n /**\n * @returns {Object}\n */\n getData: function () {\n var data = {\n 'method': this.getCode(),\n 'additional_data': {\n 'cc_type': this.creditCardType(),\n 'cc_exp_year': this.creditCardExpYear(),\n 'cc_exp_month': this.creditCardExpMonth(),\n 'cc_last_4': this.creditCardNumber().substr(-4)\n }\n };\n\n this.vaultEnabler.visitAdditionalData(data);\n\n return data;\n },\n\n /**\n * @returns {Bool}\n */\n isVaultEnabled: function () {\n return this.vaultEnabler.isVaultEnabled();\n },\n\n /**\n * @returns {String}\n */\n getVaultCode: function () {\n return 'payflowpro_cc_vault';\n }\n });\n});\n","Magento_Paypal/js/view/payment/method-renderer/paypal-express.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract'\n], function (Component) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Paypal/payment/paypal-express'\n }\n });\n});\n","Magento_Paypal/js/view/payment/method-renderer/payflow-express.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract'\n], function (Component) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Paypal/payment/payflow-express'\n }\n });\n});\n","Magento_Paypal/js/view/payment/method-renderer/payflow-express-bml.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract'\n], function (Component) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Paypal/payment/payflow-express-bml'\n }\n });\n});\n","Magento_Paypal/js/view/payment/method-renderer/iframe-methods.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'Magento_Checkout/js/view/payment/default',\n 'Magento_Paypal/js/model/iframe',\n 'Magento_Checkout/js/model/full-screen-loader'\n], function (Component, iframe, fullScreenLoader) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Paypal/payment/iframe-methods',\n paymentReady: false\n },\n redirectAfterPlaceOrder: false,\n isInAction: iframe.isInAction,\n\n /**\n * @return {exports}\n */\n initObservable: function () {\n this._super()\n .observe('paymentReady');\n\n return this;\n },\n\n /**\n * @return {*}\n */\n isPaymentReady: function () {\n return this.paymentReady();\n },\n\n /**\n * Get action url for payment method iframe.\n * @returns {String}\n */\n getActionUrl: function () {\n return this.isInAction() ? window.checkoutConfig.payment.paypalIframe.actionUrl[this.getCode()] : '';\n },\n\n /**\n * Places order in pending payment status.\n */\n placePendingPaymentOrder: function () {\n if (this.placeOrder()) {\n fullScreenLoader.startLoader();\n this.isInAction(true);\n // capture all click events\n document.addEventListener('click', iframe.stopEventPropagation, true);\n }\n },\n\n /**\n * @return {*}\n */\n getPlaceOrderDeferredObject: function () {\n var self = this;\n\n return this._super().fail(function () {\n fullScreenLoader.stopLoader();\n self.isInAction(false);\n document.removeEventListener('click', iframe.stopEventPropagation, true);\n });\n },\n\n /**\n * After place order callback\n */\n afterPlaceOrder: function () {\n if (this.iframeIsLoaded) {\n document.getElementById(this.getCode() + '-iframe')\n .contentWindow.location.reload();\n this.paymentReady(false);\n }\n\n this.paymentReady(true);\n this.iframeIsLoaded = true;\n this.isPlaceOrderActionAllowed(true);\n fullScreenLoader.stopLoader();\n },\n\n /**\n * Hide loader when iframe is fully loaded.\n */\n iframeLoaded: function () {\n fullScreenLoader.stopLoader();\n }\n });\n});\n","Magento_Paypal/js/view/payment/method-renderer/paypal-billing-agreement.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'Magento_Checkout/js/view/payment/default',\n 'mage/validation'\n], function ($, Component) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Paypal/payment/paypal_billing_agreement-form',\n selectedBillingAgreement: ''\n },\n\n /** @inheritdoc */\n initObservable: function () {\n this._super()\n .observe('selectedBillingAgreement');\n\n return this;\n },\n\n /**\n * @return {*}\n */\n getTransportName: function () {\n return window.checkoutConfig.payment.paypalBillingAgreement.transportName;\n },\n\n /**\n * @return {*}\n */\n getBillingAgreements: function () {\n return window.checkoutConfig.payment.paypalBillingAgreement.agreements;\n },\n\n /**\n * @return {Object}\n */\n getData: function () {\n var additionalData = null;\n\n if (this.getTransportName()) {\n additionalData = {};\n additionalData[this.getTransportName()] = this.selectedBillingAgreement();\n }\n\n return {\n 'method': this.item.method,\n 'additional_data': additionalData\n };\n },\n\n /**\n * @return {jQuery}\n */\n validate: function () {\n var form = '#billing-agreement-form';\n\n return $(form).validation() && $(form).validation('isValid');\n }\n });\n});\n","Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'Magento_Checkout/js/view/payment/default',\n 'Magento_Paypal/js/action/set-payment-method',\n 'Magento_Checkout/js/model/payment/additional-validators',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Customer/js/customer-data'\n], function ($, Component, setPaymentMethodAction, additionalValidators, quote, customerData) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Paypal/payment/payflow-express-bml',\n billingAgreement: ''\n },\n\n /** Init observable variables */\n initObservable: function () {\n this._super()\n .observe('billingAgreement');\n\n return this;\n },\n\n /** Open window with */\n showAcceptanceWindow: function (data, event) {\n window.open(\n $(event.currentTarget).attr('href'),\n 'olcwhatispaypal',\n 'toolbar=no, location=no,' +\n ' directories=no, status=no,' +\n ' menubar=no, scrollbars=yes,' +\n ' resizable=yes, ,left=0,' +\n ' top=0, width=400, height=350'\n );\n\n return false;\n },\n\n /** Returns payment acceptance mark link path */\n getPaymentAcceptanceMarkHref: function () {\n return window.checkoutConfig.payment.paypalExpress.paymentAcceptanceMarkHref;\n },\n\n /** Returns payment acceptance mark image path */\n getPaymentAcceptanceMarkSrc: function () {\n return window.checkoutConfig.payment.paypalExpress.paymentAcceptanceMarkSrc;\n },\n\n /** Returns billing agreement data */\n getBillingAgreementCode: function () {\n return window.checkoutConfig.payment.paypalExpress.billingAgreementCode[this.item.method];\n },\n\n /** Returns payment information data */\n getData: function () {\n var parent = this._super(),\n additionalData = null;\n\n if (this.getBillingAgreementCode()) {\n additionalData = {};\n additionalData[this.getBillingAgreementCode()] = this.billingAgreement();\n }\n\n return $.extend(true, parent, {\n 'additional_data': additionalData\n });\n },\n\n /** Redirect to paypal */\n continueToPayPal: function () {\n if (additionalValidators.validate()) {\n //update payment method information if additional data was changed\n setPaymentMethodAction(this.messageContainer).done(\n function () {\n customerData.invalidate(['cart']);\n $.mage.redirect(\n window.checkoutConfig.payment.paypalExpress.redirectUrl[quote.paymentMethod().method]\n );\n }\n );\n\n return false;\n }\n }\n });\n});\n","Magento_Paypal/js/view/payment/method-renderer/payflowpro/vault.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'Magento_Vault/js/view/payment/method-renderer/vault'\n], function (VaultComponent) {\n 'use strict';\n\n return VaultComponent.extend({\n defaults: {\n template: 'Magento_Vault/payment/form'\n },\n\n /**\n * @returns {String}\n */\n getToken: function () {\n return this.publicHash;\n },\n\n /**\n * Get last 4 digits of card\n * @returns {String}\n */\n getMaskedCard: function () {\n return this.details['cc_last_4'];\n },\n\n /**\n * Get expiration date\n * @returns {String}\n */\n getExpirationDate: function () {\n return this.details['cc_exp_month'] + '/' + this.details['cc_exp_year'];\n },\n\n /**\n * Get card type\n * @returns {String}\n */\n getCardType: function () {\n return this.details['cc_type'];\n }\n });\n});\n","Magento_Paypal/js/view/payment/method-renderer/in-context/checkout-express.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'jquery',\n 'Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract',\n 'Magento_Paypal/js/in-context/express-checkout-wrapper',\n 'Magento_Paypal/js/action/set-payment-method',\n 'Magento_Checkout/js/model/payment/additional-validators',\n 'Magento_Ui/js/model/messageList',\n 'Magento_Ui/js/lib/view/utils/async'\n], function ($, Component, Wrapper, setPaymentMethod, additionalValidators, messageList) {\n 'use strict';\n\n return Component.extend(Wrapper).extend({\n defaults: {\n template: 'Magento_Paypal/payment/paypal-express-in-context',\n validationElements: 'input'\n },\n\n /**\n * Listens element on change and validate it.\n *\n * @param {HTMLElement} context\n */\n initListeners: function (context) {\n $.async(this.validationElements, context, function (element) {\n $(element).on('change', function () {\n this.validate();\n }.bind(this));\n }.bind(this));\n },\n\n /**\n * Validates Smart Buttons\n */\n validate: function () {\n this._super();\n\n if (this.actions) {\n additionalValidators.validate(true) ? this.actions.enable() : this.actions.disable();\n }\n },\n\n /** @inheritdoc */\n beforePayment: function (resolve, reject) {\n var promise = $.Deferred();\n\n setPaymentMethod(this.messageContainer).done(function () {\n return promise.resolve();\n }).fail(function (response) {\n var error;\n\n try {\n error = JSON.parse(response.responseText);\n } catch (exception) {\n error = this.paymentActionError;\n }\n\n this.addError(error);\n\n return reject(new Error(error));\n }.bind(this));\n\n return promise;\n },\n\n /**\n * Populate client config with all required data\n *\n * @return {Object}\n */\n prepareClientConfig: function () {\n this._super();\n this.clientConfig.quoteId = window.checkoutConfig.quoteData['entity_id'];\n this.clientConfig.customerId = window.customerData.id;\n this.clientConfig.button = 0;\n\n return this.clientConfig;\n },\n\n /**\n * Adding logic to be triggered onClick action for smart buttons component\n */\n onClick: function () {\n additionalValidators.validate();\n },\n\n /**\n * Adds error message\n *\n * @param {String} message\n */\n addError: function (message) {\n messageList.addErrorMessage({\n message: message\n });\n },\n\n /**\n * After payment execute\n *\n * @param {Object} res\n * @param {Function} resolve\n * @param {Function} reject\n *\n * @return {*}\n */\n afterPayment: function (res, resolve, reject) {\n if (res.success) {\n return resolve(res.token);\n }\n\n this.addError(res['error_message']);\n\n return reject(new Error(res['error_message']));\n },\n\n /**\n * After onAuthorize execute\n *\n * @param {Object} res\n * @param {Function} resolve\n * @param {Function} reject\n * @param {Object} actions\n *\n * @return {*}\n */\n afterOnAuthorize: function (res, resolve, reject, actions) {\n if (res.success) {\n resolve();\n\n return actions.redirect(res.redirectUrl);\n }\n\n this.addError(res['error_message']);\n\n return reject(new Error(res['error_message']));\n }\n });\n});\n","Magento_Paypal/js/view/amountProviders/checkout.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'ko',\n 'uiElement',\n 'uiRegistry',\n 'Magento_Checkout/js/model/quote',\n 'domReady!'\n], function (\n $,\n ko,\n Component,\n registry,\n quote\n) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n amount: null\n },\n\n /**\n * Initialize\n *\n * @returns {*}\n */\n initialize: function () {\n this._super();\n\n this.updateAmount();\n\n return this;\n },\n\n /**\n * Update amount\n */\n updateAmount: function () {\n var payLater = registry.get(this.parentName);\n\n quote.totals.subscribe(function (newValue) {\n payLater.amount(newValue['base_grand_total']);\n });\n }\n });\n});\n","Magento_Paypal/js/view/amountProviders/product-grouped.js":"/**\n* Copyright \u00a9 Magento, Inc. All rights reserved.\n* See COPYING.txt for license details.\n*/\n\ndefine([\n 'jquery',\n 'uiElement',\n 'uiRegistry',\n 'domReady!'\n], function (\n $,\n Component,\n registry\n) {\n 'use strict';\n\n return Component.extend({\n\n defaults: {\n tableWrapperSelector: '.table-wrapper.grouped',\n priceBoxSelector: '[data-role=\"priceBox\"]',\n qtyFieldSelector: '.input-text.qty',\n amount: null\n },\n priceInfo: {},\n\n /**\n * Initialize\n *\n * @returns {*}\n */\n initialize: function () {\n var self = this;\n\n this._super();\n\n $('tbody tr', this.tableWrapperSelector).each(function (index, element) {\n var priceBox = $(self.priceBoxSelector, element),\n qtyElement = $(self.qtyFieldSelector, element),\n productId = priceBox.data('productId'),\n priceElement = $('#product-price-' + productId);\n\n self.priceInfo[productId] = {\n qty: self._getQty(qtyElement),\n price: priceElement.data('priceAmount')\n };\n });\n\n $(this.qtyFieldSelector).on('change', this._onQtyChange.bind(this));\n\n this._updateAmount();\n\n return this;\n },\n\n /**\n * Get product quantity\n *\n * @param {jQuery.Element} element\n * @private\n */\n _getQty: function (element) {\n var qty = parseFloat(element.val());\n\n return !isNaN(qty) && qty ? qty : 0;\n },\n\n /**\n * Handle changed product quantity\n *\n * @param {jQuery.Event} event\n * @private\n */\n _onQtyChange: function (event) {\n var qtyElement = $(event.target),\n parent = qtyElement.parents('tr'),\n priceBox = $(this.priceBoxSelector, parent),\n productId = priceBox.data('productId');\n\n if (this.priceInfo[productId]) {\n this.priceInfo[productId].qty = this._getQty(qtyElement);\n }\n\n this._updateAmount();\n },\n\n /**\n * Calculate and update amount\n *\n * @private\n */\n _updateAmount: function () {\n var productId,\n amount = 0,\n payLater = registry.get(this.parentName);\n\n for (productId in this.priceInfo) {\n if (this.priceInfo.hasOwnProperty(productId)) {\n amount += this.priceInfo[productId].price * this.priceInfo[productId].qty;\n }\n }\n\n payLater.amount(amount);\n }\n });\n});\n","Magento_Paypal/js/view/amountProviders/product.js":"/**\n* Copyright \u00a9 Magento, Inc. All rights reserved.\n* See COPYING.txt for license details.\n*/\n\ndefine([\n 'jquery',\n 'uiElement',\n 'uiRegistry',\n 'priceBox',\n 'domReady!'\n], function (\n $,\n Component,\n registry\n) {\n 'use strict';\n\n return Component.extend({\n\n defaults: {\n priceBoxSelector: '.price-box',\n qtyFieldSelector: '#product_addtocart_form [name=\"qty\"]',\n amount: null\n },\n qty: 1,\n price: 0,\n priceType: '',\n\n /**\n * Initialize\n *\n * @returns {*}\n */\n initialize: function () {\n var priceBox;\n\n this._super();\n\n priceBox = $(this.priceBoxSelector);\n priceBox.on('priceUpdated', this._onPriceChange.bind(this));\n\n if (priceBox.priceBox('option') &&\n priceBox.priceBox('option').prices &&\n (priceBox.priceBox('option').prices.finalPrice || priceBox.priceBox('option').prices.basePrice)\n ) {\n this.priceType = priceBox.priceBox('option').prices.finalPrice ? 'finalPrice' : 'basePrice';\n this.price = priceBox.priceBox('option').prices[this.priceType].amount;\n }\n\n $(this.qtyFieldSelector).on('change', this._onQtyChange.bind(this));\n\n priceBox.trigger('updatePrice');\n\n return this;\n },\n\n /**\n * Handle changed product qty\n *\n * @param {jQuery.Event} event\n * @private\n */\n _onQtyChange: function (event) {\n var qty = parseFloat($(event.target).val());\n\n this.qty = !isNaN(qty) && qty ? qty : 1;\n this._updateAmount();\n },\n\n /**\n * Handle product price change\n *\n * @param {jQuery.Event} event\n * @param {Object} data\n * @private\n */\n _onPriceChange: function (event, data) {\n this.price = data[this.priceType].amount;\n this._updateAmount();\n },\n\n /**\n * Calculate and update amount\n *\n * @private\n */\n _updateAmount: function () {\n var amount = this.price * this.qty,\n payLater = registry.get(this.parentName);\n\n if (amount !== 0) {\n payLater.amount(amount);\n }\n }\n });\n});\n","Magento_Paypal/js/model/iframe-redirect.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'ko',\n 'Magento_Paypal/js/model/iframe',\n 'Magento_Ui/js/model/messageList'\n],\nfunction (ko, iframe, messageList) {\n 'use strict';\n\n return function (cartUrl, errorMessage, goToSuccessPage, successUrl) {\n if (this === window.self) {\n window.location = cartUrl;\n }\n\n if (!!errorMessage.message) { //eslint-disable-line no-extra-boolean-cast\n document.removeEventListener('click', iframe.stopEventPropagation, true);\n iframe.isInAction(false);\n messageList.addErrorMessage(errorMessage);\n } else if (!!goToSuccessPage) { //eslint-disable-line no-extra-boolean-cast\n window.location = successUrl;\n } else {\n window.location = cartUrl;\n }\n };\n});\n","Magento_Paypal/js/model/iframe.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine(['ko'], function (ko) {\n 'use strict';\n\n var isInAction = ko.observable(false);\n\n return {\n isInAction: isInAction,\n\n /**\n * @param {jQuery.Event} event\n */\n stopEventPropagation: function (event) {\n event.stopImmediatePropagation();\n event.preventDefault();\n }\n };\n});\n","Magento_Reports/js/recently-viewed.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\ndefine([\n 'jquery',\n 'jquery-ui-modules/widget'\n], function ($) {\n 'use strict';\n\n $.widget('mage.recentlyViewedProducts', {\n options: {\n localStorageKey: 'recently-viewed-products',\n productBlock: '#widget_viewed_item',\n viewedContainer: 'ol'\n },\n\n /**\n * Bind events to the appropriate handlers.\n * @private\n */\n _create: function () {\n var productHtml = $(this.options.productBlock).html(),\n productSku = $(this.options.productBlock).data('sku'),\n products = JSON.parse(window.localStorage.getItem(this.options.localStorageKey)),\n productsLength, maximum, showed, index;\n\n if (products) {\n productsLength = products.sku.length;\n maximum = $(this.element).data('count');\n showed = 0;\n\n for (index = 0; index <= productsLength; index++) {\n if (products.sku[index] == productSku || showed >= maximum) { //eslint-disable-line\n products.sku.splice(index, 1);\n products.html.splice(index, 1);\n } else {\n $(this.element).find(this.options.viewedContainer).append(products.html[index]);\n $(this.element).show();\n showed++;\n }\n }\n $(this.element).find(this.options.productBlock).show();\n } else {\n products = {};\n products.sku = [];\n products.html = [];\n }\n products.sku.unshift(productSku);\n products.html.unshift(productHtml);\n window.localStorage.setItem(this.options.localStorageKey, JSON.stringify(products));\n }\n });\n\n return $.mage.recentlyViewedProducts;\n});\n","Magento_GoogleGtag/js/google-adwords.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n/* jscs:disable */\n/* eslint-disable */\ndefine([\n 'jquery'\n], function ($) {\n 'use strict';\n\n /**\n * @param {Object} config\n */\n return function (config) {\n if (!window.gtag) {\n // Inject Global Site Tag\n var gtagScript = document.createElement('script');\n gtagScript.type = 'text/javascript';\n gtagScript.async = true;\n gtagScript.src = config.gtagSiteSrc;\n document.head.appendChild(gtagScript);\n\n window.dataLayer = window.dataLayer || [];\n\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n gtag('set', 'developer_id.dYjhlMD', true);\n if (config.conversionLabel) {\n gtag(\n 'event',\n 'conversion',\n {'send_to': config.conversionId + '/'\n + config.conversionLabel}\n );\n }\n } else {\n gtag('config', config.conversionId);\n }\n }\n});\n","Magento_GoogleGtag/js/google-analytics.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n/* jscs:disable */\n/* eslint-disable */\ndefine([\n 'jquery',\n 'mage/cookies'\n], function ($) {\n 'use strict';\n\n /**\n * @param {Object} config\n */\n return function (config) {\n var allowServices = false,\n allowedCookies,\n allowedWebsites,\n measurementId;\n\n if (config.isCookieRestrictionModeEnabled) {\n allowedCookies = $.mage.cookies.get(config.cookieName);\n\n if (allowedCookies !== null) {\n allowedWebsites = JSON.parse(allowedCookies);\n\n if (allowedWebsites[config.currentWebsite] === 1) {\n allowServices = true;\n }\n }\n } else {\n allowServices = true;\n }\n\n if (allowServices) {\n /* Global site tag (gtag.js) - Google Analytics */\n measurementId = config.pageTrackingData.measurementId;\n if (window.gtag) {\n gtag('config', measurementId, { 'anonymize_ip': true });\n // Purchase Event\n if (config.ordersTrackingData.hasOwnProperty('currency')) {\n var purchaseObject = config.ordersTrackingData.orders[0];\n purchaseObject['items'] = config.ordersTrackingData.products;\n gtag('event', 'purchase', purchaseObject);\n }\n } else {\n (function(d,s,u){\n var gtagScript = d.createElement(s);\n gtagScript.type = 'text/javascript';\n gtagScript.async = true;\n gtagScript.src = u;\n d.head.insertBefore(gtagScript, d.head.children[0]);\n })(document, 'script', 'https://www.googletagmanager.com/gtag/js?id=' + measurementId);\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n gtag('set', 'developer_id.dYjhlMD', true);\n gtag('config', measurementId, { 'anonymize_ip': true });\n // Purchase Event\n if (config.ordersTrackingData.hasOwnProperty('currency')) {\n var purchaseObject = config.ordersTrackingData.orders[0];\n purchaseObject['items'] = config.ordersTrackingData.products;\n gtag('event', 'purchase', purchaseObject);\n }\n }\n }\n }\n});\n","Magento_Shipping/js/view/checkout/shipping/shipping-policy.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'uiComponent',\n 'Magento_Shipping/js/model/config'\n\n], function (Component, config) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Shipping/checkout/shipping/shipping-policy'\n },\n config: config()\n });\n});\n","Magento_Shipping/js/model/config.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([], function () {\n 'use strict';\n\n return function () {\n return window.checkoutConfig.shippingPolicy;\n };\n});\n","Magento_PaymentServicesPaypal/js/order-review.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'uiComponent',\n 'Magento_Customer/js/customer-data'\n], function ($, Component, customerData) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n element: null,\n placeOrderButtonSelector: '#review-button',\n shippingMethodFormSelector: '#shipping-method-form',\n shippingMethodInputSelector: '#shipping-method',\n updateContainerSelector: '#details-reload',\n waitLoadingContainer: '#review-please-wait',\n orderFormSelector: '#order-review-form',\n editShoppingCartSelector: '.magento-payments-review-items .edit',\n updateShippingMethodUrl: null,\n placeOrderUrl: null,\n canEditShippingMethod: false,\n isVirtual: false\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n this._super();\n this.element = element;\n\n $(this.placeOrderButtonSelector).on('click', this.submitOrder.bind(this));\n $(this.editShoppingCartSelector).on('click', this.invalidateCustomerData.bind(this));\n\n if (!this.isVirtual && this.canEditShippingMethod) {\n $(this.shippingMethodInputSelector).on('change', this.selectShippingMethod.bind(this));\n this.setPlaceOrderButtonActive(!!$(this.shippingMethodInputSelector).val());\n }\n },\n\n invalidateCustomerData: function () {\n customerData.invalidate(['cart']);\n },\n\n /**\n * Before request start\n */\n beforeRequestStart: function () {\n $(this.waitLoadingContainer).show();\n },\n\n /**\n * On request complete\n */\n onRequestComplete: function () {\n $(this.waitLoadingContainer).hide();\n },\n\n /**\n * Submit order\n */\n submitOrder: function () {\n if (this.validateForm()) {\n this.beforeRequestStart();\n $(this.orderFormSelector).trigger('submit');\n this.setPlaceOrderButtonActive(false);\n }\n },\n\n /**\n * Validate form\n */\n validateForm: function () {\n return $(this.element).validation().valid();\n },\n\n /**\n * Enable/disable order button\n *\n * @param {Boolean} isActive\n */\n setPlaceOrderButtonActive: function (isActive) {\n $(this.placeOrderButtonSelector).prop('disabled', !isActive).toggleClass('no-checkout', !isActive);\n },\n\n /**\n * Select shipping method\n */\n selectShippingMethod: function () {\n var shippingMethod,\n formData,\n responseCallback;\n\n if ($(this.waitLoadingContainer).is(':visible')) {\n return false;\n }\n shippingMethod = $(this.shippingMethodInputSelector).val();\n shippingMethod = shippingMethod.trim();\n this.setPlaceOrderButtonActive(false);\n\n if (shippingMethod) {\n formData = $(this.shippingMethodFormSelector).serialize() + '&isAjax=true';\n\n /**\n * @param {Object} response\n */\n responseCallback = function (response) {\n if (typeof response.redirectUrl == 'undefined') {\n $(this.updateContainerSelector).html(response.html);\n } else {\n window.location = response.redirectUrl;\n }\n this.setPlaceOrderButtonActive(true);\n this.onRequestComplete();\n };\n $.ajax({\n url: this.updateShippingMethodUrl,\n type: 'post',\n context: this,\n beforeSend: this.beforeRequestStart,\n data: formData,\n success: responseCallback\n });\n }\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/product/bundle-product-data-provider.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'underscore',\n 'Magento_PaymentServicesPaypal/js/view/product/product-data-provider'\n], function ($, _, Component) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n priceBoxContextSelector: '#bundleSummary',\n slideSelector: '#bundle-slide'\n },\n\n /** @inheritdoc */\n initialize: function () {\n this._super();\n\n // Need to track bundle product slide to trigger amount update to make message visible.\n $(this.slideSelector).on('click', function () {\n setTimeout(function () {\n this.updateAmount(this.getAmount());\n }.bind(this), 300);\n }.bind(this));\n this.updateAmount(this.getAmount());\n\n return this;\n },\n\n /**\n * Checks if product is grouped type.\n *\n * @return {Boolean}\n */\n isBundleProduct: function () {\n return !!$(this.constructor.defaults.priceBoxContextSelector).length;\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/product/gift-card-product-data-provider.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'underscore',\n 'Magento_PaymentServicesPaypal/js/view/product/product-data-provider'\n], function ($, _, Component) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n priceBoxContextSelector: '.giftcard-amount',\n priceBoxSelector: '#giftcard-amount, #giftcard-amount-input'\n },\n\n /** @inheritdoc */\n initialize: function () {\n this._super();\n this.price = $(this.priceBoxSelector, this.priceBoxContextSelector).val();\n\n return this;\n },\n\n /**\n * Subscribe for price change.\n */\n priceSubscribe: function () {\n $(this.priceBoxSelector, this.priceBoxContextSelector).on('change', function (event) {\n this.price = event.target.value;\n this.updateAmount(this.getAmount());\n }.bind(this));\n },\n\n /**\n * Checks if product is grouped type.\n *\n * @return {Boolean}\n */\n isProductGiftCard: function () {\n return !!$(this.constructor.defaults.priceBoxContextSelector).length;\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/product/grouped-product-data-provider.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine(['jquery', 'underscore', 'uiClass'], function ($, _, Component) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n tableWrapperSelector: '.table-wrapper.grouped',\n qtyFieldSelector: '.input-text.qty',\n priceBoxSelector: '[data-role=\"priceBox\"]',\n priceInfo: {}\n },\n\n /**\n * @inheritdoc\n */\n initialize: function () {\n this._super();\n $('tbody tr', this.tableWrapperSelector).each(function (index, element) {\n var priceBox = $(this.priceBoxSelector, element),\n qtyElement = $(this.qtyFieldSelector, element),\n productId = priceBox.data('productId'),\n priceElement = $('#product-price-' + productId);\n\n this.priceInfo[productId] = {\n qty: this.getQuantity(qtyElement),\n price: priceElement.data('priceAmount')\n };\n }.bind(this));\n this.quantitySubscribe();\n\n return this;\n },\n\n /**\n * Subscribe for quantity changes.\n */\n quantitySubscribe: function () {\n $(this.qtyFieldSelector).on('change', function (event) {\n var qtyElement = $(event.target),\n parent = qtyElement.parents('tr'),\n priceBox = $(this.priceBoxSelector, parent),\n productId = priceBox.data('productId');\n\n if (this.priceInfo[productId]) {\n this.priceInfo[productId].qty = this.getQuantity(qtyElement);\n }\n\n this.updateAmount(this.getAmount());\n }.bind(this));\n },\n\n /**\n * Get product amount.\n *\n * @return {Number}\n */\n getAmount: function () {\n var amount = 0;\n\n _.each(this.priceInfo, function (info) {\n amount += info.price * info.qty;\n });\n\n return amount;\n },\n\n /**\n * Get product quantity.\n *\n * @param {HTMLElement} element\n * @return {Number}\n */\n getQuantity: function (element) {\n var qty = parseFloat(element.val());\n\n return !isNaN(qty) && qty ? qty : 0;\n },\n\n /**\n * Checks if product is grouped type.\n *\n * @return {Boolean}\n */\n isProductGrouped: function () {\n return !!$(this.constructor.defaults.tableWrapperSelector).length;\n },\n\n /**\n * Subscribe for price change.\n */\n priceSubscribe: function () {\n },\n\n /**\n * Trigger price update.\n */\n updatePrice: function () {\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/product/product-data-provider.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine(['jquery', 'uiClass', 'priceBox'], function ($, Component) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n qtyFieldSelector: '#qty',\n priceBoxSelector: '.price-box',\n priceBoxContextSelector: '.product-info-main',\n finalPriceSelector: '[data-price-type=\"finalPrice\"]',\n price: 0,\n qty: 0\n },\n\n /** @inheritdoc */\n initialize: function () {\n this._super();\n this.price = $(this.finalPriceSelector, this.priceBoxContextSelector).attr('data-price-amount');\n this.qty = $(this.qtyFieldSelector).val();\n this.quantitySubscribe();\n this.priceSubscribe();\n\n return this;\n },\n\n /**\n * Subscribe for quantity changes.\n */\n quantitySubscribe: function () {\n $(this.qtyFieldSelector).on('change', function () {\n this.qty = $(this.qtyFieldSelector).val();\n this.updateAmount(this.getAmount());\n }.bind(this));\n },\n\n /**\n * Subscribe for price change.\n */\n priceSubscribe: function () {\n $(this.priceBoxSelector, this.priceBoxContextSelector).on('updatePrice', function (event) {\n var prices = $(event.target).data('magePriceBox').cache.displayPrices;\n\n this.price = prices.finalPrice.amount;\n this.updateAmount(this.getAmount());\n }.bind(this));\n },\n\n /**\n * Trigger price update.\n */\n updatePrice: function () {\n $(this.priceBoxSelector).trigger('updatePrice');\n },\n\n /**\n * Get product amount.\n *\n * @return {Number}\n */\n getAmount: function () {\n return this.qty * this.price;\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/errors/response-error.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([], function () {\n 'use strict';\n\n /**\n * Error type to handle response errors.\n *\n * @param {String} message\n * @constructor\n */\n function ResponseError(message) {\n this.name = 'ResponseError';\n this.message = message;\n this.stack = new Error().stack;\n }\n\n ResponseError.prototype = new Error;\n\n /**\n * Return a string representation\n *\n * @returns {String}\n */\n ResponseError.prototype.toString = function () {\n return this.message;\n };\n\n return ResponseError;\n});\n","Magento_PaymentServicesPaypal/js/view/payment/method-renderer.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'uiComponent',\n 'Magento_Checkout/js/model/payment/renderer-list'\n], function (Component, rendererList) {\n 'use strict';\n\n rendererList.push({\n type: 'payment_services_paypal_hosted_fields',\n component: 'Magento_PaymentServicesPaypal/js/view/payment/method-renderer/hosted-fields'\n }, {\n type: 'payment_services_paypal_smart_buttons',\n component: 'Magento_PaymentServicesPaypal/js/view/payment/method-renderer/smart-buttons'\n }, {\n type: 'payment_services_paypal_apple_pay',\n component: 'Magento_PaymentServicesPaypal/js/view/payment/method-renderer/apple-pay'\n }, {\n type: 'payment_services_paypal_google_pay',\n component: 'Magento_PaymentServicesPaypal/js/view/payment/method-renderer/google-pay'\n });\n\n return Component.extend({});\n});\n","Magento_PaymentServicesPaypal/js/view/payment/vault.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n/*browser:true*/\n\n/* @api */\ndefine([\n 'underscore',\n 'uiComponent',\n 'mage/translate',\n 'Magento_Checkout/js/model/payment/renderer-list',\n 'uiLayout',\n 'uiRegistry'\n], function (_, Component, $t, rendererList, layout, registry) {\n 'use strict';\n\n var vaultGroupName = 'vaultGroup';\n\n layout([{\n name: vaultGroupName,\n component: 'Magento_Checkout/js/model/payment/method-group',\n alias: 'vault',\n sortOrder: 10,\n title: $t('Stored Cards')\n }]);\n\n registry.get(vaultGroupName, function (vaultGroup) {\n _.each(window.checkoutConfig.payment.vault, function (config, index) {\n rendererList.push(\n {\n type: index,\n config: config.config,\n component: config.component,\n group: vaultGroup,\n\n /**\n * Custom payment method types comparator\n * @param {String} typeA\n * @param {String} typeB\n * @return {Boolean}\n */\n typeComparatorCallback: function (typeA, typeB) {\n // vault token items have the same name as vault payment without index\n return typeA.substring(0, typeA.lastIndexOf('_')) === typeB;\n }\n }\n );\n });\n });\n\n /**\n * Add view logic here if needed\n */\n return Component.extend({});\n});\n","Magento_PaymentServicesPaypal/js/view/payment/smart-buttons-product.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'underscore',\n 'jquery',\n 'mageUtils',\n 'Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract',\n 'scriptLoader',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/smart-buttons',\n 'mage/translate',\n 'Magento_Customer/js/customer-data',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error',\n 'jquery/jquery-storageapi'\n], function (_, $, utils, Component, loadSdkScript, SmartButtons, $t, customerData, ResponseError) {\n 'use strict';\n\n var refreshCustomerData = function (url) {\n // Trigger ajaxComplete event to update customer data\n customerData.onAjaxComplete(\n {},\n {\n type: 'POST',\n url: url,\n }\n );\n }\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalProduct',\n buttonsContainerId: 'smart-buttons-${ $.uid }',\n element: null,\n productFormSelector: '#product_addtocart_form',\n formInvalid: false,\n paymentActionError: $t('Something went wrong with your request. Please try again later.'),\n addToCartUrl: null,\n isErrorDisplayed: false\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n _.bindAll(this, 'renderButtons', 'initSmartButtons', 'onClick', 'catchError', 'beforeCreateOrder',\n 'afterCreateOrder', 'beforeOnAuthorize', 'afterOnAuthorize', 'onCancel');\n config.uid = utils.uniqueid();\n this._super();\n this.element = element;\n this.element.id = this.buttonsContainerId;\n this.getSdkParams()\n .then(this.initSmartButtons)\n .then(this.renderButtons)\n .catch(function (e) {\n console.log(e);\n });\n\n return this;\n },\n\n /**\n * Create instance of smart buttons.\n */\n initSmartButtons: function () {\n this.buttons = new SmartButtons({\n sdkNamespace: this.sdkNamespace,\n scriptParams: this.sdkParams,\n styles: this.styles,\n createOrderUrl: this.createOrderUrl,\n authorizeOrderUrl: this.authorizeOrderUrl,\n onClick: this.onClick,\n beforeCreateOrder: this.beforeCreateOrder,\n afterCreateOrder: this.afterCreateOrder,\n catchCreateOrder: this.catchError,\n finallyCreateOrder: this.showLoader.bind(this, false),\n beforeOnAuthorize: this.beforeOnAuthorize,\n afterOnAuthorize: this.afterOnAuthorize,\n catchOnAuthorize: this.catchError,\n finallyOnAuthorize: this.showLoader.bind(this, false),\n onError: this.catchError,\n onCancel: this.onCancel\n });\n },\n\n /**\n * Render buttons\n */\n renderButtons: function () {\n this.buttons.sdkLoaded.then(function () {\n try {\n this.buttons && this.buttons.render('#' + this.buttonsContainerId);\n } catch (e) {\n console.log(e);\n }\n }.bind(this)).catch(function () {\n console.log('Error: Failed to load PayPal SDK script!');\n });\n },\n\n /**\n * Show/hide loader.\n *\n * @param {Boolean} show\n */\n showLoader: function (show) {\n var event = show ? 'processStart' : 'processStop';\n\n $('body').trigger(event);\n },\n\n /**\n * Catch errors.\n *\n * @param {*} error\n */\n catchError: function (error) {\n var message = error instanceof ResponseError ? error.message : this.paymentActionError;\n\n this.showLoader(false);\n\n if (this.isErrorDisplayed) {\n return;\n }\n this.addMessage(message);\n this.isErrorDisplayed = true;\n },\n\n /**\n * Add message to customer data.\n *\n * @param {String} message\n * @param {String} [type]\n */\n addMessage: function (message, type) {\n type = type || 'error';\n customerData.set('messages', {\n messages: [{\n type: type,\n text: message\n }],\n 'data_id': Math.floor(Date.now() / 1000)\n });\n },\n\n /**\n * Calls when user click paypal button\n *\n * @param {Object} data\n * @param {Promise} actions\n * @return {Promise}\n */\n onClick: function (data, actions) {\n var $form = $(this.productFormSelector);\n\n if ($form.data('mageValidation')) {\n this.formInvalid = !$form.validation('isValid');\n }\n\n if (this.formInvalid) {\n return actions.reject();\n }\n\n return actions.resolve();\n },\n\n /**\n * Before create order.\n *\n * @return {Promise}\n */\n beforeCreateOrder: function () {\n this.isErrorDisplayed = false;\n this.showLoader(true);\n\n return new Promise(function (resolve, reject) {\n if (this.formInvalid) {\n return reject();\n }\n\n fetch(this.addToCartUrl, {\n method: 'POST',\n headers: {},\n body: new FormData($(this.productFormSelector)[0]),\n credentials: 'same-origin'\n }).then(function (response) {\n return response.json();\n }).then(function (data) {\n if (typeof data.success !== 'undefined') {\n refreshCustomerData(this.addToCartUrl);\n\n return resolve();\n }\n\n return reject(new ResponseError(data.error));\n }.bind(this)).catch(function () {\n return reject();\n });\n }.bind(this));\n },\n\n /**\n * After order id created.\n *\n * @param {Object} res\n * @return {*}\n */\n afterCreateOrder: function (res) {\n if (res.response['is_successful']) {\n refreshCustomerData(this.createOrderUrl);\n\n return res.response['paypal-order'].id;\n }\n\n throw new ResponseError(res.response.error);\n },\n\n /**\n * Before onAuthorize execute\n *\n * @param {Object} data\n * @return {Promise}\n */\n beforeOnAuthorize: function (data) {\n this.showLoader(true);\n\n return Promise.resolve(data);\n },\n\n /**\n * After onAuthorize execute\n *\n * @param {Object} res\n * @param {Object} actions\n * @return {*}\n */\n afterOnAuthorize: function (res, actions) {\n if (res.success) {\n return actions.redirect(res.redirectUrl);\n }\n\n throw new ResponseError(res.error);\n },\n\n /**\n * Redirect to cart on cancel.\n *\n * @param {Object} data\n * @param {Object} actions\n */\n onCancel: function (data, actions) {\n customerData.invalidate(['cart']);\n actions.redirect(this.cancelUrl);\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/message-cart.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract',\n 'Magento_PaymentServicesPaypal/js/view/payment/message',\n 'Magento_Customer/js/customer-data'\n], function (Component, Message, customerData) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalCart',\n element: null,\n message: null\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n var cartData = customerData.get('cart');\n\n this.element = element;\n this._super();\n this.getSdkParams()\n .then(this.initMessage.bind(this))\n .then(function () {\n cartData.subscribe(function (updatedCart) {\n this.message.updateAmount(updatedCart.subtotalAmount);\n }, this);\n }.bind(this))\n .then(this.render.bind(this));\n\n },\n\n /**\n * Create instance of messages.\n */\n initMessage: function () {\n var cartData = customerData.get('cart');\n\n this.message = new Message({\n sdkNamespace: this.sdkNamespace,\n scriptParams: this.sdkParams,\n element: this.element,\n renderContainer: this.renderContainer,\n styles: this.styles,\n placement: this.placement,\n amount: cartData().subtotalAmount\n });\n },\n\n /**\n * Render message\n */\n render: function () {\n this.message.render();\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/google-pay-product.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'underscore',\n 'jquery',\n 'mageUtils',\n 'Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract',\n 'mage/translate',\n 'Magento_Customer/js/customer-data',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/google-pay'\n], function (_, $, utils, Component, $t, customerData, ResponseError, GooglePayButton) {\n 'use strict';\n\n const HTTP_STATUS_OK = 200;\n\n var refreshCustomerData = function (url) {\n // Trigger ajaxComplete event to update customer data\n customerData.onAjaxComplete(\n {},\n {\n type: 'POST',\n url: url,\n }\n );\n }\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalGooglePay',\n scriptParams: {},\n buttonContainerId: 'google-pay-${ $.uid }',\n template: 'Magento_PaymentServicesPaypal/payment/google-pay',\n paymentsOrderId: null,\n paypalOrderId: null,\n sdkLoaded: null,\n sdkParamsKey: 'googlepay',\n paymentTypeIconTitle: $t('Pay with Google Pay'),\n requestProcessingError: $t('Something went wrong with your request. Please try again later.'),\n notEligibleErrorMessage: $t('This payment option is currently unavailable.'),\n productFormSelector: '#product_addtocart_form'\n },\n\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n _.bindAll(this, 'initGooglePayButton', 'onClick', 'afterUpdateQuote',\n 'catchError', 'beforeCreateOrder', 'afterOnAuthorize', 'onCancel');\n config.uid = utils.uniqueid();\n this._super();\n this.element = element;\n this.element.id = this.buttonContainerId;\n this.getSdkParams()\n .then(this.initGooglePayButton)\n .catch(console.log);\n\n return this;\n },\n\n initGooglePayButton: function () {\n this.googlePayButton = new GooglePayButton({\n scriptParams: this.sdkParams,\n createOrderUrl: this.createOrderUrl,\n updateQuoteUrl: this.authorizeOrderUrl,\n onClick: this.onClick,\n beforeCreateOrder: this.beforeCreateOrder,\n catchCreateOrder: this.catchError,\n onError: this.catchError,\n buttonContainerId: this.buttonContainerId,\n afterUpdateQuote: this.afterUpdateQuote,\n shippingAddressRequired: !this.isVirtual,\n styles: this.styles,\n afterOnAuthorize: this.afterOnAuthorize,\n onCancel: this.onCancel,\n mode: this.googlePayMode\n });\n\n this.googlePayButton.sdkLoaded\n .then(this.googlePayButton.initGoogleSDK);\n },\n\n afterUpdateQuote: function (data) {\n window.location = data.redirectUrl;\n this.googlePayButton.showLoader(false);\n },\n\n onClick: function () {\n var $form = $(this.productFormSelector);\n\n if ($form.data('mageValidation')) {\n this.formValid = $form.validation('isValid');\n }\n\n if (this.formValid) {\n this.isErrorDisplayed = false;\n\n this.googlePayButton.showLoaderAsync(true)\n .then(() => {\n return this.googlePayButton.createOrder();\n })\n .then(() => {\n refreshCustomerData(this.createOrderUrl);\n })\n .catch(error => {\n this.catchError(error);\n });\n }\n },\n\n /**\n * Catch errors.\n *\n * @param {*} error\n */\n catchError: function (error) {\n console.log(error);\n this.googlePayButton.showLoader(false);\n\n if (this.isErrorDisplayed) {\n return;\n }\n\n if (error.hidden === undefined || !error.hidden) {\n this.addMessage(this.requestProcessingError);\n }\n\n this.isErrorDisplayed = true;\n },\n\n /**\n * Add message to customer data.\n *\n * @param {String} message\n * @param {String} [type]\n */\n addMessage: function (message, type) {\n type = type || 'error';\n customerData.set('messages', {\n messages: [{\n type: type,\n text: message\n }],\n 'data_id': Math.floor(Date.now() / 1000)\n });\n },\n\n /**\n * Before create order.\n *\n * @return {String}\n */\n beforeCreateOrder: function () {\n this.isErrorDisplayed = false;\n\n if (this.formInvalid) {\n throw new Error('Form is Invalid');\n }\n\n let xhr = new XMLHttpRequest();\n xhr.open('POST', this.addToCartUrl, false);\n xhr.send(new FormData($(this.productFormSelector)[0]));\n\n if (xhr.status !== HTTP_STATUS_OK) {\n throw new Error('Request failed');\n } else {\n try {\n let result = JSON.parse(xhr.responseText);\n\n if (typeof result.success !== 'undefined') {\n refreshCustomerData(this.addToCartUrl);\n return result.success;\n }\n } catch (parseError) {\n throw new Error('Failed to parse response JSON: ' + parseError.message);\n }\n }\n },\n\n afterOnAuthorize: function (data) {\n window.location = data.redirectUrl;\n this.googlePayButton.showLoader(false);\n },\n\n /**\n * Redirect to cart on cancel.\n *\n * @param {Object} data\n * @param {Object} actions\n */\n onCancel: function () {\n customerData.invalidate(['cart']);\n window.location = this.cancelUrl;\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/message.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'uiComponent',\n 'scriptLoader'\n], function ($, Component, loadSdkScript) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypal',\n renderContainer: null,\n amountAttribute: 'data-pp-amount',\n amount: null\n },\n\n /**\n * @inheritdoc\n */\n initialize: function () {\n this._super();\n this.sdkLoaded = loadSdkScript(this.scriptParams, this.sdkNamespace);\n\n return this;\n },\n\n /**\n * Update amount\n *\n * @param {*} amount\n */\n updateAmount: function (amount) {\n this.amount = amount;\n $(this.renderContainer).attr(this.amountAttribute, this.amount);\n },\n\n /**\n * Render message\n *\n * @return {Promise}\n */\n render: function () {\n return this.sdkLoaded.then(function (sdkScript) {\n sdkScript.Messages({\n amount: parseFloat(this.amount).toFixed(2),\n placement: this.placement,\n style: this.styles\n })\n .render(this.renderContainer);\n }.bind(this)).catch(function (exception) {\n console.log('Error: Failed to load PayPal SDK script!');\n console.log(exception.message);\n });\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/google-pay-cart.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'underscore',\n 'jquery',\n 'mageUtils',\n 'Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract',\n 'mage/translate',\n 'Magento_Customer/js/customer-data',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/google-pay'\n], function (_, $, utils, Component, $t, customerData, ResponseError, GooglePayButton) {\n 'use strict';\n\n var refreshCustomerData = function (url) {\n // Trigger ajaxComplete event to update customer data\n customerData.onAjaxComplete(\n {},\n {\n type: 'POST',\n url: url,\n }\n );\n }\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalGooglePay',\n sdkParamsKey: 'googlepay',\n buttonContainerId: 'google-pay-${ $.uid }',\n paymentActionError: $t('Something went wrong with your request. Please try again later.'),\n isErrorDisplayed: false\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n _.bindAll(this, 'initGooglePayButton', 'onClick',\n 'afterOnAuthorize', 'catchError', 'onCancel');\n config.uid = utils.uniqueid();\n this._super();\n this.element = element;\n this.element.id = this.buttonContainerId;\n this.getSdkParams()\n .then(this.initGooglePayButton)\n .catch(console.log);\n\n return this;\n },\n\n initGooglePayButton: function () {\n this.googlePayButton = new GooglePayButton({\n scriptParams: this.sdkParams,\n createOrderUrl: this.createOrderUrl,\n updateQuoteUrl: this.authorizeOrderUrl,\n onClick: this.onClick,\n catchCreateOrder: this.catchError,\n onError: this.catchError,\n buttonContainerId: this.buttonContainerId,\n afterOnAuthorize: this.afterOnAuthorize,\n shippingAddressRequired: !this.isVirtual,\n styles: this.styles,\n onCancel: this.onCancel,\n mode: this.googlePayMode\n });\n\n this.googlePayButton.sdkLoaded\n .then(this.googlePayButton.initGoogleSDK);\n },\n\n afterOnAuthorize: function (data) {\n window.location = data.redirectUrl;\n this.googlePayButton.showLoader(false);\n },\n\n onClick: function () {\n this.isErrorDisplayed = false;\n\n this.googlePayButton.showLoaderAsync(true)\n .then(() => {\n return this.googlePayButton.createOrder();\n })\n .then(() => {\n refreshCustomerData(this.createOrderUrl);\n })\n .catch(error => {\n this.catchError(error);\n });\n },\n\n /**\n * Catch errors.\n *\n * @param {*} error\n */\n catchError: function (error) {\n var message = error instanceof ResponseError ? error.message : this.paymentActionError;\n\n console.log(error);\n\n this.googlePayButton.showLoader(false);\n\n if (this.isErrorDisplayed) {\n return;\n }\n\n if (error.hidden === undefined || !error.hidden) {\n this.addMessage(message);\n }\n\n this.isErrorDisplayed = true;\n },\n\n /**\n * Add message to customer data.\n *\n * @param {String} message\n * @param {String} [type]\n */\n addMessage: function (message, type) {\n type = type || 'error';\n customerData.set('messages', {\n messages: [{\n type: type,\n text: message\n }],\n 'data_id': Math.floor(Date.now() / 1000)\n });\n },\n\n /**\n * Redirect to cart on cancel.\n *\n * @param {Object} data\n * @param {Object} actions\n */\n onCancel: function () {\n customerData.invalidate(['cart']);\n window.location = this.cancelUrl;\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/apple-pay-cart.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'underscore',\n 'jquery',\n 'mageUtils',\n 'Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract',\n 'mage/translate',\n 'Magento_Customer/js/customer-data',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/apple-pay',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Checkout/js/model/cart/totals-processor/default',\n], function (_, $, utils, Component, $t, customerData, ResponseError, ApplePayButton, quote, totalsProcessor) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalApplePay',\n sdkParamsKey: 'applepay',\n buttonContainerId: 'apple-pay-${ $.uid }',\n paymentActionError: $t('Something went wrong with your request. Please try again later.'),\n isErrorDisplayed: false\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n _.bindAll(this, 'initApplePayButton', 'onClick', 'afterOnAuthorize', 'afterCreateOrder', 'showPopup', 'cancelApplePay');\n config.uid = utils.uniqueid();\n this._super();\n this.element = element;\n this.element.id = this.buttonContainerId;\n\n this.getSdkParams()\n .then(this.initApplePayButton)\n .catch(console.log);\n\n // Reload quote totals in minicart to have the correct grand_total for the Apple Popup\n if (this.pageType === 'minicart') {\n totalsProcessor.estimateTotals().done(function (result) {\n quote.setTotals(result);\n });\n }\n return this;\n },\n\n initApplePayButton: function () {\n this.applePayButton = new ApplePayButton({\n scriptParams: this.sdkParams,\n createOrderUrl: this.createOrderUrl,\n estimateShippingMethodsWhenLoggedInUrl: this.estimateShippingMethodsWhenLoggedInUrl,\n estimateShippingMethodsWhenGuestUrl: this.estimateShippingMethodsWhenGuestUrl,\n shippingInformationWhenLoggedInUrl: this.shippingInformationWhenLoggedInUrl,\n shippingInformationWhenGuestUrl: this.shippingInformationWhenGuestUrl,\n updatePaypalOrderUrl: this.updatePaypalOrderUrl,\n countriesUrl: this.countriesUrl,\n placeOrderUrl: this.placeOrderUrl,\n showPopup: this.showPopup,\n updateQuoteUrl: this.authorizeOrderUrl,\n onClick: this.onClick,\n afterCreateOrder: this.afterCreateOrder,\n catchCreateOrder: this.catchError,\n onError: this.catchError,\n buttonContainerId: this.buttonContainerId,\n afterOnAuthorize: this.afterOnAuthorize,\n shippingAddressRequired: !this.isVirtual,\n styles: this.styles,\n pageType: this.pageType,\n });\n\n $('#' + this.buttonContainerId).on('click', this.onClick);\n\n this.applePayButton.sdkLoaded\n .then(this.applePayButton.initAppleSDK);\n },\n\n afterOnAuthorize: function (data) {\n\n this.applePayButton.showLoaderAsync(true)\n .then(() => {\n $.ajax({\n type: 'POST',\n url: this.placeOrderUrl,\n }).then(result => {\n customerData.invalidate(['cart']);\n document.open();\n document.write(result);\n document.close();\n });\n })\n .catch(error => {\n this.catchError(error);\n });\n },\n\n onClick: function () {\n this.isErrorDisplayed = false;\n\n this.applePayButton.showLoaderAsync(true).then(() => {\n const data = {\n response: {\n 'paypal-order': {\n currency_code: String(quote.totals().quote_currency_code),\n amount: Number(quote.totals().grand_total).toString(),\n }\n }\n }\n this.applePayButton.showPopup(data);\n })\n },\n\n /**\n * After order created.\n *\n * @param {Object} data\n * @return {String}\n */\n afterCreateOrder: function (data) {\n if (data.response['paypal-order'] && data.response['paypal-order']['mp_order_id']) {\n this.paymentsOrderId = data.response['paypal-order']['mp_order_id'];\n this.paypalOrderId = data.response['paypal-order'].id;\n return this.paypalOrderId;\n }\n\n throw new Error();\n },\n\n cancelApplePay: function (){\n customerData.invalidate(['cart']);\n window.location.reload();\n },\n\n showPopup: function (paymentData) {\n const paymentRequest = {\n countryCode: this.applePayButton.applePayConfig.countryCode,\n merchantCapabilities: this.applePayButton.applePayConfig.merchantCapabilities,\n supportedNetworks: this.applePayButton.applePayConfig.supportedNetworks,\n currencyCode: paymentData.response['paypal-order']['currency_code'],\n requiredShippingContactFields: [\"name\", \"phone\", \"email\", \"postalAddress\"],\n requiredBillingContactFields: [\"postalAddress\"],\n total: {\n label: $t(\"Summary\"),\n type: \"final\",\n amount: Number(paymentData.response['paypal-order']['amount']).toString(),\n }\n };\n\n // See https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession\n this.applePaySession = new ApplePaySession(this.applePayButton.applePayVersionNumber, paymentRequest);\n\n this.applePayButton.onApplePayValidateMerchant(this.applePaySession);\n this.applePayButton.onApplePayPaymentMethodSelected(this.applePaySession, paymentRequest.total);\n this.applePayButton.onApplePayCancel(this.applePaySession, this.cancelApplePay);\n this.applePayButton.onApplePayShippingContactSelected(this.applePaySession, quote.getQuoteId() , paymentRequest.total, quote.isVirtual());\n this.applePayButton.onApplePayShippingMethodSelectedInCartPage(this.applePaySession, quote.getQuoteId());\n this.applePayButton.onApplePayPaymentAuthorized(this.applePaySession);\n\n this.applePaySession.begin();\n },\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/apple-pay-product.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'jquery',\n 'underscore',\n 'mageUtils',\n 'Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract',\n 'mage/translate',\n 'Magento_Customer/js/customer-data',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/apple-pay',\n], function ($, _, utils, Component, $t, customerData, ResponseError, ApplePayButton) {\n 'use strict';\n\n const HTTP_STATUS_OK = 200;\n\n var refreshCustomerData = function (url) {\n // Trigger ajaxComplete event to update customer data\n customerData.onAjaxComplete(\n {},\n {\n type: 'POST',\n url: url,\n }\n );\n }\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalApplePay',\n scriptParams: {},\n buttonContainerId: 'apple-pay-${ $.uid }',\n template: 'Magento_PaymentServicesPaypal/payment/apple-pay',\n paymentsOrderId: null,\n paypalOrderId: null,\n sdkLoaded: null,\n quoteIdForRest: null,\n quoteId: null,\n sdkParamsKey: 'applepay',\n paymentTypeIconTitle: $t('Pay with Apple Pay'),\n notEligibleErrorMessage: $t('This payment option is currently unavailable.'),\n productFormSelector: '#product_addtocart_form'\n },\n\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n _.bindAll(this, 'initApplePayButton', 'onClick', 'afterUpdateQuote', 'beforeCreateOrder',\n 'afterCreateOrder', 'afterOnAuthorize', 'onCancel');\n config.uid = utils.uniqueid();\n this._super();\n this.element = element;\n this.element.id = this.buttonContainerId;\n this.getSdkParams()\n .then(this.initApplePayButton)\n .catch(console.log);\n\n return this;\n },\n\n initApplePayButton: function () {\n this.applePayButton = new ApplePayButton({\n scriptParams: this.sdkParams,\n createOrderUrl: this.createOrderUrl,\n updateQuoteUrl: this.authorizeOrderUrl,\n shippingInformationWhenGuestUrl: this.shippingInformationWhenGuestUrl,\n shippingInformationWhenLoggedInUrl: this.shippingInformationWhenLoggedInUrl,\n estimateShippingMethodsWhenGuestUrl: this.estimateShippingMethodsWhenGuestUrl,\n estimateShippingMethodsWhenLoggedInUrl: this.estimateShippingMethodsWhenLoggedInUrl,\n updatePayPalOrderUrl: this.updatePayPalOrderUrl,\n setQuoteAsInactiveUrl: this.setQuoteAsInactiveUrl,\n countriesUrl: this.countriesUrl,\n placeOrderUrl: this.placeOrderUrl,\n onClick: this.onClick,\n beforeCreateOrder: this.beforeCreateOrder,\n afterCreateOrder: this.afterCreateOrder,\n catchCreateOrder: this.catchError,\n onError: this.catchError,\n buttonContainerId: this.buttonContainerId,\n afterUpdateQuote: this.afterUpdateQuote,\n shippingAddressRequired: !this.isVirtual,\n styles: this.styles,\n afterOnAuthorize: this.afterOnAuthorize,\n onCancel: this.onCancel,\n pageType: this.pageType,\n });\n\n $('#' + this.buttonContainerId).on('click', this.onClick);\n\n this.applePayButton.sdkLoaded\n .then(this.applePayButton.initAppleSDK);\n },\n\n afterUpdateQuote: function (data) {\n window.location = data.redirectUrl;\n this.applePayButton.showLoader(false);\n },\n\n onClick: function () {\n\n var $form = $(this.productFormSelector);\n\n if ($form.data('mageValidation')) {\n this.formValid = $form.validation('isValid');\n }\n\n if (this.formValid) {\n this.applePayButton.showLoaderAsync(true)\n .then(() => {\n return this.applePayButton.createOrder();\n })\n .then(() => {\n refreshCustomerData(this.createOrderUrl);\n })\n .catch(error => {\n this.applePayButton.catchError(error);\n });\n }\n },\n\n setQuoteInactive: function () {\n // Set Quote as inactive to avoid having multiple active quotes for the customer\n $.ajax({\n type: 'POST',\n url: this.setQuoteAsInactiveUrl,\n });\n },\n\n showPopup: function (paymentData) {\n\n const paymentRequest = {\n countryCode: this.applePayButton.applePayConfig.countryCode,\n merchantCapabilities: this.applePayButton.applePayConfig.merchantCapabilities,\n supportedNetworks: this.applePayButton.applePayConfig.supportedNetworks,\n currencyCode: String(paymentData['currencyCode']),\n requiredShippingContactFields: [\"name\", \"phone\", \"email\", \"postalAddress\"],\n requiredBillingContactFields: [\"postalAddress\"],\n total: {\n label: $t(\"Summary\"),\n type: \"final\",\n amount: Number(paymentData['totalPrice']).toString(),\n }\n };\n\n // See https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession\n this.applePaySession = new ApplePaySession(this.applePayButton.applePayVersionNumber, paymentRequest);\n this.applePayButton.onApplePayValidateMerchant(this.applePaySession);\n this.applePayButton.onApplePayPaymentMethodSelected(this.applePaySession, paymentRequest.total);\n this.applePayButton.onApplePayCancel(this.applePaySession, this.setQuoteInactive.bind(this));\n this.applePayButton.onApplePayShippingContactSelected(this.applePaySession, this.quoteIdForRest, paymentRequest.total, null);\n this.applePayButton.onApplePayShippingMethodSelected(this.applePaySession, this.quoteId, this.quoteIdForRest, this.paypalOrderId);\n this.applePayButton.onApplePayPaymentAuthorized(this.applePaySession);\n\n this.applePaySession.begin();\n },\n\n /**\n * Before create order.\n *\n * @return {String}\n */\n beforeCreateOrder: function () {\n if (this.formInvalid) {\n throw new Error('Form is Invalid');\n }\n\n let xhr = new XMLHttpRequest();\n xhr.open('POST', this.addToCartUrl, false);\n xhr.send(new FormData($(this.productFormSelector)[0]));\n\n if (xhr.status !== HTTP_STATUS_OK) {\n throw new Error('Request failed');\n } else {\n try {\n let result = JSON.parse(xhr.responseText);\n\n if (typeof result.success !== 'undefined') {\n refreshCustomerData(this.addToCartUrl);\n this.quoteIdForRest = result.success.quoteIdMask;\n this.quoteId = result.success.quoteId;\n return result.success;\n }\n } catch (parseError) {\n throw new Error('Failed to parse response JSON: ' + parseError.message);\n }\n }\n },\n\n /**\n * After order created.\n *\n * @param {Object} data\n * @return {String}\n */\n afterCreateOrder: function (data) {\n if (data.response['paypal-order'] && data.response['paypal-order']['mp_order_id']) {\n this.paymentsOrderId = data.response['paypal-order']['mp_order_id'];\n this.paypalOrderId = data.response['paypal-order'].id;\n\n this.showPopup({\n displayItems: [],\n currencyCode: data.response['paypal-order']['currency_code'],\n totalPriceStatus: 'FINAL',\n totalPrice: Number(data.response['paypal-order']['amount']).toString(),\n totalPriceLabel: $t('Total')\n });\n\n return this.paypalOrderId;\n }\n\n throw new Error();\n },\n\n afterOnAuthorize: function (data) {\n\n this.applePayButton.showLoaderAsync(true)\n .then(() => {\n $.ajax({\n type: 'POST',\n url: this.placeOrderUrl,\n }).then(result => {\n customerData.invalidate(['cart']);\n document.open();\n document.write(result);\n document.close();\n });\n })\n .catch(error => {\n this.catchError(error);\n });\n },\n\n /**\n * Redirect to cart on cancel.\n *\n * @param {Object} data\n * @param {Object} actions\n */\n onCancel: function () {\n customerData.invalidate(['cart']);\n window.location = this.cancelUrl;\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/smart-buttons-cart.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'underscore',\n 'jquery',\n 'mageUtils',\n 'Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract',\n 'scriptLoader',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/smart-buttons',\n 'mage/translate',\n 'Magento_Customer/js/customer-data',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error'\n], function (_, $, utils, Component, loadSdkScript, SmartButtons, $t, customerData, ResponseError) {\n 'use strict';\n\n var refreshCustomerData = function (url) {\n // Trigger ajaxComplete event to update customer data\n customerData.onAjaxComplete(\n {},\n {\n type: 'POST',\n url: url,\n }\n );\n }\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalCart',\n buttonsContainerId: 'smart-buttons-${ $.uid }',\n element: null,\n paymentActionError: $t('Something went wrong with your request. Please try again later.'),\n isErrorDisplayed: false\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n _.bindAll(this, 'renderButtons', 'initSmartButtons', 'catchError', 'beforeCreateOrder', 'afterCreateOrder',\n 'beforeOnAuthorize', 'afterOnAuthorize', 'onCancel');\n config.uid = utils.uniqueid();\n this._super();\n this.element = element;\n this.element.id = this.buttonsContainerId;\n this.getSdkParams()\n .then(this.initSmartButtons)\n .then(this.renderButtons)\n .catch(function (e) {\n console.log(e);\n });\n\n return this;\n },\n\n /**\n * Create instance of smart buttons.\n */\n initSmartButtons: function () {\n this.buttons = new SmartButtons({\n sdkNamespace: this.sdkNamespace,\n scriptParams: this.sdkParams,\n styles: this.styles,\n createOrderUrl: this.createOrderUrl,\n authorizeOrderUrl: this.authorizeOrderUrl,\n beforeCreateOrder: this.beforeCreateOrder,\n afterCreateOrder: this.afterCreateOrder,\n catchCreateOrder: this.catchError,\n finallyCreateOrder: this.showLoader.bind(this, false),\n beforeOnAuthorize: this.beforeOnAuthorize,\n afterOnAuthorize: this.afterOnAuthorize,\n catchOnAuthorize: this.catchError,\n finallyOnAuthorize: this.showLoader.bind(this, false),\n onError: this.catchError,\n onCancel: this.onCancel\n });\n },\n\n /**\n * Render buttons\n */\n renderButtons: function () {\n this.buttons.sdkLoaded.then(function () {\n this.buttons && this.buttons.render('#' + this.buttonsContainerId);\n }.bind(this)).catch(function () {\n console.log('Error: Failed to load PayPal SDK script!');\n });\n },\n\n /**\n * Show/hide loader.\n *\n * @param {Boolean} show\n */\n showLoader: function (show) {\n var event = show ? 'processStart' : 'processStop';\n\n $('body').trigger(event);\n },\n\n /**\n * Catch errors.\n *\n * @param {*} error\n */\n catchError: function (error) {\n var message = error instanceof ResponseError ? error.message : this.paymentActionError;\n\n this.showLoader(false);\n\n if (this.isErrorDisplayed) {\n return;\n }\n this.addMessage(message);\n this.isErrorDisplayed = true;\n },\n\n /**\n * Add message to customer data.\n *\n * @param {String} message\n * @param {String} [type]\n */\n addMessage: function (message, type) {\n type = type || 'error';\n customerData.set('messages', {\n messages: [{\n type: type,\n text: message\n }],\n 'data_id': Math.floor(Date.now() / 1000)\n });\n },\n\n /**\n * Before create order.\n *\n * @return {Promise}\n */\n beforeCreateOrder: function () {\n this.isErrorDisplayed = false;\n this.showLoader(true);\n\n return Promise.resolve();\n },\n\n /**\n * After order id created.\n *\n * @param {Object} res\n * @return {*}\n */\n afterCreateOrder: function (res) {\n if (res.response['is_successful']) {\n refreshCustomerData(this.createOrderUrl);\n\n return res.response['paypal-order'].id;\n }\n\n throw new ResponseError(res.response.error);\n },\n\n /**\n * Before onAuthorize execute\n *\n * @param {Object} data\n * @return {Promise}\n */\n beforeOnAuthorize: function (data) {\n this.showLoader(true);\n\n return Promise.resolve(data);\n },\n\n /**\n * After onAuthorize execute\n *\n * @param {Object} res\n * @param {Object} actions\n * @return {*}\n */\n afterOnAuthorize: function (res, actions) {\n if (res.success) {\n return actions.redirect(res.redirectUrl);\n }\n\n throw new ResponseError(res.error);\n },\n\n /**\n * Redirect to cart on cancel.\n *\n * @param {Object} data\n * @param {Object} actions\n */\n onCancel: function (data, actions) {\n customerData.invalidate(['cart']);\n actions.redirect(this.cancelUrl);\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/message-product.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract',\n 'Magento_PaymentServicesPaypal/js/view/payment/message',\n 'Magento_PaymentServicesPaypal/js/view/product/product-data-provider',\n 'Magento_PaymentServicesPaypal/js/view/product/grouped-product-data-provider',\n 'Magento_PaymentServicesPaypal/js/view/product/bundle-product-data-provider',\n 'Magento_PaymentServicesPaypal/js/view/product/gift-card-product-data-provider'\n], function (\n Component,\n Message,\n ProductDataProvider,\n GroupedProductDataProvider,\n BundledProductDataProvider,\n GiftCardProductDataProvider\n) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalProduct',\n element: null,\n message: null\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config, element) {\n var providerOptions = {\n updateAmount: this.updateAmount.bind(this)\n };\n\n this.element = element;\n this._super();\n\n if (GroupedProductDataProvider.prototype.isProductGrouped()) {\n this.provider = new GroupedProductDataProvider(providerOptions);\n } else if (BundledProductDataProvider.prototype.isBundleProduct()) {\n this.provider = new BundledProductDataProvider(providerOptions);\n } else if (GiftCardProductDataProvider.prototype.isProductGiftCard()) {\n this.provider = new GiftCardProductDataProvider(providerOptions);\n } else {\n this.provider = new ProductDataProvider(providerOptions);\n }\n this.getSdkParams()\n .then(this.initMessage.bind(this))\n .then(this.render.bind(this));\n },\n\n /**\n * Create instance of messages.\n */\n initMessage: function () {\n this.message = new Message({\n sdkNamespace: this.sdkNamespace,\n scriptParams: this.sdkParams,\n element: this.element,\n renderContainer: this.renderContainer,\n styles: this.styles,\n placement: this.placement,\n amount: this.provider.getAmount()\n });\n },\n\n /**\n * Update message amount.\n */\n updateAmount: function () {\n this.message && this.message.updateAmount(this.provider.getAmount());\n },\n\n /**\n * Render the message\n */\n render: function () {\n this.message.render();\n this.provider.updatePrice();\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/paypal-abstract.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'uiComponent',\n 'Magento_PaymentServicesPaypal/js/view/payment/actions/get-sdk-params'\n], function (Component, getSdkParams) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n sdkParamsKey: 'paypal',\n sdkParams: [],\n cacheTtl: 30000\n },\n\n /**\n * Get sdk params\n *\n * @return {Promise<Object>}\n */\n getSdkParams: function () {\n return getSdkParams(this.cacheTtl)\n .then(function (sdkParams) {\n this.sdkParams = sdkParams[this.sdkParamsKey];\n }.bind(this));\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/method-renderer/hosted-fields.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'jquery',\n 'underscore',\n 'mage/translate',\n 'Magento_Checkout/js/view/payment/default',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Checkout/js/model/full-screen-loader',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/hosted-fields',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error',\n 'Magento_Checkout/js/action/set-billing-address',\n 'Magento_Ui/js/model/messageList',\n 'Magento_Vault/js/view/payment/vault-enabler',\n 'Magento_Checkout/js/model/payment/additional-validators',\n], function (\n $,\n _,\n $t,\n Component,\n quote,\n loader,\n HostedFields,\n ResponseError,\n setBillingAddressAction,\n globalMessageList,\n VaultEnabler,\n additionalValidators\n) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n isFormValid: false,\n invalidFields: [],\n isAvailable: false,\n isFormRendered: false,\n fields: {\n number: {\n class: 'card-number-field',\n label: $t('Credit Card Number'),\n errorMessage: $t('Please enter a valid credit card number.'),\n selector: '#${ $.formId } .${ $.fields.number.class }',\n placeholder: '',\n showLockIcon: true\n },\n expirationDate: {\n class: 'expiration-date-field',\n selector: '#${ $.formId } .expiration-date-field',\n label: $t('Expiration Date'),\n errorMessage: $t('Incorrect credit card expiration date.'),\n placeholder: 'MM/YY'\n },\n cvv: {\n class: 'cvv-field',\n selector: '#${ $.formId } .cvv-field',\n label: $t('Card Security Code'),\n errorMessage: $t('Please enter a valid credit card security code.'),\n tooltip: {\n title: $t('What is this?'),\n src: $.cvvImgUrl,\n contentUnsanitizedHtml: '<img src=\"${ $.cvvImgUrl }\" ' +\n 'alt=\"${ $.cvvTitle }\" title=\"${ $.cvvTitle }\" />'\n },\n placeholder: ''\n }\n },\n fieldsLayout: {\n first: ['number'],\n second: ['expirationDate', 'cvv']\n },\n cards: {\n AE: {\n eligibilityCode: 'amex',\n typeCode: 'american-express'\n },\n DI: {\n eligibilityCode: 'discover',\n typeCode: 'discover'\n },\n ELO: {\n eligibilityCode: 'elo',\n typeCode: 'elo'\n },\n HC: {\n eligibilityCode: 'hiper',\n typeCode: 'hiper'\n },\n JCB: {\n eligibilityCode: 'jcb',\n typeCode: 'jcb'\n },\n MC: {\n eligibilityCode: 'mastercard',\n typeCode: 'master-card'\n },\n VI: {\n eligibilityCode: 'visa',\n typeCode: 'visa'\n }\n },\n availableCards: [],\n threeDSMode: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].threeDS,\n createOrderUrl: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].createOrderUrl,\n getOrderDetailsUrl: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].getOrderDetailsUrl, // eslint-disable-line max-len\n requiresCardDetails: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].requiresCardDetails, // eslint-disable-line max-len\n ccIcons: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].ccIcons,\n paymentSource: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].paymentSource,\n cvvImgUrl: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].cvvImageUrl,\n scriptParams: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].sdkParams,\n sdkNamespace: 'paypalCheckoutHostedFields',\n isCommerceVaultEnabled: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].isCommerceVaultEnabled, // eslint-disable-line max-len\n emptyErrorMessage: $t('This is a required field.'),\n paymentTypeIconUrl: window.checkoutConfig.payment['payment_services_paypal_hosted_fields'].paymentTypeIconUrl, // eslint-disable-line max-len\n paymentTypeIconTitle: $t('Pay with credit card'),\n lockTitle: $t('Secure transaction'),\n cvvTitle: $t('The card security code is a three or four digit number printed on a credit card. Visa, Mastercard, and Discover cards have a three digit code on the card back. American Express cards have a four digit code on the card front.'), // eslint-disable-line max-len\n paymentMethodValidationError: $t('Your payment was not successful. Ensure you have entered your details correctly and try again, or try a different payment method. If you have continued problems, contact the issuing bank for your payment method.'), // eslint-disable-line max-len\n notEligibleErrorMessage: $t('This payment option is currently unavailable.'),\n generalErrorMessage: '${ $.paymentMethodValidationError }',\n placeOrderTitle: $t('Place Order'),\n formId: 'hosted-fields-form',\n template: 'Magento_PaymentServicesPaypal/payment/credit-card',\n ccType: '',\n billingAddress: quote.billingAddress,\n paymentsOrderId: null,\n paypalOrderId: null,\n cardBin: null,\n holderName: null,\n cardLast4: null,\n cardExpiryMonth: null,\n cardExpiryYear: null,\n hostedFields: null,\n shouldCardBeVaulted: false\n },\n\n /** @inheritdoc */\n initialize: function () {\n // config\n\n _.bindAll(\n this,\n 'onSuccess',\n 'onError',\n 'afterHostedFieldsRender',\n 'onOrderSuccess',\n 'beforeCreateOrder',\n 'getOrderCardDetails'\n );\n this._super();\n this.initHostedFields();\n this.vaultEnabler = new VaultEnabler();\n this.vaultEnabler.isActivePaymentTokenEnabler(false);\n this.vaultEnabler.setPaymentCode(window.checkoutConfig.payment[this.getCode()].ccVaultCode);\n\n return this;\n },\n\n /**\n * Initialize Hosted Fields.\n */\n initHostedFields: function () {\n this.hostedFields = new HostedFields({\n formId: this.formId,\n fields: this.fields,\n sdkNamespace: this.sdkNamespace,\n scriptParams: this.scriptParams,\n beforeCreateOrder: this.beforeCreateOrder,\n onOrderSuccess: this.onOrderSuccess,\n createOrderUrl: this.createOrderUrl,\n shouldCardBeVaulted: this.shouldCardBeVaulted,\n paymentSource: this.paymentSource\n });\n },\n\n /** @inheritdoc */\n initObservable: function () {\n this._super()\n .observe('billingAddress paymentsOrderId paypalOrderId cardBin ' +\n 'holderName cardLast4 cardExpiryMonth cardExpiryYear ' +\n 'ccType isFormValid invalidFields availableCards isAvailable isFormRendered shouldCardBeVaulted');\n\n return this;\n },\n\n /** @inheritdoc */\n getCode: function () {\n return 'payment_services_paypal_hosted_fields';\n },\n\n /** @inheritdoc */\n getData: function () {\n var data = this._super();\n\n data['additional_data'] = {\n payments_order_id: this.paymentsOrderId(),\n paypal_order_id: this.paypalOrderId(),\n payment_source: this.paymentSource\n };\n\n if (this.cardBin()) {\n data['additional_data']['cardBin'] = this.cardBin();\n }\n\n if (this.holderName()) {\n data['additional_data']['holderName'] = this.holderName();\n }\n\n if (this.cardLast4()) {\n data['additional_data']['cardLast4'] = this.cardLast4();\n }\n\n if (this.cardExpiryMonth()) {\n data['additional_data']['cardExpiryMonth'] = this.cardExpiryMonth();\n }\n\n if (this.cardExpiryYear()) {\n data['additional_data']['cardExpiryYear'] = this.cardExpiryYear();\n }\n\n this.vaultEnabler.visitAdditionalData(data);\n return data;\n },\n\n /**\n * Get payment related data.\n *\n * @return {Object}\n */\n getPaymentData: function () {\n const paymentData = {\n vault: this.isCommerceVaultEnabled && this.checkShouldCardBeVaulted(),\n cardholderName: this.billingAddress().firstname + ' ' + this.billingAddress().lastname,\n billingAddress: {\n streetAddress: this.billingAddress().street[0],\n extendedAddress: this.billingAddress().street[1],\n region: this.billingAddress().region,\n locality: this.billingAddress().city,\n postalCode: this.billingAddress().postcode,\n countryCodeAlpha2: this.billingAddress().countryId\n }\n };\n\n if (this.threeDSMode) {\n paymentData.contingencies = [this.threeDSMode];\n }\n\n return paymentData;\n },\n\n /** @inheritdoc */\n afterRender: function () {\n this.$form = $('#' + this.formId);\n\n this.hostedFields.sdkLoaded.then(function () {\n this.isAvailable(this.hostedFields.isEligible());\n\n if (this.isAvailable()) {\n this.hostedFields.render()\n .then(this.afterHostedFieldsRender.bind(this));\n }\n }.bind(this)).catch(function () {\n this.isAvailable(false);\n }.bind(this)).finally(function () {\n this.isFormRendered(true);\n }.bind(this));\n },\n\n /**\n * Bind events after hostedFields rendered.\n *\n * @param {Object} hostedFields\n */\n afterHostedFieldsRender: function (hostedFields) {\n this.processAvailableCards(hostedFields.getCardTypes());\n hostedFields.on('cardTypeChange', this.onCardTypeChange.bind(this, hostedFields));\n hostedFields.on('validityChange', this.onValidityChange.bind(this, hostedFields));\n hostedFields.on('blur', this.validateField.bind(this, hostedFields));\n hostedFields.on('inputSubmitRequest', function (e) {\n this.validateField(hostedFields, e);\n this.submitForm(hostedFields);\n }.bind(this));\n this.$form.off('submit');\n this.$form.on('submit', function (e) {\n e.preventDefault();\n\n this.submitForm(hostedFields);\n }.bind(this));\n },\n\n /**\n * Filter eligible cards, convert to internal codes and set to available cards.\n *\n * @param {Object} cardTypes\n */\n processAvailableCards: function (cardTypes) {\n const cards = _.keys(cardTypes).sort(),\n eligibleCards = _.chain(cards)\n .filter(function (ccCode) {\n return cardTypes[ccCode].eligible;\n })\n .map(function (ccCode) {\n return _.findKey(this.cards, function (val) {\n return val.eligibilityCode === ccCode;\n }) || ccCode;\n }, this)\n .value();\n\n this.availableCards(eligibleCards);\n },\n\n /**\n * Validity change handler.\n *\n * @param {Object} hostedFields\n * @param {Object} event\n */\n onValidityChange: function (hostedFields, event) {\n const invalidFields = _.where(event.fields, {\n isValid: false\n });\n\n this.isFormValid(!invalidFields.length);\n this.isFormValid() && this.invalidFields([]);\n },\n\n /**\n * Check if field is valid.\n *\n * @param {String} fieldName\n * @return {Boolean}\n */\n isFieldValid: function (fieldName) {\n return !this.invalidFields.findWhere({\n name: fieldName\n });\n },\n\n /**\n * Get error message for field.\n *\n * @param {String} fieldName\n * @return {String}\n */\n getFieldErrorMessage: function (fieldName) {\n return !this.isFieldValid(fieldName) ? this.invalidFields.findWhere({\n name: fieldName\n }).message : '';\n },\n\n /**\n * Validate credit card field.\n *\n * @param {Object} hostedFields\n * @param {Object} event\n */\n validateField: function (hostedFields, event) {\n var fieldName = event.emittedBy,\n fieldValid = event.fields[fieldName].isValid,\n isEmpty = event.fields[fieldName].isEmpty,\n invalidFields = _.filter(this.invalidFields(), function (field) {\n return field.name !== fieldName;\n });\n\n if (!fieldValid) {\n invalidFields.push({\n name: fieldName,\n message: isEmpty ? this.emptyErrorMessage : this.fields[fieldName].errorMessage\n });\n }\n\n this.invalidFields(invalidFields);\n },\n\n /**\n * Card type changes handler.\n *\n * @param {Object} hostedFields\n * @param {Object} event\n */\n onCardTypeChange: function (hostedFields, event) {\n var code = '';\n\n if (event.cards.length === 1) {\n code = _.findKey(this.cards, function (val) {\n return val.typeCode === event.cards[0].type;\n });\n }\n\n this.ccType(code);\n },\n\n /**\n * Form submit handler\n *\n * @param {Object} hostedFields\n */\n submitForm: function (hostedFields) {\n if (this.canProceedWithOrder()) {\n loader.startLoader();\n hostedFields.submit(\n this.getPaymentData()\n ).then(this.getOrderCardDetails).then(this.onSuccess).catch(this.onError).finally(loader.stopLoader);\n }\n },\n\n /**\n * Before order created.\n *\n * @return {Promise}\n */\n beforeCreateOrder: function () {\n return new Promise(function (resolve, reject) {\n return setBillingAddressAction(globalMessageList).done(resolve).fail(reject);\n });\n },\n\n getOrderCardDetails: function (response) {\n if (!this.requiresCardDetails) {\n return Promise.resolve(response);\n }\n\n return fetch(`${this.getOrderDetailsUrl}`, {\n method: 'GET'\n }).then(function (res) {\n return res.json();\n }).then(function (data) {\n if (data.response['is_successful'] && data.response['paypal-order']) {\n const order = data.response['paypal-order'];\n\n this.cardBin(order?.payment_source_details?.card?.bin_details?.bin);\n this.holderName(order?.payment_source_details?.card?.name);\n this.cardLast4(order?.payment_source_details?.card?.last_digits);\n this.cardExpiryMonth(order?.payment_source_details?.card?.card_expiry_month);\n this.cardExpiryYear(order?.payment_source_details?.card?.card_expiry_year);\n }\n\n return response;\n }.bind(this)).catch(function (err) {\n console.log(\n 'Could not get order details. Proceeding with order placement without card details',\n err\n );\n return response;\n });\n },\n\n /**\n * Success callback for transaction.\n *\n * @param {Object} response\n */\n onSuccess: function (response) {\n if (!this.threeDSMode) {\n this.placeOrder();\n return;\n }\n\n if (response.liabilityShift === 'POSSIBLE' || response.liabilityShift === undefined) {\n this.placeOrder();\n } else {\n this.onError(new ResponseError(this.paymentMethodValidationError));\n }\n },\n\n /**\n * On PayPal order creation success.\n *\n * @param {Object} order\n */\n onOrderSuccess: function (order) {\n this.paymentsOrderId(order['mp_order_id']);\n this.paypalOrderId(order.id);\n },\n\n /**\n * Error callback for transaction.\n */\n onError: function (error) {\n var message = this.generalErrorMessage;\n\n if (error instanceof ResponseError) {\n message = error.message;\n this.reRender();\n } else if (error['debug_id']) {\n message = this.paymentMethodValidationError;\n }\n\n this.messageContainer.addErrorMessage({\n message: message\n });\n\n if (error instanceof Error) {\n console.log(error.toString());\n } else {\n console.log('Error' + JSON.stringify(error));\n }\n },\n\n /**\n * Re-render hosted fields in case of order creation error.\n */\n reRender: function () {\n this.hostedFields.instance.teardown().then(function () {\n this.hostedFields.destroy();\n this.isFormValid(false);\n this.ccType('');\n this.invalidFields([]);\n this.initHostedFields();\n this.afterRender();\n }.bind(this));\n },\n\n /**\n * Place order\n */\n placeOrderClick: function () {\n if (this.isPlaceOrderActionAllowed() === true) {\n $('#' + this.formId).trigger('submit');\n }\n },\n\n /**\n * Check if customer checks the \"Save for later\" box upon checkout\n *\n * @returns {*}\n */\n checkShouldCardBeVaulted: function () {\n const checked = this.vaultEnabler.isActivePaymentTokenEnabler();\n\n this.shouldCardBeVaulted(checked);\n return checked;\n },\n\n canProceedWithOrder: function () {\n return this.validate() && additionalValidators.validate() && this.isFormValid() && this.isPlaceOrderActionAllowed();\n }\n\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/method-renderer/smart-buttons.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'Magento_Checkout/js/view/payment/default',\n 'jquery',\n 'underscore',\n 'mageUtils',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Checkout/js/model/full-screen-loader',\n 'mage/translate',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/smart-buttons',\n 'Magento_PaymentServicesPaypal/js/view/payment/message',\n 'Magento_Checkout/js/model/payment/additional-validators',\n 'Magento_Checkout/js/action/set-billing-address',\n 'Magento_Ui/js/model/messageList',\n 'uiRegistry',\n 'Magento_Customer/js/customer-data'\n], function (\n Component,\n $,\n _,\n utils,\n quote,\n fullScreenLoader,\n $t,\n SmartButtons,\n Message,\n additionalValidators,\n setBillingAddressAction,\n globalMessageList,\n registry,\n customerData\n) {\n 'use strict';\n\n var refreshCustomerData = function (url) {\n // Trigger ajaxComplete event to update customer data\n customerData.onAjaxComplete(\n {},\n {\n type: 'POST',\n url: url,\n }\n );\n }\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalCheckoutButtons',\n buttonsContainerId: 'smart-buttons-${ $.uid }',\n payLaterMessageContainerId: 'pay-later-message-${ $.uid }',\n template: 'Magento_PaymentServicesPaypal/payment/smart-buttons',\n isAvailable: false,\n isButtonsRendered: false,\n grandTotalAmount: null,\n paymentsOrderId: null,\n paypalOrderId: null,\n requestProcessingError: $t('Error happened when processing the request. Please try again later.'),\n notEligibleErrorMessage: $t('This payment option is currently unavailable.'),\n paymentTypeIconUrl: window.checkoutConfig.payment['payment_services_paypal_smart_buttons'].paymentTypeIconUrl, // eslint-disable-line max-len\n paymentTypeIconTitle: $t('Pay with PayPal')\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config) {\n _.bindAll(this, 'onClick', 'onInit', 'catchError', 'beforeCreateOrder', 'afterCreateOrder');\n config.uid = utils.uniqueid();\n this._super();\n this.initSmartButtons();\n this.initMessage();\n quote.totals.subscribe(function (totals) {\n this.grandTotalAmount(totals['base_grand_total']);\n this.message.updateAmount(totals['base_grand_total']);\n }.bind(this));\n\n return this;\n },\n\n /**\n * Initialize observables\n *\n * @returns {Component} Chainable.\n */\n initObservable: function () {\n this._super().observe('grandTotalAmount isAvailable isButtonsRendered');\n this.grandTotalAmount(quote.totals()['base_grand_total']);\n\n return this;\n },\n\n /**\n * Create instance of smart buttons.\n */\n initSmartButtons: function () {\n this.buttons = new SmartButtons({\n sdkNamespace: this.sdkNamespace,\n scriptParams: window.checkoutConfig.payment['payment_services_paypal_smart_buttons'].sdkParams,\n createOrderUrl: window.checkoutConfig.payment['payment_services_paypal_smart_buttons'].createOrderUrl,\n styles: window.checkoutConfig.payment['payment_services_paypal_smart_buttons'].buttonStyles,\n onInit: this.onInit,\n onClick: this.onClick,\n beforeCreateOrder: this.beforeCreateOrder,\n afterCreateOrder: this.afterCreateOrder,\n catchCreateOrder: this.catchError,\n onApprove: function () {\n this.placeOrder();\n }.bind(this),\n onError: this.catchError\n });\n },\n\n /**\n * Initialize message component\n */\n initMessage: function () {\n this.message = new Message({\n scriptParams: window.checkoutConfig.payment['payment_services_paypal_smart_buttons'].sdkParams,\n element: this.element,\n renderContainer: '#' + this.payLaterMessageContainerId,\n styles: window.checkoutConfig.payment['payment_services_paypal_smart_buttons'].messageStyles,\n placement: 'payment',\n amount: this.grandTotalAmount()\n });\n },\n\n /**\n * Get method code\n *\n * @return {String}\n */\n getCode: function () {\n return 'payment_services_paypal_smart_buttons';\n },\n\n /**\n * Get method data\n *\n * @return {Object}\n */\n getData: function () {\n return {\n 'method': this.item.method,\n 'additional_data': {\n 'payments_order_id': this.paymentsOrderId,\n 'paypal_order_id': this.paypalOrderId,\n 'payment_source': this.buttons.paymentSource\n }\n };\n },\n\n /**\n * Render buttons\n */\n afterRender: function () {\n this.buttons.sdkLoaded.then(function () {\n this.buttons.render('#' + this.buttonsContainerId);\n this.renderMessage();\n this.isAvailable(!!this.buttons.instance && this.buttons.instance.isEligible());\n }.bind(this)).catch(function () {\n this.isAvailable(false);\n\n return this.buttons;\n }.bind(this)).finally(function () {\n this.isButtonsRendered(true);\n }.bind(this));\n },\n\n /**\n * Render message\n */\n renderMessage: function () {\n if (window.checkoutConfig.payment['payment_services_paypal_smart_buttons'].canDisplayMessage) {\n this.message.render();\n }\n },\n\n /**\n * Enable/disable buttons.\n *\n * @param {Object} data\n * @param {Object} actions\n */\n onInit: function (data, actions) {\n if (!this.isPlaceOrderActionAllowed()) {\n actions.disable();\n }\n\n this.isPlaceOrderActionAllowed.subscribe(function (isAllowed) {\n if (isAllowed) {\n actions.enable();\n } else {\n actions.disable();\n }\n });\n },\n\n /**\n * @inheritdoc\n */\n validate: function () {\n var isShippingValid = true,\n source, shippingAddress;\n\n if (!this._super()) {\n return false;\n }\n source = registry.get('checkoutProvider');\n shippingAddress = registry.get('index = shippingAddress');\n\n if (source && shippingAddress) {\n source.set('params.invalid', false);\n if (quote.billingAddress() === null) {\n this.triggerBillingValidation(source);\n }\n\n // skip shipping validation if quote is virtual or in-store pickup\n if (!quote.isVirtual() && !quote.shippingMethod()['method_code'] === 'pickup') {\n isShippingValid = shippingAddress.validateShippingInformation();\n }\n\n return isShippingValid && !source.get('params.invalid');\n }\n\n return true;\n },\n\n /**\n * Trigger billing address validation\n *\n * @param {Object} source\n */\n triggerBillingValidation: function (source) {\n var dataScope = `billingAddress${ window.checkoutConfig.displayBillingOnPaymentMethod ?\n this.getCode() : 'shared'}`;\n\n source.trigger(`${ dataScope }.data.validate`);\n\n if (source.get(`${dataScope}.custom_attributes`)) {\n source.trigger(`${dataScope}.custom_attributes.data.validate`);\n }\n },\n\n /**\n * Validate form onClick\n *\n * @param {Object} data\n * @param {Object} actions\n * @return {*}\n */\n onClick: function (data, actions) {\n if (this.validate() && additionalValidators.validate()) {\n return actions.resolve();\n }\n\n return actions.reject();\n },\n\n /**\n * Before order created.\n *\n * @return {Promise}\n */\n beforeCreateOrder: function () {\n return new Promise(function (resolve, reject) {\n setBillingAddressAction(globalMessageList).done(resolve.bind(null, null)).fail(reject);\n });\n },\n\n /**\n * After order created.\n *\n * @param {Object} data\n * @return {String}\n */\n afterCreateOrder: function (data) {\n if (data.response['paypal-order'] && data.response['paypal-order']['mp_order_id']) {\n refreshCustomerData(window.checkoutConfig.payment[this.getCode()].createOrderUrl);\n\n this.paymentsOrderId = data.response['paypal-order']['mp_order_id'];\n this.paypalOrderId = data.response['paypal-order'].id;\n\n return this.paypalOrderId;\n }\n\n throw new Error();\n },\n\n /**\n * Catch error.\n *\n * @param {Error} error\n */\n catchError: function (error) {\n this.messageContainer.addErrorMessage({\n message: this.requestProcessingError\n });\n console.log('Error: ', error.message);\n }\n\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/method-renderer/vault.js":"/**\n * Copyright \u00a9 2013-2017 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'mage/translate',\n 'Magento_Vault/js/view/payment/method-renderer/vault',\n 'Magento_Checkout/js/model/full-screen-loader',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error'\n], function (\n $t,\n VaultComponent,\n loader,\n ResponseError\n) {\n 'use strict';\n\n return VaultComponent.extend({\n defaults: {\n template: 'Magento_PaymentServicesPaypal/payment/vault',\n paymentSource: 'vault',\n paypalOrderId: null,\n paymentsOrderId: null,\n generalErrorMessage: $t('An error occurred. Refresh the page and try again.'),\n paymentMethodValidationError: $t('Your payment was not successful. Try again.')\n },\n\n /**\n * Get card brand\n * @returns {String}\n */\n getCardBrand: function () {\n return this.mapCardBrand(this.details.brand);\n },\n\n /**\n * Map the credit card brand received from PayPal to the Commerce standard\n * @param payPalCardBrand\n * @returns {*}\n */\n mapCardBrand: function (payPalCardBrand) {\n const cardBrandMapping = {\n AMEX: 'AE',\n DISCOVER: 'DI',\n DINERS: 'DN',\n ELO: 'ELO',\n HIPER: 'HC',\n JCB: 'JCB',\n MAESTRO: 'MI',\n MASTER_CARD: 'MC',\n MASTERCARD: 'MC',\n VISA: 'VI'\n };\n\n return cardBrandMapping[payPalCardBrand];\n },\n\n /**\n * Get last 4 digits of card\n * @returns {String}\n */\n getMaskedCard: function () {\n return this.details.maskedCC;\n },\n\n /**\n * Get PayPal order ID\n */\n getData: function () {\n let data = this._super();\n\n data['additional_data']['paypal_order_id'] = this.paypalOrderId;\n data['additional_data']['payments_order_id'] = this.paymentsOrderId;\n data['additional_data']['public_hash'] = this.publicHash;\n data['additional_data']['payment_source'] = this.paymentSource;\n return data;\n },\n\n /**\n * Place order\n */\n onPlaceOrder: function () {\n loader.startLoader();\n this.createOrder()\n .then(function (order) {\n this.onOrderSuccess(order);\n }.bind(this))\n .then(function () {\n this.placeOrder();\n }.bind(this))\n .catch(this.onError.bind(this))\n .finally(loader.stopLoader);\n },\n\n /**\n * Create PayPal order\n * @returns {Promise<any>}\n */\n createOrder: function () {\n var orderData = new FormData();\n\n orderData.append('payment_source', this.paymentSource);\n\n return fetch(this.createOrderUrl, {\n method: 'POST',\n headers: {},\n body: orderData,\n credentials: 'same-origin'\n }).then(function (res) {\n return res.json();\n }).then(function (data) {\n if (data.response['is_successful']) {\n return data.response['paypal-order'];\n }\n });\n },\n\n /**\n * populate PayPal order ID and trigger Commerce order flow\n * @param order\n */\n onOrderSuccess: function (order) {\n this.paypalOrderId = order['id'];\n this.paymentsOrderId = order['mp_order_id'];\n },\n\n /**\n * handle payment error\n * @param error\n */\n onError: function (error) {\n var message = this.generalErrorMessage;\n\n if (error instanceof ResponseError) {\n message = error.message;\n } else if (error['debug_id']) {\n message = this.paymentMethodValidationError;\n }\n\n this.messageContainer.addErrorMessage({\n message: message\n });\n console.log(error['debug_id'] ? 'Error' + JSON.stringify(error) : error.toString());\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/method-renderer/apple-pay.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'Magento_Checkout/js/view/payment/default',\n 'jquery',\n 'underscore',\n 'mageUtils',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Checkout/js/model/full-screen-loader',\n 'mage/translate',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/apple-pay',\n 'Magento_Checkout/js/model/payment/additional-validators',\n 'Magento_Checkout/js/action/set-billing-address',\n 'Magento_Ui/js/model/messageList',\n 'Magento_Customer/js/customer-data'\n], function (\n Component,\n $,\n _,\n utils,\n quote,\n fullScreenLoader,\n $t,\n ApplePayButton,\n additionalValidators,\n setBillingAddressAction,\n globalMessageList,\n customerData\n) {\n 'use strict';\n\n var refreshCustomerData = function (url) {\n // Trigger ajaxComplete event to update customer data\n customerData.onAjaxComplete(\n {},\n {\n type: 'POST',\n url: url,\n }\n );\n }\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypalApplePay',\n fundingSource: 'applepay',\n buttonContainerId: 'apple-pay-${ $.uid }',\n template: 'Magento_PaymentServicesPaypal/payment/apple-pay',\n isAvailable: false,\n isButtonRendered: false,\n grandTotalAmount: null,\n paymentsOrderId: null,\n paypalOrderId: null,\n paymentTypeIconTitle: $t('Pay with Apple Pay'),\n requestProcessingError: $t('Error happened when processing the request. Please try again later.'),\n notEligibleErrorMessage: $t('This payment option is currently unavailable.'),\n paymentTypeIconUrl: window.checkoutConfig.payment['payment_services_paypal_apple_pay'].paymentTypeIconUrl\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config) {\n _.bindAll(this, 'catchError', 'beforeCreateOrder', 'afterCreateOrder', 'placeOrder', 'onClick');\n config.uid = utils.uniqueid();\n this._super();\n this.initApplePayButton();\n\n return this;\n },\n\n /**\n * Initialize observables\n *\n * @returns {Component} Chainable.\n */\n initObservable: function () {\n this._super().observe('grandTotalAmount isAvailable isButtonRendered');\n this.grandTotalAmount(quote.totals()['base_grand_total']);\n\n return this;\n },\n\n /**\n * Create instance of smart buttons.\n */\n initApplePayButton: function () {\n this.applePayButton = new ApplePayButton({\n scriptParams: window.checkoutConfig.payment[this.getCode()].sdkParams,\n createOrderUrl: window.checkoutConfig.payment[this.getCode()].createOrderUrl,\n estimateShippingMethodsWhenLoggedInUrl: window.checkoutConfig.payment[this.getCode()].estimateShippingMethodsWhenLoggedInUrl,\n estimateShippingMethodsWhenGuestUrl: window.checkoutConfig.payment[this.getCode()].estimateShippingMethodsWhenGuestUrl,\n shippingInformationWhenLoggedInUrl: window.checkoutConfig.payment[this.getCode()].shippingInformationWhenLoggedInUrl,\n shippingInformationWhenGuestUrl: window.checkoutConfig.payment[this.getCode()].shippingInformationWhenGuestUrl,\n updatePayPalOrderUrl: window.checkoutConfig.payment[this.getCode()].updatePayPalOrderUrl,\n countriesUrl: window.checkoutConfig.payment[this.getCode()].countriesUrl,\n onClick: this.onClick,\n beforeCreateOrder: this.beforeCreateOrder,\n afterCreateOrder: this.afterCreateOrder,\n catchCreateOrder: this.catchError,\n onError: this.catchError,\n buttonContainerId: this.buttonContainerId,\n onApprove: this.placeOrder,\n styles: window.checkoutConfig.payment[this.getCode()].buttonStyles\n });\n },\n\n /**\n * Get method code\n *\n * @return {String}\n */\n getCode: function () {\n return 'payment_services_paypal_apple_pay';\n },\n\n /**\n * Get method data\n *\n * @return {Object}\n */\n getData: function () {\n return {\n 'method': this.item.method,\n 'additional_data': {\n 'payments_order_id': this.paymentsOrderId,\n 'paypal_order_id': this.paypalOrderId,\n 'payment_source': this.fundingSource\n }\n };\n },\n\n /**\n * Render buttons\n */\n afterRender: function () {\n this.applePayButton.sdkLoaded\n .then(this.applePayButton.initAppleSDK)\n .then(function () {\n this.isAvailable(true);\n this.isButtonRendered(true);\n }.bind(this)\n ).catch(function () {\n this.isAvailable(false);\n }.bind(this)).finally(function () {\n this.isButtonRendered(true);\n }.bind(this));\n },\n\n /**\n * Enable/disable buttons.\n *\n * @param {Object} data\n * @param {Object} actions\n */\n onInit: function (data, actions) {\n if (!this.isPlaceOrderActionAllowed()) {\n actions.disable();\n }\n\n this.isPlaceOrderActionAllowed.subscribe(function (isAllowed) {\n if (isAllowed) {\n actions.enable();\n } else {\n actions.disable();\n }\n });\n },\n\n /**\n * Validate form onClick\n *\n * @param {Object} data\n * @param {Object} actions\n * @return {*}\n */\n onClick: function (data, actions) {\n this.applePayButton.showLoaderAsync(true)\n .then(() => {\n this.applePayButton.createOrder();\n })\n .then(() => {\n refreshCustomerData(window.checkoutConfig.payment[this.getCode()].createOrderUrl);\n })\n .catch(error => {\n this.catchError(error);\n });\n },\n\n /**\n * Before order created.\n *\n * @return {Promise}\n */\n beforeCreateOrder: function () {\n if (this.validate() && this.isPlaceOrderActionAllowed() && additionalValidators.validate()) {\n return new Promise(function (resolve, reject) {\n setBillingAddressAction(globalMessageList).done(resolve.bind(null, null)).fail(reject);\n });\n } else {\n throw {message: 'before create order validation failed', hidden: true};\n }\n },\n\n /**\n * After order created.\n *\n * @param {Object} data\n * @return {String}\n */\n afterCreateOrder: function (data) {\n if (data.response['paypal-order'] && data.response['paypal-order']['mp_order_id']) {\n this.paymentsOrderId = data.response['paypal-order']['mp_order_id'];\n this.paypalOrderId = data.response['paypal-order'].id;\n\n this.applePayButton.showPopup(data, quote);\n\n return this.paypalOrderId;\n }\n\n throw new Error();\n },\n\n /**\n * Catch error.\n *\n * @param {Error} error\n */\n catchError: function (error) {\n this.messageContainer.addErrorMessage({\n message: this.requestProcessingError\n });\n console.log('Error: ', error.message);\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/method-renderer/google-pay.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'Magento_Checkout/js/view/payment/default',\n 'jquery',\n 'underscore',\n 'mageUtils',\n 'Magento_Checkout/js/model/quote',\n 'mage/translate',\n 'Magento_PaymentServicesPaypal/js/view/payment/methods/google-pay',\n 'Magento_Checkout/js/model/payment/additional-validators',\n 'Magento_Checkout/js/action/set-billing-address',\n 'Magento_Ui/js/model/messageList',\n 'uiRegistry',\n 'Magento_Customer/js/customer-data'\n], function (\n Component,\n $,\n _,\n utils,\n quote,\n $t,\n GooglePayButton,\n additionalValidators,\n setBillingAddressAction,\n globalMessageList,\n registry,\n customerData\n) {\n 'use strict';\n\n var refreshCustomerData = function (url) {\n // Trigger ajaxComplete event to update customer data\n customerData.onAjaxComplete(\n {},\n {\n type: 'POST',\n url: url,\n }\n );\n }\n\n return Component.extend({\n defaults: {\n buttonContainerId: 'google-pay-${ $.uid }',\n template: 'Magento_PaymentServicesPaypal/payment/google-pay',\n isAvailable: false,\n isButtonRendered: false,\n paymentsOrderId: null,\n paypalOrderId: null,\n paymentTypeIconTitle: $t('Pay with Google Pay'),\n requestProcessingError: $t('Error happened when processing the request. Please try again later.'),\n notEligibleErrorMessage: $t('This payment option is currently unavailable.'),\n paymentTypeIconUrl: window.checkoutConfig.payment['payment_services_paypal_google_pay'].paymentTypeIconUrl,\n fundingSource: window.checkoutConfig.payment['payment_services_paypal_google_pay'].paymentSource\n },\n\n /**\n * @inheritdoc\n */\n initialize: function (config) {\n _.bindAll(this, 'catchError', 'beforeCreateOrder', 'afterCreateOrder', 'placeOrder', 'onClick');\n config.uid = utils.uniqueid();\n this._super();\n this.initGooglePayButton();\n\n return this;\n },\n\n /**\n * Initialize observables\n *\n * @returns {Component} Chainable.\n */\n initObservable: function () {\n this._super().observe('isAvailable isButtonRendered');\n\n return this;\n },\n\n initGooglePayButton: function () {\n this.googlePayButton = new GooglePayButton({\n scriptParams: window.checkoutConfig.payment[this.getCode()].sdkParams,\n createOrderUrl: window.checkoutConfig.payment[this.getCode()].createOrderUrl,\n onClick: this.onClick,\n beforeCreateOrder: this.beforeCreateOrder,\n afterCreateOrder: this.afterCreateOrder,\n catchCreateOrder: this.catchError,\n onError: this.catchError,\n buttonContainerId: this.buttonContainerId,\n onApprove: this.placeOrder,\n styles: window.checkoutConfig.payment[this.getCode()].styles,\n mode: window.checkoutConfig.payment[this.getCode()].mode,\n shippingAddressRequired: false\n });\n\n if (!this.isPlaceOrderActionAllowed()) {\n this.googlePayButton.disableButton();\n }\n\n this.isPlaceOrderActionAllowed.subscribe(function (isAllowed) {\n if (isAllowed) {\n this.googlePayButton.enableButton();\n } else {\n this.googlePayButton.disableButton();\n }\n }.bind(this));\n },\n\n /**\n * Get method code\n *\n * @return {String}\n */\n getCode: function () {\n return 'payment_services_paypal_google_pay';\n },\n\n /**\n * Get method data\n *\n * @return {Object}\n */\n getData: function () {\n return {\n 'method': this.item.method,\n 'additional_data': {\n 'payments_order_id': this.paymentsOrderId,\n 'paypal_order_id': this.paypalOrderId,\n 'payment_source': this.fundingSource\n }\n };\n },\n\n onClick: function () {\n this.googlePayButton.showLoaderAsync(true)\n .then(() => {\n return this.googlePayButton.createOrder();\n })\n .then(() => {\n refreshCustomerData(window.checkoutConfig.payment[this.getCode()].createOrderUrl);\n })\n .catch(error => {\n this.catchError(error);\n });\n },\n\n /**\n * Render buttons\n */\n afterRender: function () {\n this.googlePayButton.sdkLoaded\n .then(function () {\n this.googlePayButton.initGoogleSDK()\n .then(function () {\n this.isAvailable(this.googlePayButton.isEligible());\n }.bind(this)).catch(function () {\n this.isAvailable(false);\n }.bind(this)).finally(function () {\n this.isButtonRendered(true);\n }.bind(this)\n );\n }.bind(this));\n },\n\n /**\n * Before order created.\n *\n * @return {Promise}\n */\n beforeCreateOrder: function () {\n if (this.validate() && this.isPlaceOrderActionAllowed() && additionalValidators.validate()) {\n setBillingAddressAction(globalMessageList)\n .fail(function () {\n throw {message: 'Failed to set billing address'};\n });\n } else {\n throw {message: 'before create order validation failed', hidden: true};\n }\n },\n\n /**\n * @inheritdoc\n */\n validate: function () {\n var isShippingValid = true,\n source, shippingAddress;\n\n if (!this._super()) {\n return false;\n }\n source = registry.get('checkoutProvider');\n shippingAddress = registry.get('index = shippingAddress');\n\n if (source && shippingAddress) {\n source.set('params.invalid', false);\n if (quote.billingAddress() === null) {\n this.triggerBillingValidation(source);\n }\n\n // skip shipping validation if quote is virtual or in-store pickup\n if (!quote.isVirtual() && !quote.shippingMethod()['method_code'] === 'pickup') {\n isShippingValid = shippingAddress.validateShippingInformation();\n }\n\n return isShippingValid && !source.get('params.invalid');\n }\n\n return true;\n },\n\n /**\n * Trigger billing address validation\n *\n * @param {Object} source\n */\n triggerBillingValidation: function (source) {\n var dataScope = `billingAddress${ window.checkoutConfig.displayBillingOnPaymentMethod ?\n this.getCode() : 'shared'}`;\n\n source.trigger(`${ dataScope }.data.validate`);\n\n if (source.get(`${dataScope}.custom_attributes`)) {\n source.trigger(`${dataScope}.custom_attributes.data.validate`);\n }\n },\n\n /**\n * After order created.\n *\n * @param {Object} data\n * @return {String}\n */\n afterCreateOrder: function (data) {\n if (data.response['paypal-order'] && data.response['paypal-order']['mp_order_id']) {\n this.paymentsOrderId = data.response['paypal-order']['mp_order_id'];\n this.paypalOrderId = data.response['paypal-order'].id;\n\n let displayItems = [],\n subTotal = this.getTotalsSegment('subtotal'),\n shippingTotal = this.getTotalsSegment('shipping'),\n taxTotal = this.getTotalsSegment('tax'),\n discountTotal = this.getTotalsSegment('discount');\n\n if (subTotal != null) {\n displayItems.push(\n {\n label: $t('Subtotal'),\n type: 'SUBTOTAL',\n price: subTotal.value.toString()\n }\n );\n }\n if (taxTotal != null) {\n displayItems.push(\n {\n label: $t('Tax'),\n type: 'TAX',\n price: taxTotal.value.toString()\n }\n );\n }\n\n if (shippingTotal != null) {\n displayItems.push(\n {\n label: $t('Shipping'),\n type: 'LINE_ITEM',\n price: shippingTotal.value.toString()\n }\n );\n }\n\n if (discountTotal != null) {\n displayItems.push(\n {\n label: $t('Discount'),\n type: 'LINE_ITEM',\n price: discountTotal.value.toString()\n }\n );\n }\n\n this.googlePayButton.showPopup({\n displayItems: displayItems,\n currencyCode: quote.totals()['base_currency_code'].toString(),\n totalPriceStatus: 'FINAL',\n totalPrice: quote.totals()['base_grand_total'].toString(),\n totalPriceLabel: $t('Total')\n });\n\n return this.paypalOrderId;\n }\n\n throw new Error();\n },\n\n /**\n * Catch error.\n *\n * @param {Error} error\n */\n catchError: function (error) {\n if (error.hidden === undefined || !error.hidden) {\n this.messageContainer.addErrorMessage({\n message: this.requestProcessingError\n });\n }\n\n this.googlePayButton.showLoader(false);\n\n console.log('Error: ', error);\n },\n\n getTotalsSegment: function (code) {\n var segment = null;\n\n if (!('total_segments' in quote.totals())) {\n return null;\n }\n\n quote.totals()['total_segments'].forEach(function (s) {\n if (s.code === code) {\n segment = s;\n }\n });\n\n return segment;\n }\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/methods/hosted-fields.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'underscore',\n 'uiComponent',\n 'mage/translate',\n 'Magento_PaymentServicesPaypal/js/view/errors/response-error',\n 'scriptLoader'\n], function (_, Class, $t, ResponseError, loadSdkScript) {\n 'use strict';\n\n return Class.extend({\n defaults: {\n sdkNamespace: 'paypal',\n paypal: null,\n formId: 'hosted-fields-form',\n instance: undefined,\n createOrderUrl: null,\n orderCreateErrorMessage: {\n default: $t('Failed to place order. Try again or refresh the page if that does not resolve the issue.'), // eslint-disable-line max-len,\n //TODO: Update messages\n 'POSTAL_CODE_REQUIRED': $t('Postal code is required.'),\n 'CITY_REQUIRED': $t('City is required.')\n },\n styles: {\n input: {\n color: '#ccc',\n 'font-family': '\"Open Sans\",\"Helvetica Neue\",Helvetica,Arial,sans-serif',\n 'font-size': '16px',\n 'font-weight': '400'\n },\n ':focus': {\n color: '#333'\n },\n '.valid': {\n color: '#333'\n }\n },\n fields: {\n number: {\n class: 'number',\n selector: '#${ $.formId } .${ $.fields.number.class }',\n placeholder: ''\n },\n expirationDate: {\n class: 'expiration-date',\n selector: '#${ $.formId } .${ $.fields.expirationDate.class }',\n placeholder: 'MM/YY'\n },\n cvv: {\n class: 'cvv',\n selector: '#${ $.formId } .${ $.fields.cvv.class }',\n placeholder: ''\n }\n },\n scriptParams: [],\n sdkLoaded: null,\n shouldCardBeVaulted: false\n },\n\n /** @inheritdoc */\n initialize: function (config) {\n _.bindAll(this, 'createOrder');\n\n if (config.fields) {\n this.constructor.defaults.fields = config.fields;\n }\n this._super();\n this.sdkLoaded = loadSdkScript(this.scriptParams, this.sdkNamespace).then(function (sdkScript) {\n this.paypal = sdkScript;\n }.bind(this));\n return this;\n },\n\n /** @inheritdoc */\n initObservable: function () {\n this._super()\n .observe('shouldCardBeVaulted');\n\n return this;\n },\n\n /**\n * Check if eligible\n *\n * @return {Boolean}\n */\n isEligible: function () {\n return typeof this.paypal !== 'undefined' &&\n this.paypal.HostedFields &&\n this.paypal.HostedFields.isEligible();\n },\n\n /**\n * Render fields.\n *\n * @return {*}\n */\n render: function () {\n return this.paypal.HostedFields.render({\n createOrder: this.createOrder,\n styles: this.styles,\n fields: this.fields\n }).then(function (instance) {\n this.instance = instance;\n\n return instance;\n }.bind(this));\n },\n\n /**\n * Calls before create order.\n *\n * @return {Promise}\n */\n beforeCreateOrder: function () {\n return Promise.resolve();\n },\n\n /**\n * Create order in payment service / PayPal\n *\n * @returns {Promise<any>}\n */\n createOrder: function () {\n return this.beforeCreateOrder()\n .then(function () {\n const shouldCardBeVaulted = this.shouldCardBeVaulted(),\n orderData = new FormData();\n\n orderData.append('payment_source', this.paymentSource);\n\n return fetch(`${this.createOrderUrl}?vault=${shouldCardBeVaulted}`, {\n method: 'POST',\n headers: {},\n body: orderData\n });\n }.bind(this)).then(function (res) {\n return res.json();\n }).then(function (data) {\n if (data.response['is_successful']) {\n this.onOrderSuccess(data.response['paypal-order']);\n } else {\n throw new ResponseError(\n this.orderCreateErrorMessage[data.response.message] || this.orderCreateErrorMessage.default\n );\n }\n\n return data.response['paypal-order'].id;\n }.bind(this)).catch(function (error) {\n if (error instanceof ResponseError) {\n throw error;\n }\n throw new ResponseError(this.orderCreateErrorMessage.default);\n }.bind(this));\n },\n\n /**\n * Customizable handler for order creation.\n */\n onOrderSuccess: function () {}\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/methods/smart-buttons.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'jquery',\n 'underscore',\n 'uiComponent',\n 'scriptLoader',\n 'mage/cookies'\n], function ($, _, Component, loadSdkScript) {\n 'use strict';\n\n /**\n * Create order request.\n *\n * @param {String} url\n * @param {Object} payPalOrderData\n * @param {FormData} orderData\n * @return {Promise<Object>}\n */\n var performCreateOrder = function (url, payPalOrderData, orderData) {\n orderData = orderData || new FormData();\n orderData.append('form_key', $.mage.cookies.get('form_key'));\n orderData.append('payment_source', payPalOrderData['paymentSource']);\n\n return fetch(url, {\n method: 'POST',\n headers: {},\n body: orderData || new FormData(),\n credentials: 'same-origin'\n }).then(function (response) {\n return response.json();\n });\n },\n\n /**\n * Payment authorization request.\n *\n * @return {Promise<Object>}\n */\n performAuthorization = function (url, data) {\n var orderData = new FormData();\n\n orderData.append('form_key', $.mage.cookies.get('form_key'));\n orderData.append('paypal_order_id', data.orderID);\n orderData.append('paypal_payer_id', data.payerID);\n\n return fetch(url, {\n method: 'POST',\n headers: {},\n body: orderData,\n credentials: 'same-origin'\n }).then(function (response) {\n return response.json();\n });\n };\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypal',\n paypal: null,\n paymentSource: '',\n creatOrderUrl: '',\n authorizeOrderUrl: '',\n style: {},\n paymentRequest: {\n applepay: {\n requiredShippingContactFields: []\n }\n },\n element: null,\n instance: null\n },\n\n /** @inheritdoc */\n initialize: function () {\n _.bindAll(this, 'createOrder', 'onApprove', 'onError', 'onCancel');\n this._super();\n this.sdkLoaded = loadSdkScript(this.scriptParams, this.sdkNamespace).then(function (sdkScript) {\n this.paypal = sdkScript;\n }.bind(this));\n\n return this;\n },\n\n /**\n * In the case where the button color is not supported by Apple (black or white)\n * Map the button color to black (same behavior as PayPal SDK script)\n *\n * @param buttonStyles\n * @returns {(*&{color: string})|*}\n */\n mapButtonColorForApplePay: function (buttonStyles) {\n var buttonColor = buttonStyles.color;\n\n if (buttonColor === 'black' || buttonColor === 'white') {\n return buttonStyles;\n }\n return {\n ...buttonStyles,\n color: 'black'\n };\n },\n\n /**\n * Render Smart Buttons.\n *\n * @param {HTMLElement} element\n * @return {*}\n */\n render: function (element) {\n var buttonsConfig;\n\n if (typeof this.paypal === 'undefined' || !this.paypal.Buttons) {\n return null;\n }\n\n if (element) {\n this.element = element;\n }\n\n buttonsConfig = {\n element: this.element,\n paymentRequest: this.paymentRequest,\n style: this.styles,\n onClick: this.onClick,\n createOrder: this.createOrder,\n onApprove: this.onApprove,\n onError: this.onError,\n onCancel: this.onCancel,\n onInit: this.onInit\n };\n\n if (this.onShippingChange) {\n buttonsConfig.onShippingChange = this.onShippingChange.bind(this);\n }\n if (this.fundingSource) {\n buttonsConfig.fundingSource = this.fundingSource;\n if (this.fundingSource === 'applepay') {\n buttonsConfig.style = this.mapButtonColorForApplePay(this.styles);\n }\n }\n\n this.instance = this.paypal.Buttons(buttonsConfig);\n\n if (this.instance.isEligible()) {\n this.instance.render(this.element);\n }\n\n return this.instance;\n },\n\n /**\n * Calls when smart buttons initializing\n */\n onInit: function () {\n },\n\n /**\n * Calls when user click paypal button.\n */\n onClick: function () {\n },\n\n /**\n * Calls before create order.\n *\n * @return {Promise}\n */\n beforeCreateOrder: function () {\n return Promise.resolve();\n },\n\n /**\n * Create order.\n *\n * @return {Promise}\n */\n createOrder: function (data) {\n this.paymentSource = data['paymentSource'];\n\n return this.beforeCreateOrder()\n .then(performCreateOrder.bind(this, this.createOrderUrl, data))\n .then(function (orderData) {\n return this.afterCreateOrder(orderData);\n }.bind(this)).catch(function (error) {\n return this.catchCreateOrder(error);\n }.bind(this)).finally(function (error) {\n return this.finallyCreateOrder(error);\n }.bind(this));\n },\n\n /**\n * After order created.\n *\n * @param {Object} data\n * @return {*}\n */\n afterCreateOrder: function (data) {\n return data.orderId;\n },\n\n /**\n * Catch error on order creation.\n */\n catchCreateOrder: function () {\n },\n\n /**\n * Finally for order creation.\n *\n */\n finallyCreateOrder: function () {\n },\n\n /**\n * Before authorization call.\n *\n * @return {Promise}\n */\n beforeOnAuthorize: function (data) {\n return Promise.resolve(data);\n },\n\n /**\n * On payment approve.\n *\n * @param {Object} data\n * @param {Object} actions\n * @return {Promise}\n */\n onApprove: function (data, actions) {\n return this.beforeOnAuthorize(data, actions)\n .then(performAuthorization.bind(this, this.authorizeOrderUrl))\n .then(function (authData) {\n return this.afterOnAuthorize(authData, actions);\n }.bind(this)).catch(function (error) {\n return this.catchOnAuthorize(error);\n }.bind(this)).finally(function (error) {\n return this.finallyOnAuthorize(error);\n }.bind(this));\n },\n\n /**\n * Calls after successful payment authorization.\n *\n * @param {Object} authData\n * @return {*}\n */\n afterOnAuthorize: function (authData) {\n return authData;\n },\n\n /**\n * Catch payment authorization errors.\n */\n catchOnAuthorize: function () {\n },\n\n /**\n * Finally for payment authorization.\n */\n finallyOnAuthorize: function () {\n },\n\n /**\n * Calls when shipping address chenges..\n *\n * @param {Object} data\n */\n onShippingChange: undefined,\n\n /**\n * Calls when error happened on paypal side.\n *\n * @param {Error} error\n */\n onError: function (error) {\n console.log('Error: ', error.message);\n },\n\n /**\n * Calls when user canceled payment.\n */\n onCancel: function () {}\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/methods/apple-pay.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'jquery',\n 'underscore',\n 'uiComponent',\n 'scriptLoader',\n 'Magento_PaymentServicesPaypal/js/lib/script-loader',\n 'Magento_Customer/js/customer-data',\n 'Magento_Customer/js/model/customer',\n 'mage/translate',\n], function ($, _, Component, loadSdkScript, scriptLoader, customerData, customer, $t) {\n 'use strict';\n\n const HTTP_STATUS_CREATED = 201;\n\n const APPLE_PAY_VERSION_NUMBER = 4; // See https://developer.apple.com/documentation/apple_pay_on_the_web/apple_pay_js_api/creating_an_apple_pay_session\n const appleSDKSrc = 'https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js';\n\n /**\n * Create order request.\n *\n * @param {String} url\n * @param {Object} payPalOrderData\n * @param {FormData} orderData\n * @return {Object}\n */\n var performCreateOrder = function (url, payPalOrderData, orderData) {\n\n orderData = orderData || new FormData();\n orderData.append('form_key', $.mage.cookies.get('form_key'));\n orderData.append('payment_source', payPalOrderData['paymentSource']);\n\n let xhr = new XMLHttpRequest();\n xhr.open('POST', url, false);\n xhr.send(orderData);\n\n if (xhr.status !== HTTP_STATUS_CREATED) {\n throw new Error('Request failed');\n } else {\n return JSON.parse(xhr.responseText);\n }\n },\n\n /**\n * Payment authorization request.\n *\n * @return {Promise<Object>}\n */\n performOnAuthorize = function (url, data) {\n var orderData = new FormData();\n\n orderData.append('form_key', $.mage.cookies.get('form_key'));\n orderData.append('paypal_order_id', data.orderID);\n\n return fetch(url, {\n method: 'POST',\n headers: {},\n body: orderData,\n credentials: 'same-origin'\n }).then(function (response) {\n return response.json();\n });\n };\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypal',\n paypal: null,\n paymentSource: 'applepay',\n createOrderUrl: '',\n placeOrderUrl: '',\n updateQuoteUrl: '',\n estimateShippingMethodsWhenLoggedInUrl: '',\n estimateShippingMethodsWhenGuestUrl: '',\n shippingInformationWhenLoggedInUrl: '',\n shippingInformationWhenGuestUrl: '',\n updatePaypalOrderUrl: '',\n setQuoteAsInactiveUrl: '',\n countriesUrl: '',\n instance: null,\n scriptParams: {},\n allowedPaymentMethods: null,\n merchantInfo: null,\n buttonContainerId: null,\n paypalOrderId: null,\n eligible: false,\n applePayInstance: null,\n applePayConfig: null,\n appleSession: null,\n applePayVersionNumber: APPLE_PAY_VERSION_NUMBER,\n countryCode: null,\n regionCode: null,\n regionId: null,\n postalCode: null,\n requestProcessingError: $t('Something went wrong with your request. Please try again later.'),\n },\n\n /** @inheritdoc */\n initialize: function () {\n _.bindAll(this, 'createOrder', 'onApprove', 'onError', 'initAppleSDK', 'performAuthorization',\n 'onClick', 'beforeOnAuthorize', 'afterOnAuthorize', 'onCancel');\n this._super();\n this.sdkLoaded = Promise.all([this.loadPayPalSDK(), this.loadAppleSDK()]);\n\n return this;\n },\n\n loadPayPalSDK: function () {\n return loadSdkScript(this.scriptParams, this.sdkNamespace)\n .then(function (sdkScript) {\n this.paypal = sdkScript;\n }.bind(this))\n .catch(function (e) {\n this.onError(e);\n });\n },\n\n loadAppleSDK: function () {\n return scriptLoader.loadCustom({url: appleSDKSrc})\n .catch(function (e) {\n this.onError(e);\n });\n },\n\n isCustomerLoggedIn: function () {\n return customer.isLoggedIn();\n },\n\n initAppleSDK: function () {\n if (!window.ApplePaySession) {\n console.error('This device does not support Apple Pay');\n return;\n }\n\n if (!ApplePaySession.canMakePayments()) {\n console.error('This device is not capable of making Apple Pay payments');\n }\n\n this.applePayInstance = this.paypal.Applepay();\n return this.applePayInstance.config()\n .then(applePayConfig => {\n this.applePayConfig = applePayConfig;\n this.renderApplePayButton();\n })\n .catch(applepayConfigError => {\n console.error('Error while fetching Apple Pay configuration.');\n });\n },\n\n onApplePayValidateMerchant: function (applePaySession) {\n applePaySession.onvalidatemerchant = (event) => {\n this.applePayInstance\n .validateMerchant({\n validationUrl: event.validationURL,\n })\n .then((payload) => {\n applePaySession.completeMerchantValidation(payload.merchantSession);\n })\n .catch((error) => {\n applePaySession.abort();\n this.isErrorDisplayed = false;\n this.catchError(error)\n });\n };\n },\n\n onApplePayPaymentAuthorized: function (applePaySession, paypalOrderId = null) {\n applePaySession.onpaymentauthorized = async (event) => {\n try {\n await this.applePayInstance.confirmOrder({\n orderId: paypalOrderId !== null ? paypalOrderId : this.paypalOrderId,\n token: event.payment.token,\n billingContact: event.payment.billingContact,\n shippingContact: event.payment.shippingContact\n });\n\n applePaySession.completePayment({\n status: window.ApplePaySession.STATUS_SUCCESS,\n });\n\n await this.onApprove();\n } catch (error) {\n applePaySession.completePayment({\n status: window.ApplePaySession.STATUS_FAILURE,\n });\n this.isErrorDisplayed = false;\n this.catchError(error)\n }\n };\n },\n\n onApplePayPaymentMethodSelected: function (applePaySession, total) {\n applePaySession.onpaymentmethodselected = (event) => {\n applePaySession.completePaymentMethodSelection({\n newTotal: total,\n });\n };\n },\n\n onApplePayShippingContactSelected: function (applePaySession, quoteId, total, isVirtual) {\n applePaySession.onshippingcontactselected = (event) => {\n\n const shippingMethods = [];\n\n let estimateShippingMethodURL = (this.isCustomerLoggedIn())\n ? this.estimateShippingMethodsWhenLoggedInUrl\n : this.estimateShippingMethodsWhenGuestUrl.replace(':cartId', quoteId);\n\n if (this.pageType === 'product') {\n // Product Page: we need to use guest cart quote because it is created outside the checkout process\n estimateShippingMethodURL = this.estimateShippingMethodsWhenGuestUrl.replace(':cartId', quoteId);\n }\n\n this.countryCode = event.shippingContact.countryCode;\n this.regionCode = event.shippingContact.administrativeArea;\n this.postalCode = event.shippingContact.postalCode;\n\n this.getRegionIdByCode(this.regionCode, this.countryCode)\n .then((regionId) => {\n this.regionId = regionId;\n })\n .catch((error)=> {\n // If the Apple region Code doesn't match to the one in Commerce\n // we set the regionId to null to still apply the taxes of the country\n // to continue with the checkout\n console.log(error);\n this.regionId = null;\n });\n\n $.ajax({\n type: 'POST',\n url: estimateShippingMethodURL,\n headers: {\n 'Content-Type': 'application/json',\n },\n data: JSON.stringify({\n address: {\n country_id: event.shippingContact.countryCode,\n postcode: event.shippingContact.postalCode,\n city: event.shippingContact.locality\n }\n })\n }).then(estimateShippingMethods => {\n\n estimateShippingMethods.forEach(method => {\n shippingMethods.push({\n label: method.method_title,\n detail: method.carrier_title,\n amount: method.amount.toString(),\n identifier: method.carrier_code + '_' + method.method_code,\n });\n });\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingMethods,\n newTotal: total,\n })\n\n }, error => {\n this.isErrorDisplayed = false;\n applePaySession.abort();\n this.catchError(error);\n });\n\n if (isVirtual) {\n // If Quote is virtual, no need to select shipping\n // We can already create the order\n this.createOrder();\n }\n }\n },\n\n onApplePayShippingMethodSelectedInCartPage: function (applePaySession, quoteId) {\n this.onApplePayShippingMethodSelected(applePaySession, quoteId, null,null);\n },\n\n onApplePayShippingMethodSelected: function (applePaySession, quoteId, quoteMaskedId, paypalOrderId) {\n applePaySession.onshippingmethodselected = (event) => {\n\n let shippingInformationURL = (this.isCustomerLoggedIn())\n ? this.shippingInformationWhenLoggedInUrl\n : this.shippingInformationWhenGuestUrl.replace(':quoteId', quoteId);\n\n if (this.pageType === 'product') {\n // Product Page: we need to use quoteMaskedId as the quote is created outside the checkout process\n shippingInformationURL = this.shippingInformationWhenGuestUrl.replace(':quoteId', quoteMaskedId);\n }\n\n $.ajax({\n type: 'POST',\n url: shippingInformationURL,\n headers: {\n 'Content-Type': 'application/json',\n },\n data: JSON.stringify({\n addressInformation: {\n shipping_address: {\"country_id\": this.countryCode, \"region_id\": this.regionId, \"postcode\": this.postalCode},\n shipping_method_code: event.shippingMethod.identifier.split('_')[1],\n shipping_carrier_code: event.shippingMethod.identifier.split('_')[0],\n extension_attributes: {}\n }\n })\n }).then(result => {\n\n let items = [];\n\n result['totals']['items'].forEach(item => {\n items.push({\n label: item.name + ' ( x ' + item.qty + ' )',\n type: \"final\",\n amount: item.row_total\n });\n });\n\n items.push({\n label: \"Shipping\",\n type: \"final\",\n amount: result['totals']['shipping_amount'],\n });\n\n if (result['totals']['tax_amount'] !== 0) {\n items.push({\n label: \"Tax\",\n type: \"final\",\n amount: result['totals']['tax_amount'],\n });\n }\n\n applePaySession.completeShippingMethodSelection({\n newLineItems: items,\n newTotal: {\n label: \"Summary\",\n type: \"final\",\n amount: result['totals']['grand_total'],\n },\n });\n\n if (this.pageType === 'product') {\n // In the product page, the paypal order has been created on the onClick handler\n // so we just need to update the amount with the shipping selected\n this.updatePaypalOrder();\n } else {\n // In Cart and Minicart, we need to create the Paypal Order\n this.createOrder();\n }\n\n }).catch(error => {\n applePaySession.abort();\n this.isErrorDisplayed = false;\n this.catchError(error);\n });\n };\n },\n\n updatePaypalOrder: function() {\n\n // Update PayPal Order Amount as the shipping method has been selected and the price changed\n // Without the update, the payment is failing as the order amount could be different\n $.ajax({\n type: 'POST',\n url: this.updatePayPalOrderUrl,\n }).catch(error => {\n this.catchError(error);\n });\n },\n\n onApplePayCancel: function (applePaySession, callback) {\n applePaySession.oncancel = () => {\n if (typeof callback === 'function') {\n callback();\n }\n\n this.showLoader(false);\n }\n },\n\n getApplePaymentRequestLineItems: function (quote){\n let items = [];\n\n quote.getItems().forEach(item => {\n items.push({\n label: item.name + ' ( x ' + item.qty + ' )',\n type: \"final\",\n amount: item.price * item.qty,\n });\n });\n\n items.push({\n label: $t(\"Shipping\"),\n type: \"final\",\n amount: quote.getTotals()()['shipping_amount'],\n });\n\n if (quote.getTotals()['tax_amount'] !== 0) {\n items.push({\n label: $t(\"Tax\"),\n type: \"final\",\n amount: quote.getTotals()()['tax_amount'],\n });\n }\n\n return items;\n },\n\n showPopup: function (paymentData, quote) {\n const paymentRequest = {\n countryCode: this.applePayConfig.countryCode,\n merchantCapabilities: this.applePayConfig.merchantCapabilities,\n supportedNetworks: this.applePayConfig.supportedNetworks,\n currencyCode: paymentData.response['paypal-order']['currency_code'],\n lineItems: this.getApplePaymentRequestLineItems(quote),\n requiredBillingContactFields: [\"postalAddress\"],\n shippingContact: {\n countryCode: quote.shippingAddress().countryId,\n postalCode: quote.shippingAddress().postcode,\n locality: quote.shippingAddress().city,\n administrativeArea: quote.shippingAddress().regionCode,\n familyName: quote.shippingAddress().lastname,\n givenName: quote.shippingAddress().firstname,\n addressLines: quote.shippingAddress().street,\n },\n total: {\n label: $t(\"Summary\"),\n type: \"final\",\n amount: Number(paymentData.response['paypal-order']['amount']).toString(),\n }\n };\n\n // See https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession\n this.applePaySession = new ApplePaySession(APPLE_PAY_VERSION_NUMBER, paymentRequest);\n this.onApplePayValidateMerchant(this.applePaySession);\n this.onApplePayPaymentAuthorized(this.applePaySession, paymentData.response['paypal-order']['id']);\n this.onApplePayCancel(this.applePaySession);\n\n this.applePaySession.begin();\n },\n\n onCancel: function () {\n window.location = data.redirectUrl;\n this.showLoader(false);\n },\n\n renderApplePayButton: function () {\n if (this.applePayConfig.isEligible) {\n const buttonStyle = this.mapButtonStyle();\n const buttonType = this.mapButtonType();\n const height = this.styles.height > 0\n ? this.styles.height + \"px\"\n : \"40px\";\n\n document.getElementById(this.buttonContainerId).innerHTML = `\n <apple-pay-button\n id=\"btn-appl\"\n buttonstyle=\"${buttonStyle}\"\n type=\"${buttonType}\"\n locale=\"${window.LOCALE}\"\n style=\" --apple-pay-button-width: 100%; --apple-pay-button-height: ${height}\"\n >`;\n document.getElementById(\"btn-appl\").addEventListener(\"click\", this.onClick);\n }\n },\n\n mapButtonStyle: function () {\n return this.styles.color === 'white' ? 'white' : 'black';\n },\n\n mapButtonType: function () {\n switch (this.styles.label) {\n case 'paypal':\n case 'installment':\n return 'plain';\n case 'checkout':\n return 'check-out';\n case 'buynow':\n return 'buy';\n default:\n return 'pay';\n }\n },\n\n enableButton: function () {\n $('#' + this.buttonContainerId).find('button').prop('disabled', false);\n },\n\n disableButton: function () {\n $('#' + this.buttonContainerId).find('button').prop('disabled', true);\n },\n\n performAuthorization: function (paymentData) {},\n\n onClick: function () {},\n\n /**\n * Calls before create order.\n */\n beforeCreateOrder: function () {},\n\n /**\n * Create order.\n *\n * @return {String}\n */\n createOrder: function () {\n let data = {'paymentSource': this.paymentSource};\n\n try {\n this.beforeCreateOrder();\n let orderData = performCreateOrder(this.createOrderUrl, data, null);\n this.paypalOrderId = this.afterCreateOrder(orderData);\n return this.paypalOrderId;\n } catch (error) {\n this.isErrorDisplayed = false;\n this.catchError(error);\n\n // Propagate the error to be caught in the promise chain\n return Promise.reject(error);\n }\n },\n\n /**\n * After order created.\n *\n * @param {Object} data\n * @return {String}\n */\n afterCreateOrder: function (data) {},\n\n /**\n * Catch error on order creation.\n */\n catchCreateOrder: function () {},\n\n /**\n * On payment approve.\n *\n * @param {Object} data\n * @param {Object} actions\n * @return {Promise}\n */\n onApprove: function () {\n const data = {orderID: this.paypalOrderId};\n\n return this.beforeOnAuthorize()\n .then(performOnAuthorize.bind(this, this.updateQuoteUrl, data))\n .then(this.afterOnAuthorize)\n .catch(this.onError);\n },\n\n beforeOnAuthorize: function () {\n return Promise.resolve();\n },\n\n afterOnAuthorize: function () {\n return Promise.resolve();\n },\n\n /**\n * Calls when error happened on paypal side.\n *\n * @param {Error} error\n */\n onError: function (error) {\n console.log('Error: ', error.message);\n },\n\n isEligible: function () {\n return this.eligible;\n },\n\n /**\n * Async Show/hide loader\n *\n * @param {Boolean} show\n */\n showLoaderAsync: function (show) {\n return new Promise(function (resolve, reject) {\n var event = show ? 'processStart' : 'processStop';\n $('body').trigger(event);\n\n // Set minimum time for loader to show\n setTimeout(() => {\n resolve();\n }, 10);\n });\n },\n\n /**\n * Show/hide loader.\n *\n * @param {Boolean} show\n */\n showLoader: function (show) {\n var event = show ? 'processStart' : 'processStop';\n\n $('body').trigger(event);\n },\n\n /**\n * Get region ID by region code and country code\n *\n * @param regionCode\n * @param countryCode\n * @returns {null}\n */\n getRegionIdByCode: function (regionCode, countryCode) {\n return new Promise(function (resolve, reject) {\n $.ajax({\n url: this.countriesUrl.replace(':countryCode', countryCode),\n method: 'GET',\n success: function (response) {\n if (response.available_regions && response.available_regions.length) {\n var matchedRegion = response.available_regions.find(function (region) {\n return region.code === regionCode;\n });\n\n if (matchedRegion) {\n resolve(matchedRegion.id);\n } else {\n reject('Region not found');\n }\n } else {\n reject('No regions available for country: ' + countryCode);\n }\n },\n error: function () {\n reject('Error fetching regions for country: ' + countryCode);\n }\n });\n }.bind(this));\n },\n\n /**\n * Catch errors.\n *\n * @param {*} error\n */\n catchError: function (error) {\n this.showLoader(false);\n\n if (this.isErrorDisplayed) {\n return;\n }\n\n if (error.hidden === undefined || !error.hidden) {\n this.addMessage(this.requestProcessingError);\n }\n\n this.isErrorDisplayed = true;\n },\n\n /**\n * Add message to customer data.\n *\n * @param {String} message\n * @param {String} [type]\n */\n addMessage: function (message, type) {\n type = type || 'error';\n\n // Need to set a slight delay to avoid refresh from core\n setTimeout(function () {\n customerData.set('messages', {\n messages: [{\n text: message,\n type: type\n }]\n });\n }, 1000);\n },\n\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/methods/google-pay.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'jquery',\n 'underscore',\n 'uiComponent',\n 'scriptLoader',\n 'Magento_PaymentServicesPaypal/js/lib/script-loader',\n 'mage/translate',\n 'mage/cookies'\n], function ($, _, Component, loadSdkScript, scriptLoader, $t) {\n 'use strict';\n\n const HTTP_STATUS_CREATED = 201;\n\n const googleSDKSrc = 'https://pay.google.com/gp/p/js/pay.js',\n baseRequest = {\n apiVersion: 2,\n apiVersionMinor: 0,\n callbackIntents: ['PAYMENT_AUTHORIZATION'],\n emailRequired: true,\n shippingAddressParameters: {phoneNumberRequired: true}\n };\n\n /**\n * Create order request.\n *\n * @param {String} url\n * @param {Object} payPalOrderData\n * @param {FormData} orderData\n * @return {Object}\n */\n var performCreateOrder = function (url, payPalOrderData, orderData) {\n orderData = orderData || new FormData();\n orderData.append('form_key', $.mage.cookies.get('form_key'));\n orderData.append('payment_source', payPalOrderData['paymentSource']);\n\n let xhr = new XMLHttpRequest();\n xhr.open('POST', url, false);\n xhr.send(orderData);\n\n if (xhr.status !== HTTP_STATUS_CREATED) {\n throw new Error('Request failed');\n } else {\n return JSON.parse(xhr.responseText);\n }\n },\n\n /**\n * Payment authorization request.\n *\n * @return {Promise<Object>}\n */\n performOnAuthorize = function (url, data) {\n var orderData = new FormData();\n\n orderData.append('form_key', $.mage.cookies.get('form_key'));\n orderData.append('paypal_order_id', data.orderID);\n\n return fetch(url, {\n method: 'POST',\n headers: {},\n body: orderData,\n credentials: 'same-origin'\n }).then(function (response) {\n return response.json();\n });\n };\n\n return Component.extend({\n defaults: {\n sdkNamespace: 'paypal',\n paypal: null,\n paymentSource: 'googlepay',\n createOrderUrl: '',\n updateQuoteUrl: '',\n instance: null,\n scriptParams: {},\n allowedPaymentMethods: null,\n merchantInfo: null,\n buttonContainerId: null,\n paypalOrderId: null,\n eligible: false,\n mode: 'TEST',\n shippingAddressRequired: true\n },\n\n /** @inheritdoc */\n initialize: function () {\n _.bindAll(this, 'createOrder', 'onApprove', 'onError', 'initGoogleSDK', 'performAuthorization',\n 'onClick', 'beforeOnAuthorize', 'afterOnAuthorize', 'onCancel');\n this._super();\n this.sdkLoaded = Promise.all([this.loadPayPalSDK(), this.loadGoogleSDK()]);\n\n return this;\n },\n\n loadPayPalSDK: function () {\n return loadSdkScript(this.scriptParams, this.sdkNamespace)\n .then(function (sdkScript) {\n this.paypal = sdkScript;\n }.bind(this))\n .catch(function (e) {\n this.onError(e);\n });\n },\n\n loadGoogleSDK: function () {\n return scriptLoader.loadCustom({url: googleSDKSrc})\n .catch(function (e) {\n this.onError(e);\n });\n },\n\n initGoogleSDK: function () {\n return this.getGooglePayConfig()\n .then(config =>\n this.getGooglePaymentsClient()\n .isReadyToPay(this.getGoogleIsReadyToPayRequest(config.allowedPaymentMethods))\n .then(function (response) {\n if (response.result) {\n this.renderGooglePayButton();\n }\n }.bind(this))\n ).catch(function (e) {\n this.onError({\n hidden: true,\n error: e\n });\n }.bind(this));\n },\n\n getGooglePaymentsClient: function () {\n if (this.instance === null) {\n this.instance = new google.payments.api.PaymentsClient({\n environment: this.mode,\n paymentDataCallbacks: {\n onPaymentAuthorized: this.performAuthorization\n }\n });\n }\n return this.instance;\n },\n\n showPopup: function (paymentData) {\n this.getGooglePaymentDataRequest(paymentData)\n .then((data) => {\n this.getGooglePaymentsClient()\n .loadPaymentData(data)\n .catch(this.onCancel);\n }).catch(this.onError);\n },\n\n onCancel: function () {\n this.showLoader(false);\n },\n\n getGooglePaymentDataRequest: async function (transactionInfo) {\n const paymentDataRequest = Object.assign({}, baseRequest),\n { allowedPaymentMethods, merchantInfo } = await this.getGooglePayConfig();\n\n paymentDataRequest.allowedPaymentMethods = allowedPaymentMethods;\n paymentDataRequest.transactionInfo = transactionInfo;\n paymentDataRequest.merchantInfo = merchantInfo;\n paymentDataRequest.shippingAddressRequired = this.shippingAddressRequired;\n\n return paymentDataRequest;\n },\n\n getGooglePayConfig: async function () {\n if (this.allowedPaymentMethods === null || this.merchantInfo === null) {\n const googlePayConfig = await this.paypal.Googlepay().config();\n\n this.allowedPaymentMethods = googlePayConfig.allowedPaymentMethods;\n this.merchantInfo = googlePayConfig.merchantInfo;\n }\n\n return {\n allowedPaymentMethods: this.allowedPaymentMethods,\n merchantInfo: this.merchantInfo\n };\n },\n\n getGoogleIsReadyToPayRequest: function (allowedPaymentMethods) {\n return Object.assign({}, baseRequest, {\n allowedPaymentMethods: allowedPaymentMethods\n });\n },\n\n renderGooglePayButton: function () {\n const buttonContainer = $('#' + this.buttonContainerId);\n\n let buttonProps = {\n onClick: this.onClick,\n buttonColor: this.styles.button_color,\n buttonType: this.styles.button_type\n };\n\n buttonProps.buttonSizeMode = 'fill';\n\n if (this.styles.button_custom_height) {\n buttonContainer.height(this.styles.button_custom_height);\n }\n\n buttonContainer.append(\n this.getGooglePaymentsClient().createButton(buttonProps)\n );\n this.eligible = true;\n },\n\n enableButton: function () {\n $('#' + this.buttonContainerId).find('button').prop('disabled', false);\n },\n\n disableButton: function () {\n $('#' + this.buttonContainerId).find('button').prop('disabled', true);\n },\n\n performAuthorization: function (paymentData) {\n return new Promise(function (resolve) {\n this.processPayment(paymentData)\n .then(resolve)\n .catch(function () {\n this.onError(new Error('couldn\\'t process payment'));\n resolve({ transactionState: 'ERROR' });\n }.bind(this));\n }.bind(this));\n },\n\n processPayment: async function (paymentData) {\n try {\n const { status } = await this.paypal.Googlepay().confirmOrder({\n orderId: this.paypalOrderId,\n paymentMethodData: paymentData.paymentMethodData,\n shippingAddress: paymentData.shippingAddress,\n email: paymentData.email\n });\n\n if (status === 'APPROVED') {\n this.onApprove(paymentData);\n return { transactionState: 'SUCCESS' };\n }\n\n this.onError(new Error('couldn\\'t approve order'));\n return { transactionState: 'ERROR' };\n } catch (err) {\n this.onError(err);\n return {\n transactionState: 'ERROR',\n error: {\n message: err.message\n }\n };\n }\n },\n\n onClick: function () {},\n\n /**\n * Calls before create order.\n */\n beforeCreateOrder: function () {},\n\n /**\n * Create order.\n *\n * @return {String}\n */\n createOrder: function () {\n let data = {'paymentSource': this.paymentSource};\n\n try {\n this.beforeCreateOrder();\n let orderData = performCreateOrder(this.createOrderUrl, data, null);\n this.paypalOrderId = this.afterCreateOrder(orderData);\n return this.paypalOrderId;\n } catch (error) {\n return this.catchCreateOrder(error);\n }\n },\n\n /**\n * After order created.\n *\n * @param {Object} data\n * @return {String}\n */\n afterCreateOrder: function (data) {\n if (data.response['paypal-order'] && data.response['paypal-order']['mp_order_id']) {\n this.paymentsOrderId = data.response['paypal-order']['mp_order_id'];\n this.paypalOrderId = data.response['paypal-order'].id;\n\n this.showPopup({\n displayItems: [],\n currencyCode: data.response['paypal-order']['currency_code'],\n totalPriceStatus: 'FINAL',\n totalPrice: Number(data.response['paypal-order']['amount']).toString(),\n totalPriceLabel: $t('Total')\n });\n\n return this.paypalOrderId;\n }\n\n throw new Error();\n },\n\n /**\n * Catch error on order creation.\n */\n catchCreateOrder: function () {},\n\n /**\n * On payment approve.\n *\n * @param {Object} data\n * @param {Object} actions\n * @return {Promise}\n */\n onApprove: function () {\n const data = {orderID: this.paypalOrderId};\n\n return this.beforeOnAuthorize()\n .then(performOnAuthorize.bind(this, this.updateQuoteUrl, data))\n .then(this.afterOnAuthorize)\n .catch(this.onError);\n },\n\n beforeOnAuthorize: function () {\n return Promise.resolve();\n },\n\n afterOnAuthorize: function () {\n return Promise.resolve();\n },\n\n /**\n * Calls when error happened on paypal side.\n *\n * @param {Error} error\n */\n onError: function (error) {\n console.log('Error: ', error.message);\n },\n\n isEligible: function () {\n return this.eligible;\n },\n\n /**\n * Async Show/hide loader\n *\n * @param {Boolean} show\n */\n showLoaderAsync: function (show) {\n return new Promise(function (resolve, reject) {\n var event = show ? 'processStart' : 'processStop';\n $('body').trigger(event);\n\n // Set minimum time for loader to show\n setTimeout(() => {\n resolve();\n }, 10);\n });\n },\n\n /**\n * Show/hide loader.\n *\n * @param {Boolean} show\n */\n showLoader: function (show) {\n var event = show ? 'processStart' : 'processStop';\n\n $('body').trigger(event);\n },\n });\n});\n","Magento_PaymentServicesPaypal/js/view/payment/actions/get-sdk-params.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'jquery',\n 'underscore',\n 'Magento_Customer/js/customer-data',\n 'jquery/jquery-storageapi'\n], function ($, _, customerData) {\n 'use strict';\n\n var promise = null,\n timeoutKey = 'payments-sdk-params-timeout',\n paymentsKey = 'payments',\n sdkParamsKey = 'sdkParams';\n\n return function (cacheTtl) {\n if (!promise) {\n promise = new Promise(function (resolve, reject) {\n var dateNow = Date.now(),\n dateTo = dateNow + cacheTtl,\n timeout = $.localStorage.get(timeoutKey);\n if (timeout < dateNow || !timeout) {\n return customerData.reload([paymentsKey]).done(function () {\n $.localStorage.set(timeoutKey, dateTo);\n resolve(customerData.get(paymentsKey)()[sdkParamsKey]);\n }).fail(reject.bind(this, []));\n }\n\n if (!_.isEmpty(customerData.get(paymentsKey)())) {\n return resolve(customerData.get(paymentsKey)()[sdkParamsKey]);\n }\n\n customerData.get(paymentsKey).subscribe(function (payments) {\n resolve(payments[sdkParamsKey]);\n });\n\n });\n }\n\n return promise;\n };\n});\n","Magento_PaymentServicesPaypal/js/model/payment-service-mixin.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine([\n 'underscore',\n 'mage/utils/wrapper'\n], function (_, wrapper) {\n 'use strict';\n\n /**\n * Free method filter\n * @param {Object} paymentMethod\n * @return {Boolean}\n */\n var paymentServicesMethods = [\n 'payment_services_paypal_smart_buttons',\n 'payment_services_paypal_apple_pay',\n 'payment_services_paypal_google_pay',\n 'payment_services_paypal_hosted_fields'\n ],\n\n /**\n * Check if payment method is from payment services.\n *\n * @param {String} needleName\n * @param {String} paymentMethod\n * @returns {Boolean}\n */\n isPaymentServicesButtonsPaymentMethod = function (needleName, paymentMethod) {\n return paymentMethod.method === needleName;\n },\n\n /**\n * Check if Apple Pay method is available.\n */\n checkApplePayAvailability = function () {\n window.checkoutConfig.payment['payment_services_paypal_apple_pay'].isVisible = !!(\n window.checkoutConfig.payment['payment_services_paypal_apple_pay'].isVisible &&\n window.ApplePaySession\n );\n !window.ApplePaySession && console.log('Apple Pay is not supported or not available');\n },\n\n extender = {\n /**\n * Filter hidden payment methods.\n *\n * @param {Function} originFn - Original method.\n * @param {Array} methods\n */\n setPaymentMethods: function (originFn, methods) {\n var paymentServicesButtonMethodIndex;\n\n checkApplePayAvailability();\n\n _.each(paymentServicesMethods, function (paymentMethod) {\n if (!window.checkoutConfig.payment[paymentMethod].isVisible) {\n paymentServicesButtonMethodIndex = _.findIndex(\n methods,\n isPaymentServicesButtonsPaymentMethod.bind(null, paymentMethod)\n );\n paymentServicesButtonMethodIndex >= 0 && methods.splice(paymentServicesButtonMethodIndex, 1);\n }\n });\n\n return originFn(methods);\n }\n };\n\n return function (target) {\n return wrapper.extend(target, extender);\n };\n});\n","Magento_PaymentServicesPaypal/js/lib/script-loader-wrapper.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* eslint-disable no-undef */\ndefine(['underscore', 'Magento_PaymentServicesPaypal/js/lib/script-loader'], function (_, scriptLoader) {\n 'use strict';\n\n var promises = {},\n defaultNamespace = 'paypal';\n\n /**\n * Parse src query string and move all params to object\n *\n * @param {Object} params\n * @return {Object}\n */\n function processParamsSrc(params) {\n var processedParams = _.clone(params),\n url = new URL(params.src),\n queryString = url.search.substring(1),\n urlParams = JSON.parse('{\"' +\n decodeURI(queryString).replace(/\"/g, '\\\\\"').replace(/&/g, '\",\"').replace(/=/g, '\":\"') +\n '\"}');\n\n _.extend(processedParams, urlParams);\n delete processedParams.src;\n\n return processedParams;\n }\n\n /**\n * Convert params to object key => value format\n *\n * @param {Object} params\n * @return {Object}\n */\n function convertToParamsObject(params) {\n var processedParams = {};\n\n _.each(params, function (param) {\n processedParams[param.name] = param.value;\n });\n\n return processedParams;\n }\n\n /**\n * Load PayPal sdk with params.\n *\n * @param {Array} params\n * @param {String} sdkNamespace\n * @return {Promise}\n */\n return function (params, sdkNamespace) {\n var src;\n\n if (!params || !params.length) {\n return Promise.reject();\n }\n\n params = convertToParamsObject(params);\n params['data-namespace'] = sdkNamespace || defaultNamespace;\n\n if (!params || !params.src) {\n return Promise.reject();\n }\n\n src = params.src;\n\n if (!promises[src]) {\n params = processParamsSrc(params);\n\n promises[src] = scriptLoader.load(params);\n }\n\n return promises[src];\n };\n});\n","Magento_PaymentServicesPaypal/js/lib/script-loader.min.js":"/*!\n * paypal-js v3.1.1 (2021-03-14T21:08:07.006Z)\n * Copyright 2020-present, PayPal, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar paypalLoadScript=function(t){\"use strict\";function e(t,e){var r=document.querySelector('script[src=\"'.concat(t,'\"]'));if(null===r)return null;var n=a(t,e);if(Object.keys(r.dataset).length!==Object.keys(n.dataset).length)return null;var o=!0;return Object.keys(r.dataset).forEach((function(t){r.dataset[t]!==n.dataset[t]&&(o=!1)})),o?r:null}function r(t){var e=t.url,r=t.attributes,n=t.onSuccess,o=t.onError,i=a(e,r);i.onerror=o,i.onload=n,document.head.insertBefore(i,document.head.firstElementChild)}function n(t){var e=\"https://www.paypal.com/sdk/js\";t.sdkBaseURL&&(e=t.sdkBaseURL,delete t.sdkBaseURL);var r=function(t,e){var r=\"\",n=\"\";Array.isArray(t)?t.length>1?(r=\"*\",n=t.toString()):r=t.toString():\"string\"==typeof t&&t.length>0?r=t:\"string\"==typeof e&&e.length>0&&(r=\"*\",n=e);return{\"merchant-id\":r,\"data-merchant-id\":n}}(t[\"merchant-id\"],t[\"data-merchant-id\"]),n=Object.assign(t,r),a=Object.keys(n).filter((function(t){return void 0!==n[t]&&null!==n[t]&&\"\"!==n[t]})).reduce((function(t,e){var r=n[e].toString();return\"data-\"===e.substring(0,5)?t.dataAttributes[e]=r:t.queryParams[e]=r,t}),{queryParams:{},dataAttributes:{}}),i=a.queryParams,u=a.dataAttributes;return{url:\"\".concat(e,\"?\").concat(o(i)),dataAttributes:u}}function o(t){var e=\"\";return Object.keys(t).forEach((function(r){0!==e.length&&(e+=\"&\"),e+=r+\"=\"+t[r]})),e}function a(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=document.createElement(\"script\");return r.src=t,Object.keys(e).forEach((function(t){r.setAttribute(t,e[t]),\"data-csp-nonce\"===t&&r.setAttribute(\"nonce\",e[\"data-csp-nonce\"])})),r}function i(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u();s(t,e);var n=t.url,o=t.attributes;if(\"string\"!=typeof n||0===n.length)throw new Error(\"Invalid url.\");if(void 0!==o&&\"object\"!=typeof o)throw new Error(\"Expected attributes to be an object.\");return new e((function(t,e){if(\"undefined\"==typeof window)return t();r({url:n,attributes:o,onSuccess:function(){return t()},onError:function(){return e(new Error('The script \"'.concat(n,'\" failed to load.')))}})}))}function u(){if(\"undefined\"==typeof Promise)throw new Error(\"Promise is undefined. To resolve the issue, use a Promise polyfill.\");return Promise}function c(t){return window[t]}function s(t,e){if(\"object\"!=typeof t||null===t)throw new Error(\"Expected an options object.\");if(void 0!==e&&\"function\"!=typeof e)throw new Error(\"Expected PromisePonyfill to be a function.\")}return t.loadCustomScript=i,t.loadScript=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u();if(s(t,r),\"undefined\"==typeof window)return r.resolve(null);var o=n(t),a=o.url,d=o.dataAttributes,l=d[\"data-namespace\"]||\"paypal\",f=c(l);return e(a,d)&&f?r.resolve(f):i({url:a,attributes:d},r).then((function(){var t=c(l);if(t)return t;throw new Error(\"The window.\".concat(l,\" global variable is not available.\"))}))},t.version=\"3.1.1\",Object.defineProperty(t,\"__esModule\",{value:!0}),t}({});window.paypalLoadCustomScript=paypalLoadScript.loadCustomScript,window.paypalLoadScript=paypalLoadScript.loadScript;\n","Magento_Payment/js/transparent.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'jquery',\n 'mage/template',\n 'Magento_Ui/js/modal/alert',\n 'jquery-ui-modules/widget',\n 'Magento_Payment/js/model/credit-card-validation/validator',\n 'Magento_Checkout/js/model/full-screen-loader'\n], function ($, mageTemplate, alert, ui, validator, fullScreenLoader) {\n 'use strict';\n\n $.widget('mage.transparent', {\n options: {\n context: null,\n placeOrderSelector: '[data-role=\"review-save\"]',\n paymentFormSelector: '#co-payment-form',\n updateSelectorPrefix: '#checkout-',\n updateSelectorSuffix: '-load',\n hiddenFormTmpl:\n '<form target=\"<%= data.target %>\" action=\"<%= data.action %>\" method=\"POST\" ' +\n 'hidden enctype=\"application/x-www-form-urlencoded\" class=\"no-display\">' +\n '<% _.each(data.inputs, function(val, key){ %>' +\n '<input value=\"<%= val %>\" name=\"<%= key %>\" type=\"hidden\">' +\n '<% }); %>' +\n '</form>',\n reviewAgreementForm: '#checkout-agreements',\n cgiUrl: null,\n orderSaveUrl: null,\n controller: null,\n gateway: null,\n dateDelim: null,\n cardFieldsMap: null,\n expireYearLength: 2\n },\n\n /**\n * {Function}\n * @private\n */\n _create: function () {\n this.hiddenFormTmpl = mageTemplate(this.options.hiddenFormTmpl);\n\n if (this.options.context) {\n this.options.context.setPlaceOrderHandler($.proxy(this._orderSave, this));\n this.options.context.setValidateHandler($.proxy(this._validateHandler, this));\n } else {\n $(this.options.placeOrderSelector)\n .off('click')\n .on('click', $.proxy(this._placeOrderHandler, this));\n }\n\n this.element.validation();\n $('[data-container=\"' + this.options.gateway + '-cc-number\"]').on('focusout', function () {\n $(this).valid();\n });\n },\n\n /**\n * handler for credit card validation\n * @return {Boolean}\n * @private\n */\n _validateHandler: function () {\n return this.element.validation && this.element.validation('isValid');\n },\n\n /**\n * handler for Place Order button to call gateway for credit card validation\n * @return {Boolean}\n * @private\n */\n _placeOrderHandler: function () {\n if (this._validateHandler()) {\n this._orderSave();\n }\n\n return false;\n },\n\n /**\n * Save order and generate post data for gateway call\n * @private\n */\n _orderSave: function () {\n var postData = $(this.options.paymentFormSelector).serialize();\n\n if ($(this.options.reviewAgreementForm).length) {\n postData += '&' + $(this.options.reviewAgreementForm).serialize();\n }\n postData += '&controller=' + this.options.controller;\n postData += '&cc_type=' + this.element.find(\n '[data-container=\"' + this.options.gateway + '-cc-type\"]'\n ).val();\n\n return $.ajax({\n url: this.options.orderSaveUrl,\n type: 'post',\n context: this,\n data: postData,\n dataType: 'json',\n\n /**\n * {Function}\n */\n beforeSend: function () {\n fullScreenLoader.startLoader();\n },\n\n /**\n * {Function}\n */\n success: function (response) {\n var preparedData,\n msg,\n\n /**\n * {Function}\n */\n alertActionHandler = function () {\n // default action\n };\n\n if (response.success && response[this.options.gateway]) {\n preparedData = this._preparePaymentData(\n response[this.options.gateway].fields,\n this.options.cardFieldsMap\n );\n this._postPaymentToGateway(preparedData);\n } else {\n fullScreenLoader.stopLoader(true);\n\n msg = response['error_messages'];\n\n if (this.options.context) {\n this.options.context.clearTimeout().fail();\n alertActionHandler = this.options.context.alertActionHandler;\n }\n\n if (typeof msg === 'object') {\n msg = msg.join('\\n');\n }\n\n if (msg) {\n alert(\n {\n content: msg,\n actions: {\n\n /**\n * {Function}\n */\n always: alertActionHandler\n }\n }\n );\n }\n }\n }.bind(this)\n });\n },\n\n /**\n * Post data to gateway for credit card validation\n * @param {Object} data\n * @private\n */\n _postPaymentToGateway: function (data) {\n var tmpl,\n iframeSelector = '[data-container=\"' + this.options.gateway + '-transparent-iframe\"]';\n\n tmpl = this.hiddenFormTmpl({\n data: {\n target: $(iframeSelector).attr('name'),\n action: this.options.cgiUrl,\n inputs: data\n }\n });\n $(tmpl).appendTo($(iframeSelector)).trigger('submit');\n },\n\n /**\n * Add credit card fields to post data for gateway\n * @param {Object} data\n * @param {Object} ccfields\n * @private\n */\n _preparePaymentData: function (data, ccfields) {\n var preparedata;\n\n if (this.element.find('[data-container=\"' + this.options.gateway + '-cc-cvv\"]').length) {\n data[ccfields.cccvv] = this.element.find(\n '[data-container=\"' + this.options.gateway + '-cc-cvv\"]'\n ).val();\n }\n preparedata = this._prepareExpDate();\n data[ccfields.ccexpdate] = preparedata.month + this.options.dateDelim + preparedata.year;\n data[ccfields.ccnum] = this.element.find(\n '[data-container=\"' + this.options.gateway + '-cc-number\"]'\n ).val();\n\n return data;\n },\n\n /**\n * Grab Month and Year into one\n * @returns {Object}\n * @private\n */\n _prepareExpDate: function () {\n var year = this.element.find('[data-container=\"' + this.options.gateway + '-cc-year\"]').val(),\n month = parseInt(\n this.element.find('[data-container=\"' + this.options.gateway + '-cc-month\"]').val(),\n 10\n );\n\n if (year.length > this.options.expireYearLength) {\n year = year.substring(year.length - this.options.expireYearLength);\n }\n\n if (month < 10) {\n month = '0' + month;\n }\n\n return {\n month: month, year: year\n };\n }\n });\n\n return $.mage.transparent;\n});\n","Magento_Payment/js/cc-type.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'jquery',\n 'jquery-ui-modules/widget'\n], function ($) {\n 'use strict';\n\n $.widget('mage.creditCardType', {\n options: {\n typeCodes: ['SS', 'SM', 'SO'] // Type codes for Switch/Maestro/Solo credit cards.\n },\n\n /**\n * Bind change handler to select element and trigger the event to show/hide\n * the Switch/Maestro or Solo credit card type container for those credit card types.\n * @private\n */\n _create: function () {\n this.element.on('change', $.proxy(this._toggleCardType, this)).trigger('change');\n },\n\n /**\n * Toggle the Switch/Maestro and Solo credit card type container depending on which\n * credit card type is selected.\n * @private\n */\n _toggleCardType: function () {\n $(this.options.creditCardTypeContainer)\n .toggle($.inArray(this.element.val(), this.options.typeCodes) !== -1);\n }\n });\n\n return $.mage.creditCardType;\n});\n","Magento_Payment/js/view/payment/cc-form.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'underscore',\n 'Magento_Checkout/js/view/payment/default',\n 'Magento_Payment/js/model/credit-card-validation/credit-card-data',\n 'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator',\n 'mage/translate'\n], function (_, Component, creditCardData, cardNumberValidator, $t) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n creditCardType: '',\n creditCardExpYear: '',\n creditCardExpMonth: '',\n creditCardNumber: '',\n creditCardSsStartMonth: '',\n creditCardSsStartYear: '',\n creditCardSsIssue: '',\n creditCardVerificationNumber: '',\n selectedCardType: null\n },\n\n /** @inheritdoc */\n initObservable: function () {\n this._super()\n .observe([\n 'creditCardType',\n 'creditCardExpYear',\n 'creditCardExpMonth',\n 'creditCardNumber',\n 'creditCardVerificationNumber',\n 'creditCardSsStartMonth',\n 'creditCardSsStartYear',\n 'creditCardSsIssue',\n 'selectedCardType'\n ]);\n\n return this;\n },\n\n /**\n * Init component\n */\n initialize: function () {\n var self = this;\n\n this._super();\n\n //Set credit card number to credit card data object\n this.creditCardNumber.subscribe(function (value) {\n var result;\n\n self.selectedCardType(null);\n\n if (value === '' || value === null) {\n return false;\n }\n result = cardNumberValidator(value);\n\n if (!result.isPotentiallyValid && !result.isValid) {\n return false;\n }\n\n if (result.card !== null) {\n self.selectedCardType(result.card.type);\n creditCardData.creditCard = result.card;\n }\n\n if (result.isValid) {\n creditCardData.creditCardNumber = value;\n self.creditCardType(result.card.type);\n }\n });\n\n //Set expiration year to credit card data object\n this.creditCardExpYear.subscribe(function (value) {\n creditCardData.expirationYear = value;\n });\n\n //Set expiration month to credit card data object\n this.creditCardExpMonth.subscribe(function (value) {\n creditCardData.expirationMonth = value;\n });\n\n //Set cvv code to credit card data object\n this.creditCardVerificationNumber.subscribe(function (value) {\n creditCardData.cvvCode = value;\n });\n },\n\n /**\n * Get code\n * @returns {String}\n */\n getCode: function () {\n return 'cc';\n },\n\n /**\n * Get data\n * @returns {Object}\n */\n getData: function () {\n return {\n 'method': this.item.method,\n 'additional_data': {\n 'cc_cid': this.creditCardVerificationNumber(),\n 'cc_ss_start_month': this.creditCardSsStartMonth(),\n 'cc_ss_start_year': this.creditCardSsStartYear(),\n 'cc_ss_issue': this.creditCardSsIssue(),\n 'cc_type': this.creditCardType(),\n 'cc_exp_year': this.creditCardExpYear(),\n 'cc_exp_month': this.creditCardExpMonth(),\n 'cc_number': this.creditCardNumber()\n }\n };\n },\n\n /**\n * Get list of available credit card types\n * @returns {Object}\n */\n getCcAvailableTypes: function () {\n return window.checkoutConfig.payment.ccform.availableTypes[this.getCode()];\n },\n\n /**\n * Get payment icons\n * @param {String} type\n * @returns {Boolean}\n */\n getIcons: function (type) {\n return window.checkoutConfig.payment.ccform.icons.hasOwnProperty(type) ?\n window.checkoutConfig.payment.ccform.icons[type]\n : false;\n },\n\n /**\n * Get list of months\n * @returns {Object}\n */\n getCcMonths: function () {\n return window.checkoutConfig.payment.ccform.months[this.getCode()];\n },\n\n /**\n * Get list of years\n * @returns {Object}\n */\n getCcYears: function () {\n return window.checkoutConfig.payment.ccform.years[this.getCode()];\n },\n\n /**\n * Check if current payment has verification\n * @returns {Boolean}\n */\n hasVerification: function () {\n return window.checkoutConfig.payment.ccform.hasVerification[this.getCode()];\n },\n\n /**\n * @deprecated\n * @returns {Boolean}\n */\n hasSsCardType: function () {\n return window.checkoutConfig.payment.ccform.hasSsCardType[this.getCode()];\n },\n\n /**\n * Get image url for CVV\n * @returns {String}\n */\n getCvvImageUrl: function () {\n return window.checkoutConfig.payment.ccform.cvvImageUrl[this.getCode()];\n },\n\n /**\n * Get image for CVV\n * @returns {String}\n */\n getCvvImageHtml: function () {\n return '<img src=\"' + this.getCvvImageUrl() +\n '\" alt=\"' + $t('Card Verification Number Visual Reference') +\n '\" title=\"' + $t('Card Verification Number Visual Reference') +\n '\" />';\n },\n\n /**\n * Get unsanitized html for image for CVV\n * @returns {String}\n */\n getCvvImageUnsanitizedHtml: function () {\n return this.getCvvImageHtml();\n },\n\n /**\n * @deprecated\n * @returns {Object}\n */\n getSsStartYears: function () {\n return window.checkoutConfig.payment.ccform.ssStartYears[this.getCode()];\n },\n\n /**\n * Get list of available credit card types values\n * @returns {Object}\n */\n getCcAvailableTypesValues: function () {\n return _.map(this.getCcAvailableTypes(), function (value, key) {\n return {\n 'value': key,\n 'type': value\n };\n });\n },\n\n /**\n * Get list of available month values\n * @returns {Object}\n */\n getCcMonthsValues: function () {\n return _.map(this.getCcMonths(), function (value, key) {\n return {\n 'value': key,\n 'month': value\n };\n });\n },\n\n /**\n * Get list of available year values\n * @returns {Object}\n */\n getCcYearsValues: function () {\n return _.map(this.getCcYears(), function (value, key) {\n return {\n 'value': key,\n 'year': value\n };\n });\n },\n\n /**\n * @deprecated\n * @returns {Object}\n */\n getSsStartYearsValues: function () {\n return _.map(this.getSsStartYears(), function (value, key) {\n return {\n 'value': key,\n 'year': value\n };\n });\n },\n\n /**\n * Is legend available to display\n * @returns {Boolean}\n */\n isShowLegend: function () {\n return false;\n },\n\n /**\n * Get available credit card type by code\n * @param {String} code\n * @returns {String}\n */\n getCcTypeTitleByCode: function (code) {\n var title = '',\n keyValue = 'value',\n keyType = 'type';\n\n _.each(this.getCcAvailableTypesValues(), function (value) {\n if (value[keyValue] === code) {\n title = value[keyType];\n }\n });\n\n return title;\n },\n\n /**\n * Prepare credit card number to output\n * @param {String} number\n * @returns {String}\n */\n formatDisplayCcNumber: function (number) {\n return 'xxxx-' + number.substr(-4);\n },\n\n /**\n * Get credit card details\n * @returns {Array}\n */\n getInfo: function () {\n return [\n {\n 'name': 'Credit Card Type', value: this.getCcTypeTitleByCode(this.creditCardType())\n },\n {\n 'name': 'Credit Card Number', value: this.formatDisplayCcNumber(this.creditCardNumber())\n }\n ];\n }\n });\n});\n","Magento_Payment/js/view/payment/payments.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'uiComponent',\n 'Magento_Checkout/js/model/payment/renderer-list'\n], function (Component, rendererList) {\n 'use strict';\n\n rendererList.push(\n {\n type: 'free',\n component: 'Magento_Payment/js/view/payment/method-renderer/free-method'\n }\n );\n\n /** Add view logic here if needed */\n return Component.extend({});\n});\n","Magento_Payment/js/view/payment/iframe.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'jquery',\n 'Magento_Payment/js/view/payment/cc-form',\n 'Magento_Ui/js/model/messageList',\n 'mage/translate',\n 'Magento_Checkout/js/model/full-screen-loader',\n 'Magento_Checkout/js/action/set-payment-information',\n 'Magento_Checkout/js/model/payment/additional-validators',\n 'Magento_Ui/js/modal/alert'\n], function (\n $,\n Component,\n messageList,\n $t,\n fullScreenLoader,\n setPaymentInformationAction,\n additionalValidators,\n alert\n) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Payment/payment/iframe',\n timeoutId: null,\n timeoutMessage: 'Sorry, but something went wrong.'\n },\n\n /**\n * @returns {String}\n */\n getSource: function () {\n return window.checkoutConfig.payment.iframe.source[this.getCode()];\n },\n\n /**\n * @returns {String}\n */\n getControllerName: function () {\n return window.checkoutConfig.payment.iframe.controllerName[this.getCode()];\n },\n\n /**\n * @returns {String}\n */\n getPlaceOrderUrl: function () {\n return window.checkoutConfig.payment.iframe.placeOrderUrl[this.getCode()];\n },\n\n /**\n * @returns {String}\n */\n getCgiUrl: function () {\n return window.checkoutConfig.payment.iframe.cgiUrl[this.getCode()];\n },\n\n /**\n * @returns {String}\n */\n getSaveOrderUrl: function () {\n return window.checkoutConfig.payment.iframe.saveOrderUrl[this.getCode()];\n },\n\n /**\n * @returns {String}\n */\n getDateDelim: function () {\n return window.checkoutConfig.payment.iframe.dateDelim[this.getCode()];\n },\n\n /**\n * @returns {String}\n */\n getCardFieldsMap: function () {\n return window.checkoutConfig.payment.iframe.cardFieldsMap[this.getCode()];\n },\n\n /**\n * @returns {String}\n */\n getExpireYearLength: function () {\n return window.checkoutConfig.payment.iframe.expireYearLength[this.getCode()];\n },\n\n /**\n * @param {Object} parent\n * @returns {Function}\n */\n originalPlaceOrder: function (parent) {\n return parent.placeOrder.bind(parent);\n },\n\n /**\n * @returns {Number}\n */\n getTimeoutTime: function () {\n return window.checkoutConfig.payment.iframe.timeoutTime[this.getCode()];\n },\n\n /**\n * @returns {String}\n */\n getTimeoutMessage: function () {\n return $t(this.timeoutMessage);\n },\n\n /**\n * @override\n */\n placeOrder: function () {\n var self = this;\n\n if (this.validateHandler() &&\n additionalValidators.validate() &&\n this.isPlaceOrderActionAllowed() === true\n ) {\n fullScreenLoader.startLoader();\n\n this.isPlaceOrderActionAllowed(false);\n\n $.when(\n this.setPaymentInformation()\n ).done(\n this.done.bind(this)\n ).fail(\n this.fail.bind(this)\n ).always(\n function () {\n self.isPlaceOrderActionAllowed(true);\n }\n );\n\n this.initTimeoutHandler();\n }\n },\n\n /**\n * {Function}\n */\n setPaymentInformation: function () {\n return setPaymentInformationAction(\n this.messageContainer,\n {\n method: this.getCode()\n }\n );\n },\n\n /**\n * {Function}\n */\n initTimeoutHandler: function () {\n this.timeoutId = setTimeout(\n this.timeoutHandler.bind(this),\n this.getTimeoutTime()\n );\n\n $(window).off('clearTimeout')\n .on('clearTimeout', this.clearTimeout.bind(this));\n },\n\n /**\n * {Function}\n */\n clearTimeout: function () {\n clearTimeout(this.timeoutId);\n this.fail();\n\n return this;\n },\n\n /**\n * {Function}\n */\n timeoutHandler: function () {\n this.clearTimeout();\n\n alert(\n {\n content: this.getTimeoutMessage(),\n actions: {\n\n /**\n * {Function}\n */\n always: this.alertActionHandler.bind(this)\n }\n }\n );\n\n this.fail();\n },\n\n /**\n * {Function}\n */\n alertActionHandler: function () {\n fullScreenLoader.startLoader();\n window.location.reload();\n },\n\n /**\n * {Function}\n */\n fail: function () {\n fullScreenLoader.stopLoader();\n\n return this;\n },\n\n /**\n * {Function}\n */\n done: function () {\n this.placeOrderHandler().fail(function () {\n fullScreenLoader.stopLoader();\n });\n\n return this;\n }\n });\n});\n","Magento_Payment/js/view/payment/method-renderer/free-method.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'Magento_Checkout/js/view/payment/default',\n 'Magento_Checkout/js/model/quote'\n], function (Component, quote) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Payment/payment/free'\n },\n\n /** Returns is method available */\n isAvailable: function () {\n return quote.totals()['grand_total'] <= 0;\n }\n });\n});\n","Magento_Payment/js/model/credit-card-validation/credit-card-number-validator.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'mageUtils',\n 'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator',\n 'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator/credit-card-type'\n], function (utils, luhn10, creditCardTypes) {\n 'use strict';\n\n /**\n * @param {*} card\n * @param {*} isPotentiallyValid\n * @param {*} isValid\n * @return {Object}\n */\n function resultWrapper(card, isPotentiallyValid, isValid) {\n return {\n card: card,\n isValid: isValid,\n isPotentiallyValid: isPotentiallyValid\n };\n }\n\n return function (value) {\n var potentialTypes,\n cardType,\n valid,\n i,\n maxLength;\n\n if (utils.isEmpty(value)) {\n return resultWrapper(null, false, false);\n }\n\n value = value.replace(/\\s+/g, '');\n\n if (!/^\\d*$/.test(value)) {\n return resultWrapper(null, false, false);\n }\n\n potentialTypes = creditCardTypes.getCardTypes(value);\n\n if (potentialTypes.length === 0) {\n return resultWrapper(null, false, false);\n } else if (potentialTypes.length !== 1) {\n return resultWrapper(null, true, false);\n }\n\n cardType = potentialTypes[0];\n\n if (cardType.type === 'unionpay') { // UnionPay is not Luhn 10 compliant\n valid = true;\n } else {\n valid = luhn10(value);\n }\n\n for (i = 0; i < cardType.lengths.length; i++) {\n if (cardType.lengths[i] === value.length) {\n return resultWrapper(cardType, valid, valid);\n }\n }\n\n maxLength = Math.max.apply(null, cardType.lengths);\n\n if (value.length < maxLength) {\n return resultWrapper(cardType, true, false);\n }\n\n return resultWrapper(cardType, false, false);\n };\n});\n","Magento_Payment/js/model/credit-card-validation/cvv-validator.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([], function () {\n 'use strict';\n\n /**\n * @param {*} isValid\n * @param {*} isPotentiallyValid\n * @return {Object}\n */\n function resultWrapper(isValid, isPotentiallyValid) {\n return {\n isValid: isValid,\n isPotentiallyValid: isPotentiallyValid\n };\n }\n\n /**\n * CVV number validation.\n * Validate digit count for CVV code.\n *\n * @param {*} value\n * @param {Number} maxLength\n * @return {Object}\n */\n return function (value, maxLength) {\n var DEFAULT_LENGTH = 3;\n\n maxLength = maxLength || DEFAULT_LENGTH;\n\n if (!/^\\d*$/.test(value)) {\n return resultWrapper(false, false);\n }\n\n if (value.length === maxLength) {\n return resultWrapper(true, true);\n }\n\n if (value.length < maxLength) {\n return resultWrapper(false, true);\n }\n\n if (value.length > maxLength) {\n return resultWrapper(false, false);\n }\n };\n});\n","Magento_Payment/js/model/credit-card-validation/validator.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'jquery',\n 'Magento_Payment/js/model/credit-card-validation/cvv-validator',\n 'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator',\n 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator',\n 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator',\n 'Magento_Payment/js/model/credit-card-validation/credit-card-data',\n 'mage/translate'\n], function ($, cvvValidator, creditCardNumberValidator, yearValidator, monthValidator, creditCardData) {\n 'use strict';\n\n $('.payment-method-content input[type=\"number\"]').on('keyup', function () {\n if ($(this).val() < 0) {\n $(this).val($(this).val().replace(/^-/, ''));\n }\n });\n\n $.each({\n 'validate-card-type': [\n function (number, item, allowedTypes) {\n var cardInfo,\n i,\n l;\n\n if (!creditCardNumberValidator(number).isValid) {\n return false;\n }\n\n cardInfo = creditCardNumberValidator(number).card;\n\n for (i = 0, l = allowedTypes.length; i < l; i++) {\n if (cardInfo.title == allowedTypes[i].type) { //eslint-disable-line eqeqeq\n return true;\n }\n }\n\n return false;\n },\n $.mage.__('Please enter a valid credit card type number.')\n ],\n 'validate-card-number': [\n\n /**\n * Validate credit card number based on mod 10\n *\n * @param {*} number - credit card number\n * @return {Boolean}\n */\n function (number) {\n return creditCardNumberValidator(number).isValid;\n },\n $.mage.__('Please enter a valid credit card number.')\n ],\n 'validate-card-date': [\n\n /**\n * Validate credit card expiration month\n *\n * @param {String} date - month\n * @return {Boolean}\n */\n function (date) {\n return monthValidator(date).isValid;\n },\n $.mage.__('Incorrect credit card expiration month.')\n ],\n 'validate-card-cvv': [\n\n /**\n * Validate cvv\n *\n * @param {String} cvv - card verification value\n * @return {Boolean}\n */\n function (cvv) {\n var maxLength = creditCardData.creditCard ? creditCardData.creditCard.code.size : 3;\n\n return cvvValidator(cvv, maxLength).isValid;\n },\n $.mage.__('Please enter a valid credit card verification number.')\n ],\n 'validate-card-year': [\n\n /**\n * Validate credit card expiration year\n *\n * @param {String} date - year\n * @return {Boolean}\n */\n function (date) {\n return yearValidator(date).isValid;\n },\n $.mage.__('Incorrect credit card expiration year.')\n ]\n\n }, function (i, rule) {\n rule.unshift(i);\n $.validator.addMethod.apply($.validator, rule);\n });\n});\n","Magento_Payment/js/model/credit-card-validation/credit-card-data.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([], function () {\n 'use strict';\n\n return {\n creditCard: null,\n creditCardNumber: null,\n expirationMonth: null,\n expirationYear: null,\n cvvCode: null\n };\n});\n","Magento_Payment/js/model/credit-card-validation/expiration-date-validator.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'mageUtils',\n 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/parse-date',\n 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator',\n 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator'\n], function (utils, parseDate, expirationMonth, expirationYear) {\n 'use strict';\n\n /**\n * @param {*} isValid\n * @param {*} isPotentiallyValid\n * @param {*} month\n * @param {*} year\n * @return {Object}\n */\n function resultWrapper(isValid, isPotentiallyValid, month, year) {\n return {\n isValid: isValid,\n isPotentiallyValid: isPotentiallyValid,\n month: month,\n year: year\n };\n }\n\n return function (value) {\n var date,\n monthValid,\n yearValid;\n\n if (utils.isEmpty(value)) {\n return resultWrapper(false, false, null, null);\n }\n\n value = value.replace(/^(\\d\\d) (\\d\\d(\\d\\d)?)$/, '$1/$2');\n date = parseDate(value);\n monthValid = expirationMonth(date.month);\n yearValid = expirationYear(date.year);\n\n if (monthValid.isValid && yearValid.isValid) {\n return resultWrapper(true, true, date.month, date.year);\n }\n\n if (monthValid.isPotentiallyValid && yearValid.isPotentiallyValid) {\n return resultWrapper(false, true, null, null);\n }\n\n return resultWrapper(false, false, null, null);\n };\n});\n","Magento_Payment/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([], function () {\n 'use strict';\n\n /**\n * Luhn algorithm verification\n */\n return function (a, b, c, d, e) {\n for (d = +a[b = a.length - 1], e = 0; b--;) {\n c = +a[b];\n d += ++e % 2 ? 2 * c % 10 + (c > 4) : c;\n }\n\n return !(d % 10);\n };\n});\n","Magento_Payment/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/* @api */\ndefine([\n 'jquery',\n 'mageUtils'\n], function ($, utils) {\n 'use strict';\n\n var types = [\n {\n title: 'Visa',\n type: 'VI',\n pattern: '^4\\\\d*$',\n gaps: [4, 8, 12],\n lengths: [16],\n code: {\n name: 'CVV',\n size: 3\n }\n },\n {\n title: 'MasterCard',\n type: 'MC',\n pattern: '^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$',\n gaps: [4, 8, 12],\n lengths: [16],\n code: {\n name: 'CVC',\n size: 3\n }\n },\n {\n title: 'American Express',\n type: 'AE',\n pattern: '^3([47]\\\\d*)?$',\n isAmex: true,\n gaps: [4, 10],\n lengths: [15],\n code: {\n name: 'CID',\n size: 4\n }\n },\n {\n title: 'Diners',\n type: 'DN',\n pattern: '^(3(0[0-5]|095|6|[8-9]))\\\\d*$',\n gaps: [4, 10],\n lengths: [14, 16, 17, 18, 19],\n code: {\n name: 'CVV',\n size: 3\n }\n },\n {\n title: 'Discover',\n type: 'DI',\n pattern: '^(6011(0|[2-4]|74|7[7-9]|8[6-9]|9)|6(4[4-9]|5))\\\\d*$',\n gaps: [4, 8, 12],\n lengths: [16, 17, 18, 19],\n code: {\n name: 'CID',\n size: 3\n }\n },\n {\n title: 'JCB',\n type: 'JCB',\n pattern: '^35(2[8-9]|[3-8])\\\\d*$',\n gaps: [4, 8, 12],\n lengths: [16, 17, 18, 19],\n code: {\n name: 'CVV',\n size: 3\n }\n },\n {\n title: 'UnionPay',\n type: 'UN',\n pattern: '^(622(1(2[6-9]|[3-9])|[3-8]|9([[0-1]|2[0-5]))|62[4-6]|628([2-8]))\\\\d*?$',\n gaps: [4, 8, 12],\n lengths: [16, 17, 18, 19],\n code: {\n name: 'CVN',\n size: 3\n }\n },\n {\n title: 'Maestro International',\n type: 'MI',\n pattern: '^(5(0|[6-9])|63|67(?!59|6770|6774))\\\\d*$',\n gaps: [4, 8, 12],\n lengths: [12, 13, 14, 15, 16, 17, 18, 19],\n code: {\n name: 'CVC',\n size: 3\n }\n },\n {\n title: 'Maestro Domestic',\n type: 'MD',\n pattern: '^6759(?!24|38|40|6[3-9]|70|76)|676770|676774\\\\d*$',\n gaps: [4, 8, 12],\n lengths: [12, 13, 14, 15, 16, 17, 18, 19],\n code: {\n name: 'CVC',\n size: 3\n }\n },\n {\n title: 'Hipercard',\n type: 'HC',\n pattern: '^((606282)|(637095)|(637568)|(637599)|(637609)|(637612))\\\\d*$',\n gaps: [4, 8, 12],\n lengths: [13, 16],\n code: {\n name: 'CVC',\n size: 3\n }\n },\n {\n title: 'Elo',\n type: 'ELO',\n pattern: '^((509091)|(636368)|(636297)|(504175)|(438935)|(40117[8-9])|(45763[1-2])|' +\n '(457393)|(431274)|(50990[0-2])|(5099[7-9][0-9])|(50996[4-9])|(509[1-8][0-9][0-9])|' +\n '(5090(0[0-2]|0[4-9]|1[2-9]|[24589][0-9]|3[1-9]|6[0-46-9]|7[0-24-9]))|' +\n '(5067(0[0-24-8]|1[0-24-9]|2[014-9]|3[0-379]|4[0-9]|5[0-3]|6[0-5]|7[0-8]))|' +\n '(6504(0[5-9]|1[0-9]|2[0-9]|3[0-9]))|' +\n '(6504(8[5-9]|9[0-9])|6505(0[0-9]|1[0-9]|2[0-9]|3[0-8]))|' +\n '(6505(4[1-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-8]))|' +\n '(6507(0[0-9]|1[0-8]))|(65072[0-7])|(6509(0[1-9]|1[0-9]|20))|' +\n '(6516(5[2-9]|6[0-9]|7[0-9]))|(6550(0[0-9]|1[0-9]))|' +\n '(6550(2[1-9]|3[0-9]|4[0-9]|5[0-8])))\\\\d*$',\n gaps: [4, 8, 12],\n lengths: [16],\n code: {\n name: 'CVC',\n size: 3\n }\n },\n {\n title: 'Aura',\n type: 'AU',\n pattern: '^5078\\\\d*$',\n gaps: [4, 8, 12],\n lengths: [19],\n code: {\n name: 'CVC',\n size: 3\n }\n }\n ];\n\n return {\n /**\n * @param {*} cardNumber\n * @return {Array}\n */\n getCardTypes: function (cardNumber) {\n var i, value,\n result = [];\n\n if (utils.isEmpty(cardNumber)) {\n return result;\n }\n\n if (cardNumber === '') {\n return $.extend(true, {}, types);\n }\n\n for (i = 0; i < types.length; i++) {\n value = types[i];\n\n if (new RegExp(value.pattern).test(cardNumber)) {\n result.push($.extend(true, {}, value));\n }\n }\n\n return result;\n }\n };\n});\n","Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([], function () {\n 'use strict';\n\n /**\n * @param {*} isValid\n * @param {*} isPotentiallyValid\n * @return {Object}\n */\n function resultWrapper(isValid, isPotentiallyValid) {\n return {\n isValid: isValid,\n isPotentiallyValid: isPotentiallyValid\n };\n }\n\n return function (value) {\n var month,\n monthValid;\n\n if (value.replace(/\\s/g, '') === '' || value === '0') {\n return resultWrapper(false, true);\n }\n\n if (!/^\\d*$/.test(value)) {\n return resultWrapper(false, false);\n }\n\n if (isNaN(value)) {\n return resultWrapper(false, false);\n }\n\n month = parseInt(value, 10);\n monthValid = month > 0 && month < 13;\n\n return resultWrapper(monthValid, monthValid);\n };\n});\n","Magento_Payment/js/model/credit-card-validation/expiration-date-validator/parse-date.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([], function () {\n 'use strict';\n\n return function (value) {\n var month, len;\n\n if (value.match('/')) {\n value = value.split(/\\s*\\/\\s*/g);\n\n return {\n month: value[0],\n year: value.slice(1).join()\n };\n }\n\n len = value[0] === '0' || value.length > 5 || value.length === 4 || value.length === 3 ? 2 : 1;\n month = value.substr(0, len);\n\n return {\n month: month,\n year: value.substr(month.length, 4)\n };\n };\n});\n","Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([], function () {\n 'use strict';\n\n /**\n * @param {*} isValid\n * @param {*} isPotentiallyValid\n * @return {Object}\n */\n function resultWrapper(isValid, isPotentiallyValid) {\n return {\n isValid: isValid,\n isPotentiallyValid: isPotentiallyValid\n };\n }\n\n return function (value) {\n var currentYear = new Date().getFullYear(),\n len = value.length,\n valid,\n expMaxLifetime = 19;\n\n if (value.replace(/\\s/g, '') === '') {\n return resultWrapper(false, true);\n }\n\n if (!/^\\d*$/.test(value)) {\n return resultWrapper(false, false);\n }\n\n if (len !== 4) {\n return resultWrapper(false, true);\n }\n\n value = parseInt(value, 10);\n valid = value >= currentYear && value <= currentYear + expMaxLifetime;\n\n return resultWrapper(valid, valid);\n };\n});\n","Magento_ReCaptchaStorePickup/js/reCaptchaStorePickup.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine(['Magento_ReCaptchaFrontendUi/js/reCaptcha'], function (reCaptcha) {\n 'use strict';\n\n return reCaptcha.extend({\n\n /**\n * @inheritdoc\n */\n renderReCaptcha: function () {\n this.captchaInitialized = false;\n this._super();\n }\n });\n});\n","js-cookie/cookie-wrapper.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'js-cookie/js.cookie'\n], function ($, cookie) {\n 'use strict';\n\n window.Cookies = window.Cookies || cookie;\n\n var config = $.cookie = function (key, value, options) {\n if (value !== undefined) {\n options = $.extend({}, config.defaults, options);\n\n return cookie.set(key, value, options);\n }\n\n var result = key ? undefined : {},\n cookies = document.cookie ? document.cookie.split('; ') : [],\n i;\n\n for (i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('='),\n name = config.raw ? parts.shift() : decodeURIComponent(parts.shift()),\n cookieValue = parts.join('=');\n\n if (key && key === name) {\n result = decodeURIComponent(cookieValue.replace('/\\\\+/g', ' '));\n break;\n }\n\n if (!key && (cookieValue = decodeURIComponent(cookieValue.replace('/\\\\+/g', ' '))) !== undefined) {\n result[name] = cookieValue;\n }\n }\n\n return result;\n };\n\n config.defaults = {};\n\n $.removeCookie = function (key, options) {\n if ($.cookie(key) === undefined) {\n return false;\n }\n\n $.cookie(key, '', $.extend({}, options, { expires: -1 }));\n return !$.cookie(key);\n };\n});\n","js-cookie/js.cookie.js":"/*! js-cookie v3.0.5 | MIT */\n;\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, (function () {\n var current = global.Cookies;\n var exports = global.Cookies = factory();\n exports.noConflict = function () { global.Cookies = current; return exports; };\n })());\n})(this, (function () { 'use strict';\n\n /* eslint-disable no-var */\n function assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n }\n /* eslint-enable no-var */\n\n /* eslint-disable no-var */\n var defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n };\n /* eslint-enable no-var */\n\n /* eslint-disable no-var */\n\n function init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n }\n\n var api = init(defaultConverter, { path: '/' });\n /* eslint-enable no-var */\n\n return api;\n\n}));\n","Magento_InstantPurchase/js/view/instant-purchase.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'ko',\n 'jquery',\n 'underscore',\n 'uiComponent',\n 'Magento_Ui/js/modal/confirm',\n 'Magento_Customer/js/customer-data',\n 'mage/url',\n 'mage/template',\n 'mage/translate',\n 'text!Magento_InstantPurchase/template/confirmation.html',\n 'mage/validation'\n], function (ko, $, _, Component, confirm, customerData, urlBuilder, mageTemplate, $t, confirmationTemplate) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_InstantPurchase/instant-purchase',\n buttonText: $t('Instant Purchase'),\n purchaseUrl: urlBuilder.build('instantpurchase/button/placeOrder'),\n showButton: false,\n paymentToken: null,\n shippingAddress: null,\n billingAddress: null,\n shippingMethod: null,\n productFormSelector: '#product_addtocart_form',\n confirmationTitle: $t('Instant Purchase Confirmation'),\n confirmationData: {\n message: $t('Are you sure you want to place order and pay?'),\n shippingAddressTitle: $t('Shipping Address'),\n billingAddressTitle: $t('Billing Address'),\n paymentMethodTitle: $t('Payment Method'),\n shippingMethodTitle: $t('Shipping Method')\n }\n },\n\n /** @inheritdoc */\n initialize: function () {\n var instantPurchase = customerData.get('instant-purchase');\n\n this._super();\n\n this.setPurchaseData(instantPurchase());\n instantPurchase.subscribe(this.setPurchaseData, this);\n },\n\n /** @inheritdoc */\n initObservable: function () {\n this._super()\n .observe('showButton paymentToken shippingAddress billingAddress shippingMethod');\n\n return this;\n },\n\n /**\n * Set data from customerData.\n *\n * @param {Object} data\n */\n setPurchaseData: function (data) {\n this.showButton(data.available);\n this.paymentToken(data.paymentToken);\n this.shippingAddress(data.shippingAddress);\n this.billingAddress(data.billingAddress);\n this.shippingMethod(data.shippingMethod);\n },\n\n /**\n * Confirmation method\n */\n instantPurchase: function () {\n var form = $(this.productFormSelector),\n confirmTemplate = mageTemplate(confirmationTemplate),\n confirmData = _.extend({}, this.confirmationData, {\n paymentToken: this.paymentToken().summary,\n shippingAddress: this.shippingAddress().summary,\n billingAddress: this.billingAddress().summary,\n shippingMethod: this.shippingMethod().summary\n });\n\n if (!(form.validation() && form.validation('isValid'))) {\n return;\n }\n\n confirm({\n title: this.confirmationTitle,\n content: confirmTemplate({\n data: confirmData\n }),\n actions: {\n /** @inheritdoc */\n confirm: function () {\n $.ajax({\n url: this.purchaseUrl,\n data: form.serialize(),\n type: 'post',\n dataType: 'json',\n\n /** Show loader before send */\n beforeSend: function () {\n $('body').trigger('processStart');\n }\n }).always(function () {\n $('body').trigger('processStop');\n });\n }.bind(this)\n }\n });\n }\n });\n});\n","Magento_Tax/js/price/adjustment.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'Magento_Ui/js/grid/columns/column',\n 'mage/translate'\n], function (Element, $t) {\n 'use strict';\n\n return Element.extend({\n defaults: {\n bodyTmpl: 'Magento_Tax/price/adjustment',\n taxPriceType: 'final_price',\n taxPriceCssClass: 'price-including-tax',\n bothPrices: 3,\n inclTax: 2,\n exclTax: 1,\n modules: {\n price: '${ $.parentName }'\n },\n listens: {\n price: 'initializePriceAttributes'\n }\n },\n\n /**\n * {@inheritdoc}\n */\n initialize: function () {\n this._super()\n .initializePriceAttributes();\n\n return this;\n },\n\n /**\n * Update parent price.\n *\n * @returns {Object} Chainable.\n */\n initializePriceAttributes: function () {\n if (this.displayBothPrices && this.price()) {\n this.price().priceWrapperCssClasses = this.taxPriceCssClass;\n this.price().priceWrapperAttr = {\n 'data-label': $t('Incl. Tax')\n };\n }\n\n return this;\n },\n\n /**\n * Get price tax adjustment.\n *\n * @param {Object} row\n * @return {HTMLElement} tax html\n */\n getTax: function (row) {\n return row['price_info']['extension_attributes']['tax_adjustments']['formatted_prices'][this.taxPriceType];\n },\n\n /**\n * UnsanitizedHtml version of getTax.\n *\n * @param {Object} row\n * @return {HTMLElement} tax html\n */\n getTaxUnsanitizedHtml: function (row) {\n return this.getTax(row);\n },\n\n /**\n * Set price tax type.\n *\n * @param {String} priceType\n * @return {Object}\n */\n setPriceType: function (priceType) {\n this.taxPriceType = priceType;\n\n return this;\n },\n\n /**\n * Return whether display setting is to display\n * both price including tax and price excluding tax.\n *\n * @return {Boolean}\n */\n displayBothPrices: function () {\n return +this.source.data.displayTaxes === this.bothPrices;\n },\n\n /**\n * Return whether display setting is to display price including tax.\n *\n * @return {Boolean}\n */\n displayPriceIncludeTax: function () {\n return +this.source.data.displayTaxes === this.inclTax;\n },\n\n /**\n * Return whether display setting is to display price excluding tax.\n *\n * @return {Boolean}\n */\n displayPriceExclTax: function () {\n return +this.source.data.displayTaxes === this.exclTax;\n }\n });\n});\n","Magento_Tax/js/view/checkout/cart/totals/tax.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'Magento_Tax/js/view/checkout/summary/tax',\n 'Magento_Checkout/js/model/totals'\n], function (Component, totals) {\n 'use strict';\n\n var isFullTaxSummaryDisplayed = window.checkoutConfig.isFullTaxSummaryDisplayed,\n isZeroTaxDisplayed = window.checkoutConfig.isZeroTaxDisplayed;\n\n return Component.extend({\n /**\n * @override\n */\n ifShowValue: function () {\n if (this.isFullMode() && this.getPureValue() == 0) { //eslint-disable-line eqeqeq\n return isZeroTaxDisplayed;\n }\n\n return true;\n },\n\n /**\n * @override\n */\n ifShowDetails: function () {\n return this.getPureValue() > 0 && isFullTaxSummaryDisplayed;\n },\n\n /**\n * @override\n */\n isCalculated: function () {\n return this.totals() && totals.getSegment('tax') !== null;\n }\n });\n});\n","Magento_Tax/js/view/checkout/cart/totals/shipping.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'Magento_Tax/js/view/checkout/summary/shipping',\n 'Magento_Checkout/js/model/quote'\n], function (Component, quote) {\n 'use strict';\n\n return Component.extend({\n /**\n * @override\n */\n isCalculated: function () {\n return !!quote.shippingMethod();\n },\n\n /**\n * @override\n */\n getShippingMethodTitle: function () {\n return '(' + this._super() + ')';\n }\n });\n});\n","Magento_Tax/js/view/checkout/cart/totals/grand-total.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'Magento_Tax/js/view/checkout/summary/grand-total'\n], function (Component) {\n 'use strict';\n\n return Component.extend({\n /**\n * @override\n */\n isDisplayed: function () {\n return true;\n }\n });\n});\n","Magento_Tax/js/view/checkout/minicart/subtotal/totals.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'ko',\n 'uiComponent',\n 'Magento_Customer/js/customer-data'\n], function (ko, Component, customerData) {\n 'use strict';\n\n return Component.extend({\n displaySubtotal: ko.observable(true),\n\n /**\n * @override\n */\n initialize: function () {\n this._super();\n this.cart = customerData.get('cart');\n }\n });\n});\n","Magento_Tax/js/view/checkout/summary/tax.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'ko',\n 'Magento_Checkout/js/view/summary/abstract-total',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Checkout/js/model/totals',\n 'mage/translate',\n 'underscore'\n], function (ko, Component, quote, totals, $t, _) {\n 'use strict';\n\n var isTaxDisplayedInGrandTotal = window.checkoutConfig.includeTaxInGrandTotal,\n isFullTaxSummaryDisplayed = window.checkoutConfig.isFullTaxSummaryDisplayed,\n isZeroTaxDisplayed = window.checkoutConfig.isZeroTaxDisplayed,\n taxAmount = 0,\n rates = 0;\n\n return Component.extend({\n defaults: {\n isTaxDisplayedInGrandTotal: isTaxDisplayedInGrandTotal,\n notCalculatedMessage: $t('Not yet calculated'),\n template: 'Magento_Tax/checkout/summary/tax'\n },\n totals: quote.getTotals(),\n isFullTaxSummaryDisplayed: isFullTaxSummaryDisplayed,\n\n /**\n * @return {Boolean}\n */\n ifShowValue: function () {\n if (this.isFullMode() && this.getPureValue() == 0) { //eslint-disable-line eqeqeq\n return isZeroTaxDisplayed;\n }\n\n return true;\n },\n\n /**\n * @return {Boolean}\n */\n ifShowDetails: function () {\n if (!this.isFullMode()) {\n return false;\n }\n\n return this.getPureValue() > 0 && isFullTaxSummaryDisplayed;\n },\n\n /**\n * @return {Number}\n */\n getPureValue: function () {\n var amount = 0,\n taxTotal;\n\n if (this.totals()) {\n taxTotal = totals.getSegment('tax');\n\n if (taxTotal) {\n amount = taxTotal.value;\n }\n }\n\n return amount;\n },\n\n /**\n * @return {*|Boolean}\n */\n isCalculated: function () {\n return this.totals() && this.isFullMode() && totals.getSegment('tax') != null;\n },\n\n /**\n * @return {*}\n */\n getValue: function () {\n var amount;\n\n if (!this.isCalculated()) {\n return this.notCalculatedMessage;\n }\n amount = totals.getSegment('tax').value;\n\n return this.getFormattedPrice(amount);\n },\n\n /**\n * @param {*} amount\n * @return {*|String}\n */\n formatPrice: function (amount) {\n return this.getFormattedPrice(amount);\n },\n\n /**\n * @param {*} parent\n * @param {*} percentage\n * @return {*|String}\n */\n getTaxAmount: function (parent, percentage) {\n var totalPercentage = 0;\n\n taxAmount = parent.amount;\n rates = parent.rates;\n _.each(rates, function (rate) {\n totalPercentage += parseFloat(rate.percent);\n });\n\n return this.getFormattedPrice(this.getPercentAmount(taxAmount, totalPercentage, percentage));\n },\n\n /**\n * @param {*} amount\n * @param {*} totalPercentage\n * @param {*} percentage\n * @return {*|String}\n */\n getPercentAmount: function (amount, totalPercentage, percentage) {\n return parseFloat(amount * percentage / totalPercentage);\n },\n\n /**\n * @return {Array}\n */\n getDetails: function () {\n var taxSegment = totals.getSegment('tax');\n\n if (taxSegment && taxSegment['extension_attributes']) {\n return taxSegment['extension_attributes']['tax_grandtotal_details'];\n }\n\n return [];\n }\n });\n});\n","Magento_Tax/js/view/checkout/summary/subtotal.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'Magento_Checkout/js/view/summary/abstract-total',\n 'Magento_Checkout/js/model/quote'\n], function (Component, quote) {\n 'use strict';\n\n var displaySubtotalMode = window.checkoutConfig.reviewTotalsDisplayMode;\n\n return Component.extend({\n defaults: {\n displaySubtotalMode: displaySubtotalMode,\n template: 'Magento_Tax/checkout/summary/subtotal'\n },\n totals: quote.getTotals(),\n\n /**\n * @return {*|String}\n */\n getValue: function () {\n var price = 0;\n\n if (this.totals()) {\n price = this.totals().subtotal;\n }\n\n return this.getFormattedPrice(price);\n },\n\n /**\n * @return {Boolean}\n */\n isBothPricesDisplayed: function () {\n return this.displaySubtotalMode == 'both'; //eslint-disable-line eqeqeq\n },\n\n /**\n * @return {Boolean}\n */\n isIncludingTaxDisplayed: function () {\n return this.displaySubtotalMode == 'including'; //eslint-disable-line eqeqeq\n },\n\n /**\n * @return {*|String}\n */\n getValueInclTax: function () {\n var price = 0;\n\n if (this.totals()) {\n price = this.totals()['subtotal_incl_tax'];\n }\n\n return this.getFormattedPrice(price);\n }\n });\n});\n","Magento_Tax/js/view/checkout/summary/shipping.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'jquery',\n 'Magento_Checkout/js/view/summary/shipping',\n 'Magento_Checkout/js/model/quote'\n], function ($, Component, quote) {\n 'use strict';\n\n var displayMode = window.checkoutConfig.reviewShippingDisplayMode;\n\n return Component.extend({\n defaults: {\n displayMode: displayMode,\n template: 'Magento_Tax/checkout/summary/shipping'\n },\n\n /**\n * @return {Boolean}\n */\n isBothPricesDisplayed: function () {\n return this.displayMode == 'both'; //eslint-disable-line eqeqeq\n },\n\n /**\n * @return {Boolean}\n */\n isIncludingDisplayed: function () {\n return this.displayMode == 'including'; //eslint-disable-line eqeqeq\n },\n\n /**\n * @return {Boolean}\n */\n isExcludingDisplayed: function () {\n return this.displayMode == 'excluding'; //eslint-disable-line eqeqeq\n },\n\n /**\n * @return {*|Boolean}\n */\n isCalculated: function () {\n return this.totals() && this.isFullMode() && quote.shippingMethod() != null;\n },\n\n /**\n * @return {*}\n */\n getIncludingValue: function () {\n var price;\n\n if (!this.isCalculated()) {\n return this.notCalculatedMessage;\n }\n price = this.totals()['shipping_incl_tax'];\n\n return this.getFormattedPrice(price);\n },\n\n /**\n * @return {*}\n */\n getExcludingValue: function () {\n var price;\n\n if (!this.isCalculated()) {\n return this.notCalculatedMessage;\n }\n price = this.totals()['shipping_amount'];\n\n return this.getFormattedPrice(price);\n }\n });\n});\n","Magento_Tax/js/view/checkout/summary/grand-total.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'Magento_Checkout/js/view/summary/abstract-total',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Catalog/js/price-utils',\n 'Magento_Checkout/js/model/totals'\n], function (Component, quote, priceUtils, totals) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n isFullTaxSummaryDisplayed: window.checkoutConfig.isFullTaxSummaryDisplayed || false,\n template: 'Magento_Tax/checkout/summary/grand-total'\n },\n totals: quote.getTotals(),\n isTaxDisplayedInGrandTotal: window.checkoutConfig.includeTaxInGrandTotal || false,\n\n /**\n * @return {*}\n */\n isDisplayed: function () {\n return this.isFullMode();\n },\n\n /**\n * @return {*|String}\n */\n getValue: function () {\n var price = 0;\n\n if (this.totals()) {\n price = totals.getSegment('grand_total').value;\n }\n\n return this.getFormattedPrice(price);\n },\n\n /**\n * @return {*|String}\n */\n getBaseValue: function () {\n var price = 0;\n\n if (this.totals()) {\n price = this.totals()['base_grand_total'];\n }\n\n return priceUtils.formatPriceLocale(price, quote.getBasePriceFormat());\n },\n\n /**\n * @return {*}\n */\n getGrandTotalExclTax: function () {\n var total = this.totals(),\n amount;\n\n if (!total) {\n return 0;\n }\n\n amount = total['grand_total'] - total['tax_amount'];\n\n if (amount < 0) {\n amount = 0;\n }\n\n return this.getFormattedPrice(amount);\n },\n\n /**\n * @return {Boolean}\n */\n isBaseGrandTotalDisplayNeeded: function () {\n var total = this.totals();\n\n if (!total) {\n return false;\n }\n\n return total['base_currency_code'] != total['quote_currency_code']; //eslint-disable-line eqeqeq\n }\n });\n});\n","Magento_Tax/js/view/checkout/summary/item/details/subtotal.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'Magento_Checkout/js/view/summary/item/details/subtotal'\n], function (subtotal) {\n 'use strict';\n\n var displayPriceMode = window.checkoutConfig.reviewItemPriceDisplayMode || 'including';\n\n return subtotal.extend({\n defaults: {\n displayPriceMode: displayPriceMode,\n template: 'Magento_Tax/checkout/summary/item/details/subtotal'\n },\n\n /**\n * @return {Boolean}\n */\n isPriceInclTaxDisplayed: function () {\n return displayPriceMode == 'both' || displayPriceMode == 'including'; //eslint-disable-line eqeqeq\n },\n\n /**\n * @return {Boolean}\n */\n isPriceExclTaxDisplayed: function () {\n return displayPriceMode == 'both' || displayPriceMode == 'excluding'; //eslint-disable-line eqeqeq\n },\n\n /**\n * @param {Object} quoteItem\n * @return {*|String}\n */\n getValueInclTax: function (quoteItem) {\n return this.getFormattedPrice(quoteItem['row_total_incl_tax']);\n },\n\n /**\n * @param {Object} quoteItem\n * @return {*|String}\n */\n getValueExclTax: function (quoteItem) {\n return this.getFormattedPrice(quoteItem['row_total']);\n }\n\n });\n});\n","Magento_Tax/js/view/checkout/shipping_method/price.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n/**\n * @api\n */\n\ndefine([\n 'uiComponent',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Catalog/js/price-utils'\n], function (Component, quote, priceUtils) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Magento_Tax/checkout/shipping_method/price'\n },\n isDisplayShippingPriceExclTax: window.checkoutConfig.isDisplayShippingPriceExclTax,\n isDisplayShippingBothPrices: window.checkoutConfig.isDisplayShippingBothPrices,\n\n /**\n * @param {Object} item\n * @return {Boolean}\n */\n isPriceEqual: function (item) {\n return item['price_excl_tax'] != item['price_incl_tax']; //eslint-disable-line eqeqeq\n },\n\n /**\n * @param {*} price\n * @return {*|String}\n */\n getFormattedPrice: function (price) {\n //todo add format data\n return priceUtils.formatPriceLocale(price, quote.getPriceFormat());\n }\n });\n});\n","Magento_OrderCancellationUi/js/cancel-order-modal.js":"/**\n * Copyright 2023 Adobe\n * All Rights Reserved.\n */\ndefine([\n 'jquery',\n 'Magento_Ui/js/modal/modal',\n 'Magento_Customer/js/customer-data'\n],function ($, modal, customerData) {\n 'use strict';\n\n return function (config, element) {\n let order_id = config.order_id,\n options = {\n type: 'popup',\n responsive: true,\n title: 'Cancel Order',\n buttons: [{\n text: $.mage.__('Close'),\n class: 'action-secondary action-dismiss close-modal-button',\n\n /** @inheritdoc */\n click: function () {\n this.closeModal();\n }\n }, {\n text: $.mage.__('Confirm'),\n class: 'action-primary action-accept cancel-order-button',\n\n /** @inheritdoc */\n click: function () {\n let thisModal = this,\n reason = $('#cancel-order-reason-' + order_id).find(':selected').text(),\n mutation = `\nmutation cancelOrder($order_id: ID!, $reason: String!) {\n cancelOrder(input: {order_id: $order_id, reason: $reason}) {\n error\n order {\n status\n }\n }\n}`;\n\n $.ajax({\n showLoader: true,\n type: 'POST',\n url: `${config.url}graphql`,\n contentType: 'application/json',\n data: JSON.stringify({\n query: mutation,\n variables: {\n 'order_id': config.order_id,\n 'reason': reason\n }\n }),\n complete: function (response) {\n let type = 'success',\n message;\n\n if (response.responseJSON.data.cancelOrder.error !== null) {\n message = $.mage.__(response.responseJSON.data.cancelOrder.error);\n type = 'error';\n } else {\n message = $.mage.__(response.responseJSON.data.cancelOrder.order.status);\n location.reload();\n }\n\n setTimeout(function () {\n customerData.set('messages', {\n messages: [{\n text: message,\n type: type\n }]\n });\n }, 1000);\n }\n }).always(function () {\n thisModal.closeModal(true);\n });\n }\n }]\n };\n\n $(element).on('click', function () {\n $('#cancel-order-modal-' + order_id).modal('openModal');\n });\n\n modal(options, $('#cancel-order-modal-' + order_id));\n };\n});\n","Magento_Translation/js/add-class.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine(['jquery'], function ($) {\n 'use strict';\n\n return function (config, element) {\n $(element).addClass(config.class);\n };\n});\n","Magento_Translation/js/i18n-config.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\n(function () {\n 'use strict';\n\n require.config({\n config: {\n 'Magento_Ui/js/lib/knockout/bindings/i18n': {\n inlineTranslation: true\n }\n }\n });\n})();\n","Magento_Translation/js/mage-translation-dictionary.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'text!js-translation.json'\n], function (dict) {\n 'use strict';\n\n return JSON.parse(dict);\n});\n","Magento_CatalogSearch/js/search-terms-log.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\ndefine([\n 'jquery',\n 'mageUtils'\n], function ($, utils) {\n 'use strict';\n\n return function (data) {\n $.ajax({\n method: 'GET',\n url: data.url,\n data: {\n 'q': utils.getUrlParameters(window.location.href).q\n }\n });\n };\n});\n","Amasty_Rewards/js/guest-highlight.js":"define([\n 'uiComponent',\n 'mage/translate',\n], function (Component, $t) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Amasty_Rewards/guest-highlight',\n captionStartText : $t('You can earn'),\n captionAfterText: '',\n captionRegistrationText: $t('for registration!'),\n captionEndText: '',\n frontend_class: '',\n highlight: []\n },\n\n initObservable: function () {\n this._super().observe([ 'highlight' ]);\n if (this.highlight._latestValue.need_to_change_message === 1) {\n this.captionAfterText = $t('for making a purchase! Available for');\n this.captionRegistrationText = $t('registered');\n this.captionEndText = $t('customers only.');\n }\n\n return this;\n }\n });\n});\n","Amasty_Rewards/js/amreward-points.js":"/*jshint browser:true jquery:true*/\ndefine([\n \"jquery\",\n \"Magento_Ui/js/modal/modal\"\n], function($){\n \"use strict\";\n\n $.widget('mage.amrewardPoints', {\n options: {\n },\n _create: function () {\n this.rewardAmount = $(this.options.rewardAmount);\n\n this.removeReward = $(this.options.removeRewardSelector);\n\n $(this.options.applyButton).on('click', $.proxy(function () {\n this.rewardAmount.attr('data-validate', '{required:true}');\n\n this.removeReward.attr('value', '0');\n $(this.element).validation().submit();\n }, this));\n\n $(this.options.cancelButton).on('click', $.proxy(function () {\n this.rewardAmount.removeAttr('data-validate');\n this.removeReward.attr('value', '1');\n this.element.submit();\n }, this));\n\n if (!this.isGreaterThanMinimumBalance()) {\n this.getMinimumRewardNoteDOM().show();\n this.disableRewardInput();\n\n }\n },\n\n /**\n *\n * @returns {boolean}\n */\n isGreaterThanMinimumBalance: function () {\n var realBalance = this.options.customerBalance;\n\n if (this.options.usedPoints) {\n realBalance += this.options.usedPoints;\n }\n\n return !this.options.minimumBalance || (realBalance >= this.options.minimumBalance);\n },\n\n /**\n * @return void\n */\n disableRewardInput: function() {\n $(this.options.applyButton).prop(\"disabled\", true);\n $(this.options.rewardAmount).prop(\"disabled\", true);\n },\n\n /**\n *\n * @returns {*|jQuery|HTMLElement}\n */\n getMinimumRewardNoteDOM: function() {\n return $(this.options.minimumNoteSelector);\n }\n });\n\n return $.mage.amrewardPoints;\n});\n","Amasty_Rewards/js/action/cancel-reward.js":"/**\n * Customer store credit(balance) application\n */\ndefine([\n 'jquery',\n 'Magento_Checkout/js/model/quote',\n 'Magento_Checkout/js/model/url-builder',\n 'Magento_Checkout/js/model/error-processor',\n 'Amasty_Rewards/js/model/payment/reward-messages',\n 'mage/storage',\n 'Magento_Checkout/js/action/get-payment-information',\n 'Magento_Checkout/js/model/totals',\n 'mage/translate',\n 'Magento_Checkout/js/model/full-screen-loader'\n], function ($, quote, urlBuilder, errorProcessor, messageContainer, storage, getPaymentInformationAction, totals, $t,\n fullScreenLoader\n) {\n 'use strict';\n\n return function (isApplied) {\n var url = urlBuilder.createUrl('/carts/mine/points/delete', {}),\n message = $t('You Canceled Reward.');\n\n messageContainer.clear();\n fullScreenLoader.startLoader();\n\n return storage.delete(\n url,\n false\n ).done(function () {\n var deferred = $.Deferred();\n\n totals.isLoading(true);\n getPaymentInformationAction(deferred);\n $.when(deferred).done(function () {\n isApplied(false);\n totals.isLoading(false);\n fullScreenLoader.stopLoader();\n });\n messageContainer.addSuccessMessage({\n 'message': message\n });\n }).fail(function (response) {\n totals.isLoading(false);\n fullScreenLoader.stopLoader();\n errorProcessor.process(response, messageContainer);\n });\n };\n});","Amasty_Rewards/js/action/add-reward.js":"define([\n 'ko',\n 'jquery',\n 'Magento_Checkout/js/model/quote',\n 'Amasty_Rewards/js/model/resource-url-manager',\n 'Magento_Checkout/js/model/error-processor',\n 'Amasty_Rewards/js/model/payment/reward-messages',\n 'mage/storage',\n 'mage/translate',\n 'Magento_Checkout/js/action/get-payment-information',\n 'Magento_Checkout/js/model/totals',\n 'Magento_Checkout/js/model/full-screen-loader'\n ], function (ko, $, quote, urlManager, errorProcessor, messageContainer,\n storage, $t, getPaymentInformationAction, totals, fullScreenLoader\n ) {\n 'use strict';\n return function (points, isApplied, pointsLeftObs, rateForCurrency, noticeMessage) {\n var quoteId = quote.getQuoteId(),\n url = urlManager.getRewardsUrl(points(), quoteId);\n\n messageContainer.clear();\n fullScreenLoader.startLoader();\n\n return storage.put(\n url,\n {},\n false\n ).done(function (response) {\n var deferred,\n pointsUsed = 0;\n\n if (response) {\n pointsUsed = response[1];\n noticeMessage($t(response[0]));\n $('[data-amrewards-js=\"notice-message\"]').show();\n setTimeout(function () {\n $('[data-amrewards-js=\"notice-message\"]').hide('blind', {}, 500);\n }, 5000);\n\n deferred = $.Deferred();\n\n if (pointsUsed > 0) {\n isApplied(true);\n totals.isLoading(true);\n getPaymentInformationAction(deferred);\n\n $.when(deferred).done(function () {\n points((pointsUsed).toFixed(2));\n pointsLeftObs((pointsLeftObs() - points()).toFixed(2));\n $('#amreward_amount').val(points()).change();\n\n fullScreenLoader.stopLoader();\n totals.isLoading(false);\n });\n }\n\n fullScreenLoader.stopLoader();\n }\n }).fail(function (response) {\n fullScreenLoader.stopLoader();\n totals.isLoading(false);\n errorProcessor.process(response, messageContainer);\n });\n };\n }\n);","Amasty_Rewards/js/view/balance.js":"define([\n 'uiComponent',\n 'Magento_Customer/js/customer-data'\n], function (Component, customerData) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n visible: false,\n balance: 0,\n captionText: false\n },\n\n initObservable: function () {\n this._super().observe('visible balance captionText');\n\n return this;\n },\n\n initialize: function () {\n this._super();\n var rewardsData = customerData.get('rewards');\n\n if (rewardsData().balance) {\n this.balance(rewardsData().balance);\n }\n\n rewardsData.subscribe(function (rewardsData) {\n this.balance(rewardsData.balance);\n }.bind(this));\n\n this.visible(true);\n },\n });\n});\n","Amasty_Rewards/js/view/checkout/payment/rewards.js":"define([\n 'jquery',\n 'underscore',\n 'uiComponent',\n 'Magento_Checkout/js/model/quote',\n 'Amasty_Rewards/js/action/add-reward',\n 'Amasty_Rewards/js/action/cancel-reward',\n 'Amasty_Rewards/vendor/tooltipster/js/tooltipster.min',\n 'Magento_Ui/js/model/messageList',\n 'mage/translate'\n], function (\n $,\n _,\n Component,\n quote,\n setRewardPointAction,\n cancelRewardPointAction,\n tooltipster,\n messageList,\n $t\n) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Amasty_Rewards/checkout/payment/rewards',\n isApplied: false,\n pointsUsed: 0,\n pointsLeft: 0,\n noticeMessage: '',\n minimumPointsValue: 0,\n disableElem: false,\n isRewardsTooltipEnabled: false,\n rewardsTooltipContent: '',\n selectors: {\n tooltipElement: '[data-amrewards-js=\"tooltip\"]'\n }\n },\n\n initObservable: function () {\n this._super();\n this.observe(['pointsUsed', 'pointsLeft', 'isApplied', 'noticeMessage', 'disableElem']);\n\n return this;\n },\n\n /**\n * @return {exports}\n */\n initialize: function () {\n this._super();\n this.isApplied(false);\n\n if (this.pointsUsed() > 0) {\n this.isApplied(true);\n }\n\n if (_.isUndefined(Number.parseFloat)) {\n Number.parseFloat = parseFloat;\n }\n\n if (this.getMinimumPointsValue() > this.pointsLeft() + Number.parseFloat(this.pointsUsed())) {\n this.disableElem(true);\n }\n\n this.initTooltip();\n\n return this;\n },\n\n /**\n * @return {*|Boolean}\n */\n isDisplayed: function () {\n return this.customerId;\n },\n\n /**\n * Coupon code application procedure\n */\n apply: function () {\n if (this.validate()) {\n setRewardPointAction(this.pointsUsed, this.isApplied, this.pointsLeft, this.rateForCurrency, this.noticeMessage);\n }\n },\n\n /**\n * Cancel using coupon\n */\n cancel: function () {\n cancelRewardPointAction(this.isApplied);\n this.pointsLeft((Number.parseFloat(this.pointsLeft()) + Number.parseFloat(this.pointsUsed())).toFixed(2));\n },\n\n /**\n *\n * @return {*}\n */\n getRewardsCount: function () {\n return this.pointsLeft();\n },\n\n /**\n *\n * @return {*}\n */\n getPointsRate: function () {\n return this.pointsRate;\n },\n\n /**\n *\n * @return {*}\n */\n getCurrentCurrency: function () {\n return this.currentCurrencyCode;\n },\n\n /**\n *\n * @return {*}\n */\n getRateForCurrency: function () {\n return this.rateForCurrency;\n },\n\n /**\n * @return {*}\n */\n getMinimumPointsValue: function () {\n return Number.parseFloat(this.minimumPointsValue);\n },\n\n /**\n * @return {Boolean}\n */\n canApply: function () {\n return !(this.disableElem() || this.isApplied());\n },\n\n /**\n * Coupon form validation\n *\n * @returns {Boolean}\n */\n validate: function () {\n var form = '#discount-reward-form',\n valueValid = (this.pointsLeft() - this.pointsUsed() >= 0) && this.pointsUsed() > 0;\n\n if ($(form).validation() && $(form).validation('isValid') && valueValid) {\n return true;\n }\n\n messageList.addErrorMessage({\n message: $t('Points \"' + this.pointsUsed() +'\" not valid.')\n });\n\n return false;\n },\n\n initTooltip: function () {\n var tooltipTrigger = this.isTouchDevice() ? 'click' : 'hover';\n\n if (!this.isRewardsTooltipEnabled) {\n return;\n }\n\n $.async(this.selectors.tooltipElement, function () {\n $(this.selectors.tooltipElement).tooltipster({\n position: 'right',\n contentAsHtml: true,\n interactive: true,\n trigger: tooltipTrigger\n });\n }.bind(this));\n },\n\n isTouchDevice: function () {\n return ('ontouchstart' in window)\n || (navigator.maxTouchPoints > 0)\n || (navigator.msMaxTouchPoints > 0);\n }\n });\n});\n","Amasty_Rewards/js/view/checkout/payment/reward-messages.js":"define([\n 'Magento_Ui/js/view/messages',\n 'Amasty_Rewards/js/model/payment/reward-messages'\n], function (Component, messageContainer) {\n 'use strict';\n\n return Component.extend({\n /** @inheritdoc */\n initialize: function (config) {\n return this._super(config, messageContainer);\n }\n });\n});","Amasty_Rewards/js/model/resource-url-manager.js":"define([\n 'Magento_Customer/js/model/customer',\n 'Magento_Checkout/js/model/url-builder',\n 'mageUtils',\n 'mage/url',\n 'mage/translate'\n ], function (customer, urlBuilder, utils, url, $t) {\n 'use strict';\n\n return {\n\n /**\n * @param {String} points\n * @return {*}\n */\n getRewardsUrl: function (points) {\n var params = {},\n url = {\n 'customer': '/carts/mine/points/' + encodeURIComponent(points)\n };\n\n return this.getUrl(url, params);\n },\n\n /**\n * @return {String}\n */\n getCheckoutMethod: function () {\n return 'customer';\n },\n\n /**\n * Get url for service.\n *\n * @param {*} url\n * @param {*} urlParams\n * @return {String|*}\n */\n getUrl: function (url, urlParams) {\n var finalUrl;\n\n if (utils.isEmpty(url)) {\n return $t('Provided service call does not exist.');\n }\n\n if (!utils.isEmpty(url['default'])) {\n finalUrl = url['default'];\n } else {\n finalUrl = url[this.getCheckoutMethod()];\n }\n\n return urlBuilder.createUrl(finalUrl, urlParams);\n }\n };\n }\n);\n","Amasty_Rewards/js/model/totals/highlight.js":"define([\n 'uiComponent',\n 'Magento_Checkout/js/model/totals',\n 'mage/translate',\n], function (Component, totals, $t) {\n 'use strict';\n\n return Component.extend({\n defaults: {\n template: 'Amasty_Rewards/highlight',\n captionEndText: $t('for completing your purchase!'),\n captionStartText : $t('You can earn'),\n frontend_class: '',\n highlight: []\n },\n\n /**\n * @return {Object}\n */\n initObservable: function () {\n this._super().observe(['highlight']);\n totals.totals.subscribe(this.getHighlightData.bind(this));\n\n return this;\n },\n\n /**\n * @param totals {Object}\n * @return {void}\n */\n getHighlightData: function (totals) {\n let totalsAttributes = totals.extension_attributes;\n\n if (totalsAttributes && totalsAttributes.amasty_rewards_highlight) {\n this.highlight(totalsAttributes.amasty_rewards_highlight);\n } else {\n this.highlight({'visible': false});\n }\n },\n });\n});\n","Amasty_Rewards/js/model/payment/reward-messages.js":"define([\n 'Magento_Ui/js/model/messages'\n], function (Messages) {\n 'use strict';\n\n return new Messages();\n});","Amasty_Rewards/js/model/catalog/highlight-product.js":"define([\n 'jquery',\n 'uiComponent',\n 'mage/translate',\n 'mage/storage',\n], function ($, Component, $t, storage) {\n 'use strict';\n var xhr = null;\n\n return Component.extend({\n defaults: {\n template: 'Amasty_Rewards/highlight',\n captionEndText: $t('for buying this product!'),\n captionStartText : $t('You can earn'),\n productId : 0,\n refreshUrl: false,\n loader: false,\n formSelector: '#product_addtocart_form',\n frontend_class: '',\n highlight: {\n visible: false\n }\n },\n\n initObservable: function () {\n this._super().observe(['highlight', 'loader']);\n this.updateData();\n $(this.formSelector).change(this.updateData.bind(this));\n\n return this;\n },\n\n hide: function () {\n this.highlight({'visible':false});\n\n return this;\n },\n\n updateData: function () {\n if (xhr) {\n xhr.abort();\n }\n this.hide().loader(true);\n\n xhr = storage.post(this.refreshUrl,\n JSON.stringify({\n productId: this.productId,\n attributes: $(this.formSelector).serialize()\n }),\n false\n ).done(function (result) {\n if (result) {\n this.highlight(result);\n }\n }.bind(this)).always(function () {\n this.loader(false);\n xhr = null;\n }.bind(this));\n },\n });\n});\n","Amasty_Rewards/js/model/catalog/highlight-category.js":"define([\n 'jquery',\n 'uiComponent',\n 'mage/translate',\n 'mage/storage',\n], function ($, Component, $t, storage) {\n 'use strict';\n var xhr = {};\n\n return Component.extend({\n defaults: {\n template: 'Amasty_Rewards/highlight-category',\n captionEndText: '',\n captionStartText: $t('Earn'),\n productId: 0,\n refreshUrl: false,\n loader: false,\n formSelector: false,\n frontend_class: '',\n highlight: {\n visible: false\n }\n },\n\n initObservable: function () {\n this._super().observe(['highlight', 'loader']);\n\n if (this.refreshUrl) {\n this.updateData();\n $(this.formSelector).change(this.updateData.bind(this));\n }\n\n return this;\n },\n\n hide: function () {\n this.highlight({'visible': false});\n\n return this;\n },\n\n updateData: function () {\n if (xhr.hasOwnProperty(this.productId)) {\n xhr[this.productId].abort();\n }\n this.hide().loader(true);\n\n xhr[this.productId] = storage.post(this.refreshUrl,\n JSON.stringify({\n productId: this.productId,\n attributes: $(this.formSelector).serialize()\n }),\n false\n ).done(function (result) {\n if (result) {\n this.highlight(result);\n }\n }.bind(this)).always(function () {\n this.loader(false);\n delete xhr[this.productId];\n }.bind(this));\n },\n });\n});\n","Amasty_Rewards/js/model/catalog/guest-highlight-category.js":"define([\n 'jquery',\n 'uiComponent',\n 'mage/translate',\n 'mage/storage',\n], function ($, Component, $t, storage) {\n 'use strict';\n var xhr = {};\n\n return Component.extend({\n defaults: {\n template: 'Amasty_Rewards/guest-highlight',\n captionStartText: $t('You can earn'),\n captionAfterText: '',\n captionRegistrationText: $t('for registration!'),\n captionEndText: '',\n productId: 0,\n refreshUrl: false,\n loader: false,\n formSelector: false,\n frontend_class: '',\n highlight: {\n visible: false\n }\n },\n\n initObservable: function () {\n this._super().observe([ 'highlight', 'loader' ]);\n\n if (this.refreshUrl) {\n this.updateData();\n $(this.formSelector).change(this.updateData.bind(this));\n }\n\n return this;\n },\n\n hide: function () {\n this.highlight({ 'visible': false });\n\n return this;\n },\n\n updateData: function () {\n if (xhr.hasOwnProperty(this.productId)) {\n xhr[this.productId].abort();\n }\n this.hide().loader(true);\n\n xhr[this.productId] = storage.post(this.refreshUrl,\n JSON.stringify({\n page: 3,\n productId: this.productId,\n attributes: $(this.formSelector).serialize()\n }),\n false\n ).done(function (result) {\n if (result) {\n if (result.need_to_change_message === 1) {\n this.captionAfterText = $t('for making a purchase! Available for');\n this.captionRegistrationText = $t('registered');\n this.captionEndText = $t('customers only.');\n }\n this.highlight(result);\n }\n }.bind(this)).always(function () {\n this.loader(false);\n delete xhr[this.productId];\n }.bind(this));\n }\n });\n});\n","Amasty_Rewards/js/model/catalog/guest-highlight-product.js":"define([\n 'jquery',\n 'uiComponent',\n 'mage/translate',\n 'mage/storage',\n], function ($, Component, $t, storage) {\n 'use strict';\n var xhr = null;\n\n return Component.extend({\n defaults: {\n template: 'Amasty_Rewards/guest-highlight',\n captionStartText: $t('You can earn'),\n captionAfterText: '',\n captionRegistrationText: $t('for registration!'),\n captionEndText: '',\n productId: 0,\n refreshUrl: false,\n loader: false,\n formSelector: '#product_addtocart_form',\n frontend_class: '',\n highlight: {\n visible: false\n }\n },\n\n initObservable: function () {\n this._super().observe([ 'highlight', 'loader' ]);\n this.updateData();\n $(this.formSelector).change(this.updateData.bind(this));\n\n return this;\n },\n\n hide: function () {\n this.highlight({ 'visible':false });\n\n return this;\n },\n\n updateData: function () {\n if (xhr) {\n xhr.abort();\n }\n this.hide().loader(true);\n\n xhr = storage.post(this.refreshUrl,\n JSON.stringify({\n page: 0,\n productId: this.productId,\n attributes: $(this.formSelector).serialize()\n }),\n false\n ).done(function (result) {\n if (result) {\n if (result.need_to_change_message === 1) {\n this.captionAfterText = $t('for making a purchase! Available for');\n this.captionRegistrationText = $t('registered');\n this.captionEndText = $t('customers only.');\n }\n this.highlight(result);\n }\n }.bind(this)).always(function () {\n this.loader(false);\n xhr = null;\n }.bind(this));\n }\n });\n});\n","Amasty_Rewards/vendor/tooltipster/js/tooltipster.min.js":"!function(t,i){\"function\"==typeof define&&define.amd?define([\"jquery\"],function(t){return i(t)}):\"object\"==typeof exports?module.exports=i(require(\"jquery\")):i(jQuery)}(0,function(t){var i={animation:\"fade\",animationDuration:350,content:null,contentAsHTML:!1,contentCloning:!1,debug:!0,delay:300,delayTouch:[300,500],functionInit:null,functionBefore:null,functionReady:null,functionAfter:null,functionFormat:null,IEmin:6,interactive:!1,multiple:!1,parent:null,plugins:[\"sideTip\"],repositionOnScroll:!1,restoration:\"none\",selfDestruction:!0,theme:[],timer:0,trackerInterval:500,trackOrigin:!1,trackTooltip:!1,trigger:\"hover\",triggerClose:{click:!1,mouseleave:!1,originClick:!1,scroll:!1,tap:!1,touchleave:!1},triggerOpen:{click:!1,mouseenter:!1,tap:!1,touchstart:!1},updateAnimation:\"rotate\",zIndex:9999999,styles:{backgroundColor:\"\",textColor:\"\"}},o=\"undefined\"!=typeof window?window:null,e={hasTouchCapability:!(!o||!(\"ontouchstart\"in o||o.DocumentTouch&&o.document instanceof o.DocumentTouch||o.navigator.maxTouchPoints)),hasTransitions:function(){if(!o)return!1;var t=(o.document.body||o.document.documentElement).style,i=\"transition\",e=[\"Moz\",\"Webkit\",\"Khtml\",\"O\",\"ms\"];if(\"string\"==typeof t[i])return!0;i=i.charAt(0).toUpperCase()+i.substr(1);for(var n=0;n<e.length;n++)if(\"string\"==typeof t[e[n]+i])return!0;return!1}(),IE:!1,semVer:\"4.2.8\",window:o},n=function(){this.__$emitterPrivate=t({}),this.__$emitterPublic=t({}),this.__instancesLatestArr=[],this.__plugins={},this._env=e};function s(t){this.$container,this.constraints=null,this.__$tooltip,this.__init(t)}function r(i,o){var e=!0;return t.each(i,function(t,n){if(void 0===o[t]||i[t]!==o[t])return e=!1,!1}),e}function _(i){var o=i.attr(\"id\"),n=o?e.window.document.getElementById(o):null;return n?n===i[0]:t.contains(e.window.document.body,i[0])}n.prototype={__bridge:function(o,e,n){if(!e[n]){var s=function(){};s.prototype=o;var r=new s;r.__init&&r.__init(e),t.each(o,function(t,o){0!=t.indexOf(\"__\")&&(e[t]?i.debug&&console.log(\"The \"+t+\" method of the \"+n+\" plugin conflicts with another plugin or native methods\"):(e[t]=function(){return r[t].apply(r,Array.prototype.slice.apply(arguments))},e[t].bridged=r))}),e[n]=r}return this},__setWindow:function(t){return e.window=t,this},_getRuler:function(t){return new s(t)},_off:function(){return this.__$emitterPrivate.off.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_on:function(){return this.__$emitterPrivate.on.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_one:function(){return this.__$emitterPrivate.one.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_plugin:function(i){if(\"string\"==typeof i){var o=i,e=null;return o.indexOf(\".\")>0?e=this.__plugins[o]:t.each(this.__plugins,function(t,i){if(i.name.substring(i.name.length-o.length-1)==\".\"+o)return e=i,!1}),e}if(i.name.indexOf(\".\")<0)throw new Error(\"Plugins must be namespaced\");return this.__plugins[i.name]=i,i.core&&this.__bridge(i.core,this,i.name),this},_trigger:function(){var t=Array.prototype.slice.apply(arguments);return\"string\"==typeof t[0]&&(t[0]={type:t[0]}),this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate,t),this.__$emitterPublic.trigger.apply(this.__$emitterPublic,t),this},instances:function(i){var o=[];return t(i||\".tooltipstered\").each(function(){var i=t(this),e=i.data(\"tooltipster-ns\");e&&t.each(e,function(t,e){o.push(i.data(e))})}),o},instancesLatest:function(){return this.__instancesLatestArr},off:function(){return this.__$emitterPublic.off.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},on:function(){return this.__$emitterPublic.on.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},one:function(){return this.__$emitterPublic.one.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},origins:function(i){return t((i?i+\" \":\"\")+\".tooltipstered\").toArray()},setDefaults:function(o){return t.extend(i,o),this},triggerHandler:function(){return this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this}},t.tooltipster=new n,t.Tooltipster=function(i,o){this.__callbacks={close:[],open:[]},this.__closingTime,this.__Content,this.__contentBcr,this.__destroyed=!1,this.__$emitterPrivate=t({}),this.__$emitterPublic=t({}),this.__enabled=!0,this.__garbageCollector,this.__Geometry,this.__lastPosition,this.__namespace=\"tooltipster-\"+Math.round(1e6*Math.random()),this.__options,this.__$originParents,this.__pointerIsOverOrigin=!1,this.__previousThemes=[],this.__state=\"closed\",this.__timeouts={close:[],open:null},this.__touchEvents=[],this.__tracker=null,this._$origin,this._$tooltip,this.__init(i,o)},t.Tooltipster.prototype={__init:function(o,n){var s=this;if(s._$origin=t(o),s.__options=t.extend(!0,{},i,n),s.__optionsFormat(),!e.IE||e.IE>=s.__options.IEmin){var r=null;if(void 0===s._$origin.data(\"tooltipster-initialTitle\")&&(void 0===(r=s._$origin.attr(\"title\"))&&(r=null),s._$origin.data(\"tooltipster-initialTitle\",r)),null!==s.__options.content)s.__contentSet(s.__options.content);else{var _,a=s._$origin.attr(\"data-tooltip-content\");a&&(_=t(a)),_&&_[0]?s.__contentSet(_.first()):s.__contentSet(r)}s._$origin.removeAttr(\"title\").addClass(\"tooltipstered\"),s.__prepareOrigin(),s.__prepareGC(),t.each(s.__options.plugins,function(t,i){s._plug(i)}),e.hasTouchCapability&&t(e.window.document.body).on(\"touchmove.\"+s.__namespace+\"-triggerOpen\",function(t){s._touchRecordEvent(t)}),s._on(\"created\",function(){s.__prepareTooltip()})._on(\"repositioned\",function(t){s.__lastPosition=t.position})}else s.__options.disabled=!0},__contentInsert:function(){var t=this._$tooltip.find(\".tooltipster-content\"),i=this.__Content;return this._trigger({type:\"format\",content:this.__Content,format:function(t){i=t}}),this.__options.functionFormat&&(i=this.__options.functionFormat.call(this,this,{origin:this._$origin[0]},this.__Content)),\"string\"!=typeof i||this.__options.contentAsHTML?t.empty().append(i):t.text(i),this},__contentSet:function(i){return i instanceof t&&this.__options.contentCloning&&(i=i.clone(!0)),this.__Content=i,this._trigger({type:\"updated\",content:i}),this},__destroyError:function(){throw new Error(\"This tooltip has been destroyed and cannot execute your method call.\")},__geometry:function(){var i=this._$origin,o=this._$origin.is(\"area\");if(o){var n=this._$origin.parent().attr(\"name\");i=t('img[usemap=\"#'+n+'\"]')}var s=i[0].getBoundingClientRect(),r=t(e.window.document),_=t(e.window),a=i,l={available:{document:null,window:null},document:{size:{height:r.height(),width:r.width()}},window:{scroll:{left:e.window.scrollX||e.window.document.documentElement.scrollLeft,top:e.window.scrollY||e.window.document.documentElement.scrollTop},size:{height:_.height(),width:_.width()}},origin:{fixedLineage:!1,offset:{},size:{height:s.bottom-s.top,width:s.right-s.left},usemapImage:o?i[0]:null,windowOffset:{bottom:s.bottom,left:s.left,right:s.right,top:s.top}}};if(o){var p=this._$origin.attr(\"shape\"),c=this._$origin.attr(\"coords\");if(c&&(c=c.split(\",\"),t.map(c,function(t,i){c[i]=parseInt(t)})),\"default\"!=p)switch(p){case\"circle\":var h=c[0],d=c[1],u=c[2],g=d-u,f=h-u;l.origin.size.height=2*u,l.origin.size.width=l.origin.size.height,l.origin.windowOffset.left+=f,l.origin.windowOffset.top+=g;break;case\"rect\":var m=c[0],w=c[1],v=c[2],y=c[3];l.origin.size.height=y-w,l.origin.size.width=v-m,l.origin.windowOffset.left+=m,l.origin.windowOffset.top+=w;break;case\"poly\":for(var b=0,$=0,C=0,O=0,T=\"even\",z=0;z<c.length;z++){var E=c[z];\"even\"==T?(E>C&&(C=E,0===z&&(b=C)),E<b&&(b=E),T=\"odd\"):(E>O&&(O=E,1==z&&($=O)),E<$&&($=E),T=\"even\")}l.origin.size.height=O-$,l.origin.size.width=C-b,l.origin.windowOffset.left+=b,l.origin.windowOffset.top+=$}}for(this._trigger({type:\"geometry\",edit:function(t){l.origin.size.height=t.height,l.origin.windowOffset.left=t.left,l.origin.windowOffset.top=t.top,l.origin.size.width=t.width},geometry:{height:l.origin.size.height,left:l.origin.windowOffset.left,top:l.origin.windowOffset.top,width:l.origin.size.width}}),l.origin.windowOffset.right=l.origin.windowOffset.left+l.origin.size.width,l.origin.windowOffset.bottom=l.origin.windowOffset.top+l.origin.size.height,l.origin.offset.left=l.origin.windowOffset.left+l.window.scroll.left,l.origin.offset.top=l.origin.windowOffset.top+l.window.scroll.top,l.origin.offset.bottom=l.origin.offset.top+l.origin.size.height,l.origin.offset.right=l.origin.offset.left+l.origin.size.width,l.available.document={bottom:{height:l.document.size.height-l.origin.offset.bottom,width:l.document.size.width},left:{height:l.document.size.height,width:l.origin.offset.left},right:{height:l.document.size.height,width:l.document.size.width-l.origin.offset.right},top:{height:l.origin.offset.top,width:l.document.size.width}},l.available.window={bottom:{height:Math.max(l.window.size.height-Math.max(l.origin.windowOffset.bottom,0),0),width:l.window.size.width},left:{height:l.window.size.height,width:Math.max(l.origin.windowOffset.left,0)},right:{height:l.window.size.height,width:Math.max(l.window.size.width-Math.max(l.origin.windowOffset.right,0),0)},top:{height:Math.max(l.origin.windowOffset.top,0),width:l.window.size.width}};\"html\"!=a[0].tagName.toLowerCase();){if(\"fixed\"==a.css(\"position\")){l.origin.fixedLineage=!0;break}a=a.parent()}return l},__optionsFormat:function(){return\"number\"==typeof this.__options.animationDuration&&(this.__options.animationDuration=[this.__options.animationDuration,this.__options.animationDuration]),\"number\"==typeof this.__options.delay&&(this.__options.delay=[this.__options.delay,this.__options.delay]),\"number\"==typeof this.__options.delayTouch&&(this.__options.delayTouch=[this.__options.delayTouch,this.__options.delayTouch]),\"string\"==typeof this.__options.theme&&(this.__options.theme=[this.__options.theme]),null===this.__options.parent?this.__options.parent=t(e.window.document.body):\"string\"==typeof this.__options.parent&&(this.__options.parent=t(this.__options.parent)),\"hover\"==this.__options.trigger?(this.__options.triggerOpen={mouseenter:!0,touchstart:!0},this.__options.triggerClose={mouseleave:!0,originClick:!0,touchleave:!0}):\"click\"==this.__options.trigger&&(this.__options.triggerOpen={click:!0,tap:!0},this.__options.triggerClose={click:!0,tap:!0}),this._trigger(\"options\"),this},__prepareGC:function(){var i=this;return i.__options.selfDestruction?i.__garbageCollector=setInterval(function(){var o=(new Date).getTime();i.__touchEvents=t.grep(i.__touchEvents,function(t,i){return o-t.time>6e4}),_(i._$origin)||i.close(function(){i.destroy()})},2e4):clearInterval(i.__garbageCollector),i},__prepareOrigin:function(){var t=this;if(t._$origin.off(\".\"+t.__namespace+\"-triggerOpen\"),e.hasTouchCapability&&t._$origin.on(\"touchstart.\"+t.__namespace+\"-triggerOpen touchend.\"+t.__namespace+\"-triggerOpen touchcancel.\"+t.__namespace+\"-triggerOpen\",function(i){t._touchRecordEvent(i)}),t.__options.triggerOpen.click||t.__options.triggerOpen.tap&&e.hasTouchCapability){var i=\"\";t.__options.triggerOpen.click&&(i+=\"click.\"+t.__namespace+\"-triggerOpen \"),t.__options.triggerOpen.tap&&e.hasTouchCapability&&(i+=\"touchend.\"+t.__namespace+\"-triggerOpen\"),t._$origin.on(i,function(i){t._touchIsMeaningfulEvent(i)&&t._open(i)})}if(t.__options.triggerOpen.mouseenter||t.__options.triggerOpen.touchstart&&e.hasTouchCapability){i=\"\";t.__options.triggerOpen.mouseenter&&(i+=\"mouseenter.\"+t.__namespace+\"-triggerOpen \"),t.__options.triggerOpen.touchstart&&e.hasTouchCapability&&(i+=\"touchstart.\"+t.__namespace+\"-triggerOpen\"),t._$origin.on(i,function(i){!t._touchIsTouchEvent(i)&&t._touchIsEmulatedEvent(i)||(t.__pointerIsOverOrigin=!0,t._openShortly(i))})}if(t.__options.triggerClose.mouseleave||t.__options.triggerClose.touchleave&&e.hasTouchCapability){i=\"\";t.__options.triggerClose.mouseleave&&(i+=\"mouseleave.\"+t.__namespace+\"-triggerOpen \"),t.__options.triggerClose.touchleave&&e.hasTouchCapability&&(i+=\"touchend.\"+t.__namespace+\"-triggerOpen touchcancel.\"+t.__namespace+\"-triggerOpen\"),t._$origin.on(i,function(i){t._touchIsMeaningfulEvent(i)&&(t.__pointerIsOverOrigin=!1)})}return t},__prepareTooltip:function(){var i=this,o=i.__options.interactive?\"auto\":\"\";return i._$tooltip.attr(\"id\",i.__namespace).css({\"pointer-events\":o,zIndex:i.__options.zIndex}),t.each(i.__previousThemes,function(t,o){i._$tooltip.removeClass(o)}),t.each(i.__options.theme,function(t,o){i._$tooltip.addClass(o)}),i.__previousThemes=t.merge([],i.__options.theme),i},__scrollHandler:function(i){if(this.__options.triggerClose.scroll)this._close(i);else if(_(this._$origin)&&_(this._$tooltip)){var o=null;if(i.target===e.window.document)this.__Geometry.origin.fixedLineage||this.__options.repositionOnScroll&&this.reposition(i);else{o=this.__geometry();var n=!1;if(\"fixed\"!=this._$origin.css(\"position\")&&this.__$originParents.each(function(i,e){var s=t(e),r=s.css(\"overflow-x\"),_=s.css(\"overflow-y\");if(\"visible\"!=r||\"visible\"!=_){var a=e.getBoundingClientRect();if(\"visible\"!=r&&(o.origin.windowOffset.left<a.left||o.origin.windowOffset.right>a.right))return n=!0,!1;if(\"visible\"!=_&&(o.origin.windowOffset.top<a.top||o.origin.windowOffset.bottom>a.bottom))return n=!0,!1}if(\"fixed\"==s.css(\"position\"))return!1}),n)this._$tooltip.css(\"visibility\",\"hidden\");else if(this._$tooltip.css(\"visibility\",\"visible\"),this.__options.repositionOnScroll)this.reposition(i);else{var s=o.origin.offset.left-this.__Geometry.origin.offset.left,r=o.origin.offset.top-this.__Geometry.origin.offset.top;this._$tooltip.css({left:this.__lastPosition.coord.left+s,top:this.__lastPosition.coord.top+r})}}this._trigger({type:\"scroll\",event:i,geo:o})}return this},__stateSet:function(t){return this.__state=t,this._trigger({type:\"state\",state:t}),this},__timeoutsClear:function(){return clearTimeout(this.__timeouts.open),this.__timeouts.open=null,t.each(this.__timeouts.close,function(t,i){clearTimeout(i)}),this.__timeouts.close=[],this},__trackerStart:function(){var t=this,i=t._$tooltip.find(\".tooltipster-content\");return t.__options.trackTooltip&&(t.__contentBcr=i[0].getBoundingClientRect()),t.__tracker=setInterval(function(){if(_(t._$origin)&&_(t._$tooltip)){if(t.__options.trackOrigin){var o=t.__geometry(),e=!1;r(o.origin.size,t.__Geometry.origin.size)&&(t.__Geometry.origin.fixedLineage?r(o.origin.windowOffset,t.__Geometry.origin.windowOffset)&&(e=!0):r(o.origin.offset,t.__Geometry.origin.offset)&&(e=!0)),e||(t.__options.triggerClose.mouseleave?t._close():t.reposition())}if(t.__options.trackTooltip){var n=i[0].getBoundingClientRect();n.height===t.__contentBcr.height&&n.width===t.__contentBcr.width||(t.reposition(),t.__contentBcr=n)}}else t._close()},t.__options.trackerInterval),t},_close:function(i,o,n){var s=this,r=!0;if(s._trigger({type:\"close\",event:i,stop:function(){r=!1}}),r||n){o&&s.__callbacks.close.push(o),s.__callbacks.open=[],s.__timeoutsClear();var _=function(){t.each(s.__callbacks.close,function(t,o){o.call(s,s,{event:i,origin:s._$origin[0]})}),s.__callbacks.close=[]};if(\"closed\"!=s.__state){var a=!0,l=(new Date).getTime()+s.__options.animationDuration[1];if(\"disappearing\"==s.__state&&l>s.__closingTime&&s.__options.animationDuration[1]>0&&(a=!1),a){s.__closingTime=l,\"disappearing\"!=s.__state&&s.__stateSet(\"disappearing\");var p=function(){clearInterval(s.__tracker),s._trigger({type:\"closing\",event:i}),s._$tooltip.off(\".\"+s.__namespace+\"-triggerClose\").removeClass(\"tooltipster-dying\"),t(e.window).off(\".\"+s.__namespace+\"-triggerClose\"),s.__$originParents.each(function(i,o){t(o).off(\"scroll.\"+s.__namespace+\"-triggerClose\")}),s.__$originParents=null,t(e.window.document.body).off(\".\"+s.__namespace+\"-triggerClose\"),s._$origin.off(\".\"+s.__namespace+\"-triggerClose\"),s._off(\"dismissable\"),s.__stateSet(\"closed\"),s._trigger({type:\"after\",event:i}),s.__options.functionAfter&&s.__options.functionAfter.call(s,s,{event:i,origin:s._$origin[0]}),_()};e.hasTransitions?(s._$tooltip.css({\"-moz-animation-duration\":s.__options.animationDuration[1]+\"ms\",\"-ms-animation-duration\":s.__options.animationDuration[1]+\"ms\",\"-o-animation-duration\":s.__options.animationDuration[1]+\"ms\",\"-webkit-animation-duration\":s.__options.animationDuration[1]+\"ms\",\"animation-duration\":s.__options.animationDuration[1]+\"ms\",\"transition-duration\":s.__options.animationDuration[1]+\"ms\"}),s._$tooltip.clearQueue().removeClass(\"tooltipster-show\").addClass(\"tooltipster-dying\"),s.__options.animationDuration[1]>0&&s._$tooltip.delay(s.__options.animationDuration[1]),s._$tooltip.queue(p)):s._$tooltip.stop().fadeOut(s.__options.animationDuration[1],p)}}else _()}return s},_off:function(){return this.__$emitterPrivate.off.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_on:function(){return this.__$emitterPrivate.on.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_one:function(){return this.__$emitterPrivate.one.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_open:function(i,o){var n=this;if(!n.__destroying&&_(n._$origin)&&n.__enabled){var s=!0;if(\"closed\"==n.__state&&(n._trigger({type:\"before\",event:i,stop:function(){s=!1}}),s&&n.__options.functionBefore&&(s=n.__options.functionBefore.call(n,n,{event:i,origin:n._$origin[0]}))),!1!==s&&null!==n.__Content){o&&n.__callbacks.open.push(o),n.__callbacks.close=[],n.__timeoutsClear();var r,a=function(){\"stable\"!=n.__state&&n.__stateSet(\"stable\"),t.each(n.__callbacks.open,function(t,i){i.call(n,n,{origin:n._$origin[0],tooltip:n._$tooltip[0]})}),n.__callbacks.open=[]};if(\"closed\"!==n.__state)r=0,\"disappearing\"===n.__state?(n.__stateSet(\"appearing\"),e.hasTransitions?(n._$tooltip.clearQueue().removeClass(\"tooltipster-dying\").addClass(\"tooltipster-show\"),n.__options.animationDuration[0]>0&&n._$tooltip.delay(n.__options.animationDuration[0]),n._$tooltip.queue(a)):n._$tooltip.stop().fadeIn(a)):\"stable\"==n.__state&&a();else{if(n.__stateSet(\"appearing\"),r=n.__options.animationDuration[0],n.__contentInsert(),n.reposition(i,!0),e.hasTransitions?(n._$tooltip.addClass(\"tooltipster-\"+n.__options.animation).addClass(\"tooltipster-initial\").css({\"-moz-animation-duration\":n.__options.animationDuration[0]+\"ms\",\"-ms-animation-duration\":n.__options.animationDuration[0]+\"ms\",\"-o-animation-duration\":n.__options.animationDuration[0]+\"ms\",\"-webkit-animation-duration\":n.__options.animationDuration[0]+\"ms\",\"animation-duration\":n.__options.animationDuration[0]+\"ms\",\"transition-duration\":n.__options.animationDuration[0]+\"ms\"}),setTimeout(function(){\"closed\"!=n.__state&&(n._$tooltip.addClass(\"tooltipster-show\").removeClass(\"tooltipster-initial\"),n.__options.animationDuration[0]>0&&n._$tooltip.delay(n.__options.animationDuration[0]),n._$tooltip.queue(a))},0)):n._$tooltip.css(\"display\",\"none\").fadeIn(n.__options.animationDuration[0],a),n.__trackerStart(),t(e.window).on(\"resize.\"+n.__namespace+\"-triggerClose\",function(i){var o=t(document.activeElement);(o.is(\"input\")||o.is(\"textarea\"))&&t.contains(n._$tooltip[0],o[0])||n.reposition(i)}).on(\"scroll.\"+n.__namespace+\"-triggerClose\",function(t){n.__scrollHandler(t)}),n.__$originParents=n._$origin.parents(),n.__$originParents.each(function(i,o){t(o).on(\"scroll.\"+n.__namespace+\"-triggerClose\",function(t){n.__scrollHandler(t)})}),n.__options.triggerClose.mouseleave||n.__options.triggerClose.touchleave&&e.hasTouchCapability){n._on(\"dismissable\",function(t){t.dismissable?t.delay?(h=setTimeout(function(){n._close(t.event)},t.delay),n.__timeouts.close.push(h)):n._close(t):clearTimeout(h)});var l=n._$origin,p=\"\",c=\"\",h=null;n.__options.interactive&&(l=l.add(n._$tooltip)),n.__options.triggerClose.mouseleave&&(p+=\"mouseenter.\"+n.__namespace+\"-triggerClose \",c+=\"mouseleave.\"+n.__namespace+\"-triggerClose \"),n.__options.triggerClose.touchleave&&e.hasTouchCapability&&(p+=\"touchstart.\"+n.__namespace+\"-triggerClose\",c+=\"touchend.\"+n.__namespace+\"-triggerClose touchcancel.\"+n.__namespace+\"-triggerClose\"),l.on(c,function(t){if(n._touchIsTouchEvent(t)||!n._touchIsEmulatedEvent(t)){var i=\"mouseleave\"==t.type?n.__options.delay:n.__options.delayTouch;n._trigger({delay:i[1],dismissable:!0,event:t,type:\"dismissable\"})}}).on(p,function(t){!n._touchIsTouchEvent(t)&&n._touchIsEmulatedEvent(t)||n._trigger({dismissable:!1,event:t,type:\"dismissable\"})})}n.__options.triggerClose.originClick&&n._$origin.on(\"click.\"+n.__namespace+\"-triggerClose\",function(t){n._touchIsTouchEvent(t)||n._touchIsEmulatedEvent(t)||n._close(t)}),(n.__options.triggerClose.click||n.__options.triggerClose.tap&&e.hasTouchCapability)&&setTimeout(function(){if(\"closed\"!=n.__state){var i=\"\",o=t(e.window.document.body);n.__options.triggerClose.click&&(i+=\"click.\"+n.__namespace+\"-triggerClose \"),n.__options.triggerClose.tap&&e.hasTouchCapability&&(i+=\"touchend.\"+n.__namespace+\"-triggerClose\"),o.on(i,function(i){n._touchIsMeaningfulEvent(i)&&(n._touchRecordEvent(i),n.__options.interactive&&t.contains(n._$tooltip[0],i.target)||n._close(i))}),n.__options.triggerClose.tap&&e.hasTouchCapability&&o.on(\"touchstart.\"+n.__namespace+\"-triggerClose\",function(t){n._touchRecordEvent(t)})}},0),n._trigger(\"ready\"),n.__options.functionReady&&n.__options.functionReady.call(n,n,{origin:n._$origin[0],tooltip:n._$tooltip[0]})}if(n.__options.timer>0){h=setTimeout(function(){n._close()},n.__options.timer+r);n.__timeouts.close.push(h)}}}return n},_openShortly:function(t){var i=this,o=!0;if(\"stable\"!=i.__state&&\"appearing\"!=i.__state&&!i.__timeouts.open&&(i._trigger({type:\"start\",event:t,stop:function(){o=!1}}),o)){var e=0==t.type.indexOf(\"touch\")?i.__options.delayTouch:i.__options.delay;e[0]?i.__timeouts.open=setTimeout(function(){i.__timeouts.open=null,i.__pointerIsOverOrigin&&i._touchIsMeaningfulEvent(t)?(i._trigger(\"startend\"),i._open(t)):i._trigger(\"startcancel\")},e[0]):(i._trigger(\"startend\"),i._open(t))}return i},_optionsExtract:function(i,o){var e=this,n=t.extend(!0,{},o),s=e.__options[i];return s||(s={},t.each(o,function(t,i){var o=e.__options[t];void 0!==o&&(s[t]=o)})),t.each(n,function(i,o){void 0!==s[i]&&(\"object\"!=typeof o||o instanceof Array||null==o||\"object\"!=typeof s[i]||s[i]instanceof Array||null==s[i]?n[i]=s[i]:t.extend(n[i],s[i]))}),n},_plug:function(i){var o=t.tooltipster._plugin(i);if(!o)throw new Error('The \"'+i+'\" plugin is not defined');return o.instance&&t.tooltipster.__bridge(o.instance,this,o.name),this},_touchIsEmulatedEvent:function(t){for(var i=!1,o=(new Date).getTime(),e=this.__touchEvents.length-1;e>=0;e--){var n=this.__touchEvents[e];if(!(o-n.time<500))break;n.target===t.target&&(i=!0)}return i},_touchIsMeaningfulEvent:function(t){return this._touchIsTouchEvent(t)&&!this._touchSwiped(t.target)||!this._touchIsTouchEvent(t)&&!this._touchIsEmulatedEvent(t)},_touchIsTouchEvent:function(t){return 0==t.type.indexOf(\"touch\")},_touchRecordEvent:function(t){return this._touchIsTouchEvent(t)&&(t.time=(new Date).getTime(),this.__touchEvents.push(t)),this},_touchSwiped:function(t){for(var i=!1,o=this.__touchEvents.length-1;o>=0;o--){var e=this.__touchEvents[o];if(\"touchmove\"==e.type){i=!0;break}if(\"touchstart\"==e.type&&t===e.target)break}return i},_trigger:function(){var i=Array.prototype.slice.apply(arguments);return\"string\"==typeof i[0]&&(i[0]={type:i[0]}),i[0].instance=this,i[0].origin=this._$origin?this._$origin[0]:null,i[0].tooltip=this._$tooltip?this._$tooltip[0]:null,this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate,i),t.tooltipster._trigger.apply(t.tooltipster,i),this.__$emitterPublic.trigger.apply(this.__$emitterPublic,i),this},_unplug:function(i){var o=this;if(o[i]){var e=t.tooltipster._plugin(i);e.instance&&t.each(e.instance,function(t,e){o[t]&&o[t].bridged===o[i]&&delete o[t]}),o[i].__destroy&&o[i].__destroy(),delete o[i]}return o},close:function(t){return this.__destroyed?this.__destroyError():this._close(null,t),this},content:function(t){var i=this;if(void 0===t)return i.__Content;if(i.__destroyed)i.__destroyError();else if(i.__contentSet(t),null!==i.__Content){if(\"closed\"!==i.__state&&(i.__contentInsert(),i.reposition(),i.__options.updateAnimation))if(e.hasTransitions){var o=i.__options.updateAnimation;i._$tooltip.addClass(\"tooltipster-update-\"+o),setTimeout(function(){\"closed\"!=i.__state&&i._$tooltip.removeClass(\"tooltipster-update-\"+o)},1e3)}else i._$tooltip.fadeTo(200,.5,function(){\"closed\"!=i.__state&&i._$tooltip.fadeTo(200,1)})}else i._close();return i},destroy:function(){var i=this;if(i.__destroyed)i.__destroyError();else{\"closed\"!=i.__state?i.option(\"animationDuration\",0)._close(null,null,!0):i.__timeoutsClear(),i._trigger(\"destroy\"),i.__destroyed=!0,i._$origin.removeData(i.__namespace).off(\".\"+i.__namespace+\"-triggerOpen\"),t(e.window.document.body).off(\".\"+i.__namespace+\"-triggerOpen\");var o=i._$origin.data(\"tooltipster-ns\");if(o)if(1===o.length){var n=null;\"previous\"==i.__options.restoration?n=i._$origin.data(\"tooltipster-initialTitle\"):\"current\"==i.__options.restoration&&(n=\"string\"==typeof i.__Content?i.__Content:t(\"<div></div>\").append(i.__Content).html()),n&&i._$origin.attr(\"title\",n),i._$origin.removeClass(\"tooltipstered\"),i._$origin.removeData(\"tooltipster-ns\").removeData(\"tooltipster-initialTitle\")}else o=t.grep(o,function(t,o){return t!==i.__namespace}),i._$origin.data(\"tooltipster-ns\",o);i._trigger(\"destroyed\"),i._off(),i.off(),i.__Content=null,i.__$emitterPrivate=null,i.__$emitterPublic=null,i.__options.parent=null,i._$origin=null,i._$tooltip=null,t.tooltipster.__instancesLatestArr=t.grep(t.tooltipster.__instancesLatestArr,function(t,o){return i!==t}),clearInterval(i.__garbageCollector)}return i},disable:function(){return this.__destroyed?(this.__destroyError(),this):(this._close(),this.__enabled=!1,this)},elementOrigin:function(){if(!this.__destroyed)return this._$origin[0];this.__destroyError()},elementTooltip:function(){return this._$tooltip?this._$tooltip[0]:null},enable:function(){return this.__enabled=!0,this},hide:function(t){return this.close(t)},instance:function(){return this},off:function(){return this.__destroyed||this.__$emitterPublic.off.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},on:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.on.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},one:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.one.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},open:function(t){return this.__destroyed?this.__destroyError():this._open(null,t),this},option:function(i,o){return void 0===o?this.__options[i]:(this.__destroyed?this.__destroyError():(this.__options[i]=o,this.__optionsFormat(),t.inArray(i,[\"trigger\",\"triggerClose\",\"triggerOpen\"])>=0&&this.__prepareOrigin(),\"selfDestruction\"===i&&this.__prepareGC()),this)},reposition:function(t,i){return this.__destroyed?this.__destroyError():\"closed\"!=this.__state&&_(this._$origin)&&(i||_(this._$tooltip))&&(i||this._$tooltip.detach(),this.__Geometry=this.__geometry(),this._trigger({type:\"reposition\",event:t,helper:{geo:this.__Geometry}})),this},show:function(t){return this.open(t)},status:function(){return{destroyed:this.__destroyed,enabled:this.__enabled,open:\"closed\"!==this.__state,state:this.__state}},triggerHandler:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this}},t.fn.tooltipster=function(){var o=Array.prototype.slice.apply(arguments),e=\"You are using a single HTML element as content for several tooltips. You probably want to set the contentCloning option to TRUE.\";if(0===this.length)return this;if(\"string\"==typeof o[0]){var n=\"#*$~&\";return this.each(function(){var i=t(this).data(\"tooltipster-ns\"),s=i?t(this).data(i[0]):null;if(!s)throw new Error(\"You called Tooltipster's \\\"\"+o[0]+'\" method on an uninitialized element');if(\"function\"!=typeof s[o[0]])throw new Error('Unknown method \"'+o[0]+'\"');this.length>1&&\"content\"==o[0]&&(o[1]instanceof t||\"object\"==typeof o[1]&&null!=o[1]&&o[1].tagName)&&!s.__options.contentCloning&&s.__options.debug&&console.log(e);var r=s[o[0]](o[1],o[2]);if(r!==s||\"instance\"===o[0])return n=r,!1}),\"#*$~&\"!==n?n:this}t.tooltipster.__instancesLatestArr=[];var s=o[0]&&void 0!==o[0].multiple,r=s&&o[0].multiple||!s&&i.multiple,_=o[0]&&void 0!==o[0].content,a=_&&o[0].content||!_&&i.content,l=o[0]&&void 0!==o[0].contentCloning,p=l&&o[0].contentCloning||!l&&i.contentCloning,c=o[0]&&void 0!==o[0].debug,h=c&&o[0].debug||!c&&i.debug;return this.length>1&&(a instanceof t||\"object\"==typeof a&&null!=a&&a.tagName)&&!p&&h&&console.log(e),this.each(function(){var i=!1,e=t(this),n=e.data(\"tooltipster-ns\"),s=null;n?r?i=!0:h&&(console.log(\"Tooltipster: one or more tooltips are already attached to the element below. Ignoring.\"),console.log(this)):i=!0,i&&(s=new t.Tooltipster(this,o[0]),n||(n=[]),n.push(s.__namespace),e.data(\"tooltipster-ns\",n),e.data(s.__namespace,s),s.__options.functionInit&&s.__options.functionInit.call(s,s,{origin:this}),s._trigger(\"init\")),t.tooltipster.__instancesLatestArr.push(s)}),this},s.prototype={__init:function(i){this.__$tooltip=i,this.__$tooltip.css({left:0,overflow:\"hidden\",position:\"absolute\",top:0}).find(\".tooltipster-content\").css(\"overflow\",\"auto\"),this.$container=t('<div class=\"tooltipster-ruler\"></div>').append(this.__$tooltip).appendTo(e.window.document.body)},__forceRedraw:function(){var t=this.__$tooltip.parent();this.__$tooltip.detach(),this.__$tooltip.appendTo(t)},constrain:function(t,i){return this.constraints={width:t,height:i},this.__$tooltip.css({display:\"block\",height:\"\",overflow:\"auto\",width:t}),this},destroy:function(){this.__$tooltip.detach().find(\".tooltipster-content\").css({display:\"\",overflow:\"\"}),this.$container.remove()},free:function(){return this.constraints=null,this.__$tooltip.css({display:\"\",height:\"\",overflow:\"visible\",width:\"\"}),this},measure:function(){this.__forceRedraw();var t=this.__$tooltip[0].getBoundingClientRect(),i={size:{height:t.height||t.bottom-t.top,width:t.width||t.right-t.left}};if(this.constraints){var o=this.__$tooltip.find(\".tooltipster-content\"),n=this.__$tooltip.outerHeight(),s=o[0].getBoundingClientRect(),r={height:n<=this.constraints.height,width:t.width<=this.constraints.width&&s.width>=o[0].scrollWidth-1};i.fits=r.height&&r.width}return e.IE&&e.IE<=11&&i.size.width!==e.window.document.documentElement.clientWidth&&(i.size.width=Math.ceil(i.size.width)+1),i}};var a=navigator.userAgent.toLowerCase();-1!=a.indexOf(\"msie\")?e.IE=parseInt(a.split(\"msie\")[1]):-1!==a.toLowerCase().indexOf(\"trident\")&&-1!==a.indexOf(\" rv:11\")?e.IE=11:-1!=a.toLowerCase().indexOf(\"edge/\")&&(e.IE=parseInt(a.toLowerCase().split(\"edge/\")[1]));return t.tooltipster._plugin({name:\"tooltipster.sideTip\",instance:{__defaults:function(){return{arrow:!0,distance:6,functionPosition:null,maxWidth:null,minIntersection:16,minWidth:0,position:null,side:\"top\",viewportAware:!0,defaultStyles:{backgroundColor:\"#fff\",textColor:\"#000\"}}},__init:function(t){var i=this;i.__instance=t,i.__namespace=\"tooltipster-sideTip-\"+Math.round(1e6*Math.random()),i.__previousState=\"closed\",i.__options,i.__optionsFormat(),i.__instance._on(\"state.\"+i.__namespace,function(t){\"closed\"==t.state?i.__close():\"appearing\"==t.state&&\"closed\"==i.__previousState&&i.__create(),i.__previousState=t.state}),i.__instance._on(\"options.\"+i.__namespace,function(){i.__optionsFormat()}),i.__instance._on(\"reposition.\"+i.__namespace,function(t){i.__reposition(t.event,t.helper)})},__close:function(){this.__instance.content()instanceof t&&this.__instance.content().detach(),this.__instance._$tooltip.remove(),this.__instance._$tooltip=null},__create:function(){var i=this.__instance.__options.styles,o=t('<div class=\"tooltipster-base tooltipster-sidetip\"><div class=\"tooltipster-box\"><div class=\"tooltipster-content\"></div></div><div class=\"tooltipster-arrow\"><div class=\"tooltipster-arrow-uncropped\"><div class=\"tooltipster-arrow-border\"></div><div class=\"tooltipster-arrow-background\"></div></div></div></div>');o.find(\".tooltipster-box\").css({color:i.textColor?i.textColor:this.__options.defaultStyles.textColor,backgroundColor:i.backgroundColor?i.backgroundColor:this.__options.defaultStyles.backgroundColor}),o.find(\".tooltipster-arrow-border\").css({backgroundColor:i.backgroundColor?i.backgroundColor:this.__options.defaultStyles.backgroundColor}),this.__options.arrow||o.find(\".tooltipster-box\").css(\"margin\",0).end().find(\".tooltipster-arrow\").hide(),this.__options.minWidth&&o.css(\"min-width\",this.__options.minWidth+\"px\"),this.__options.maxWidth&&o.css(\"max-width\",this.__options.maxWidth+\"px\"),this.__instance._$tooltip=o,this.__instance._trigger(\"created\")},__destroy:function(){this.__instance._off(\".\"+self.__namespace)},__optionsFormat:function(){if(this.__options=this.__instance._optionsExtract(\"tooltipster.sideTip\",this.__defaults()),this.__options.position&&(this.__options.side=this.__options.position),\"object\"!=typeof this.__options.distance&&(this.__options.distance=[this.__options.distance]),this.__options.distance.length<4&&(void 0===this.__options.distance[1]&&(this.__options.distance[1]=this.__options.distance[0]),void 0===this.__options.distance[2]&&(this.__options.distance[2]=this.__options.distance[0]),void 0===this.__options.distance[3]&&(this.__options.distance[3]=this.__options.distance[1])),this.__options.distance={top:this.__options.distance[0],right:this.__options.distance[1],bottom:this.__options.distance[2],left:this.__options.distance[3]},\"string\"==typeof this.__options.side){this.__options.side=[this.__options.side,{top:\"bottom\",right:\"left\",bottom:\"top\",left:\"right\"}[this.__options.side]],\"left\"==this.__options.side[0]||\"right\"==this.__options.side[0]?this.__options.side.push(\"top\",\"bottom\"):this.__options.side.push(\"right\",\"left\")}6===t.tooltipster._env.IE&&!0!==this.__options.arrow&&(this.__options.arrow=!1)},__reposition:function(i,o){var e,n=this,s=n.__targetFind(o),r=[];n.__instance._$tooltip.detach();var _=n.__instance._$tooltip.clone(),a=t.tooltipster._getRuler(_),l=!1,p=n.__instance.option(\"animation\");switch(p&&_.removeClass(\"tooltipster-\"+p),t.each([\"window\",\"document\"],function(e,p){var c=null;if(n.__instance._trigger({container:p,helper:o,satisfied:l,takeTest:function(t){c=t},results:r,type:\"positionTest\"}),1==c||0!=c&&0==l&&(\"window\"!=p||n.__options.viewportAware))for(e=0;e<n.__options.side.length;e++){var h={horizontal:0,vertical:0},d=n.__options.side[e];\"top\"==d||\"bottom\"==d?h.vertical=n.__options.distance[d]:h.horizontal=n.__options.distance[d],n.__sideChange(_,d),t.each([\"natural\",\"constrained\"],function(t,e){if(c=null,n.__instance._trigger({container:p,event:i,helper:o,mode:e,results:r,satisfied:l,side:d,takeTest:function(t){c=t},type:\"positionTest\"}),1==c||0!=c&&0==l){var _={container:p,distance:h,fits:null,mode:e,outerSize:null,side:d,size:null,target:s[d],whole:null},u=(\"natural\"==e?a.free():a.constrain(o.geo.available[p][d].width-h.horizontal,o.geo.available[p][d].height-h.vertical)).measure();if(_.size=u.size,_.outerSize={height:u.size.height+h.vertical,width:u.size.width+h.horizontal},\"natural\"==e?o.geo.available[p][d].width>=_.outerSize.width&&o.geo.available[p][d].height>=_.outerSize.height?_.fits=!0:_.fits=!1:_.fits=u.fits,\"window\"==p&&(_.fits?_.whole=\"top\"==d||\"bottom\"==d?o.geo.origin.windowOffset.right>=n.__options.minIntersection&&o.geo.window.size.width-o.geo.origin.windowOffset.left>=n.__options.minIntersection:o.geo.origin.windowOffset.bottom>=n.__options.minIntersection&&o.geo.window.size.height-o.geo.origin.windowOffset.top>=n.__options.minIntersection:_.whole=!1),r.push(_),_.whole)l=!0;else if(\"natural\"==_.mode&&(_.fits||_.size.width<=o.geo.available[p][d].width))return!1}})}}),n.__instance._trigger({edit:function(t){r=t},event:i,helper:o,results:r,type:\"positionTested\"}),r.sort(function(t,i){return t.whole&&!i.whole?-1:!t.whole&&i.whole?1:t.whole&&i.whole?(o=n.__options.side.indexOf(t.side))<(e=n.__options.side.indexOf(i.side))?-1:o>e?1:\"natural\"==t.mode?-1:1:t.fits&&!i.fits?-1:!t.fits&&i.fits?1:t.fits&&i.fits?(o=n.__options.side.indexOf(t.side))<(e=n.__options.side.indexOf(i.side))?-1:o>e?1:\"natural\"==t.mode?-1:1:\"document\"==t.container&&\"bottom\"==t.side&&\"natural\"==t.mode?-1:1;var o,e}),(e=r[0]).coord={},e.side){case\"left\":case\"right\":e.coord.top=Math.floor(e.target-e.size.height/2);break;case\"bottom\":case\"top\":e.coord.left=Math.floor(e.target-e.size.width/2)}switch(e.side){case\"left\":e.coord.left=o.geo.origin.windowOffset.left-e.outerSize.width;break;case\"right\":e.coord.left=o.geo.origin.windowOffset.right+e.distance.horizontal;break;case\"top\":e.coord.top=o.geo.origin.windowOffset.top-e.outerSize.height;break;case\"bottom\":e.coord.top=o.geo.origin.windowOffset.bottom+e.distance.vertical}\"window\"==e.container?\"top\"==e.side||\"bottom\"==e.side?e.coord.left<0?o.geo.origin.windowOffset.right-this.__options.minIntersection>=0?e.coord.left=0:e.coord.left=o.geo.origin.windowOffset.right-this.__options.minIntersection-1:e.coord.left>o.geo.window.size.width-e.size.width&&(o.geo.origin.windowOffset.left+this.__options.minIntersection<=o.geo.window.size.width?e.coord.left=o.geo.window.size.width-e.size.width:e.coord.left=o.geo.origin.windowOffset.left+this.__options.minIntersection+1-e.size.width):e.coord.top<0?o.geo.origin.windowOffset.bottom-this.__options.minIntersection>=0?e.coord.top=0:e.coord.top=o.geo.origin.windowOffset.bottom-this.__options.minIntersection-1:e.coord.top>o.geo.window.size.height-e.size.height&&(o.geo.origin.windowOffset.top+this.__options.minIntersection<=o.geo.window.size.height?e.coord.top=o.geo.window.size.height-e.size.height:e.coord.top=o.geo.origin.windowOffset.top+this.__options.minIntersection+1-e.size.height):(e.coord.left>o.geo.window.size.width-e.size.width&&(e.coord.left=o.geo.window.size.width-e.size.width),e.coord.left<0&&(e.coord.left=0)),n.__sideChange(_,e.side),o.tooltipClone=_[0],o.tooltipParent=n.__instance.option(\"parent\").parent[0],o.mode=e.mode,o.whole=e.whole,o.origin=n.__instance._$origin[0],o.tooltip=n.__instance._$tooltip[0],delete e.container,delete e.fits,delete e.mode,delete e.outerSize,delete e.whole,e.distance=e.distance.horizontal||e.distance.vertical;var c,h,d,u=t.extend(!0,{},e);if(n.__instance._trigger({edit:function(t){e=t},event:i,helper:o,position:u,type:\"position\"}),n.__options.functionPosition){var g=n.__options.functionPosition.call(n,n.__instance,o,u);g&&(e=g)}a.destroy(),\"top\"==e.side||\"bottom\"==e.side?(c={prop:\"left\",val:e.target-e.coord.left},h=e.size.width-this.__options.minIntersection):(c={prop:\"top\",val:e.target-e.coord.top},h=e.size.height-this.__options.minIntersection),c.val<this.__options.minIntersection?c.val=this.__options.minIntersection:c.val>h&&(c.val=h),d=o.geo.origin.fixedLineage?o.geo.origin.windowOffset:{left:o.geo.origin.windowOffset.left+o.geo.window.scroll.left,top:o.geo.origin.windowOffset.top+o.geo.window.scroll.top},e.coord={left:d.left+(e.coord.left-o.geo.origin.windowOffset.left),top:d.top+(e.coord.top-o.geo.origin.windowOffset.top)},n.__sideChange(n.__instance._$tooltip,e.side),o.geo.origin.fixedLineage?n.__instance._$tooltip.css(\"position\",\"fixed\"):n.__instance._$tooltip.css(\"position\",\"\"),n.__instance._$tooltip.css({left:e.coord.left,top:e.coord.top,height:e.size.height,width:e.size.width}).find(\".tooltipster-arrow\").css({left:\"\",top:\"\"}).css(c.prop,c.val),n.__instance._$tooltip.appendTo(n.__instance.option(\"parent\")),n.__instance._trigger({type:\"repositioned\",event:i,position:e})},__sideChange:function(t,i){t.removeClass(\"tooltipster-bottom\").removeClass(\"tooltipster-left\").removeClass(\"tooltipster-right\").removeClass(\"tooltipster-top\").addClass(\"tooltipster-\"+i)},__targetFind:function(t){var i={},o=this.__instance._$origin[0].getClientRects();o.length>1&&(1==this.__instance._$origin.css(\"opacity\")&&(this.__instance._$origin.css(\"opacity\",.99),o=this.__instance._$origin[0].getClientRects(),this.__instance._$origin.css(\"opacity\",1)));if(o.length<2)i.top=Math.floor(t.geo.origin.windowOffset.left+t.geo.origin.size.width/2),i.bottom=i.top,i.left=Math.floor(t.geo.origin.windowOffset.top+t.geo.origin.size.height/2),i.right=i.left;else{var e=o[0];i.top=Math.floor(e.left+(e.right-e.left)/2),e=o.length>2?o[Math.ceil(o.length/2)-1]:o[0],i.right=Math.floor(e.top+(e.bottom-e.top)/2),e=o[o.length-1],i.bottom=Math.floor(e.left+(e.right-e.left)/2),e=o.length>2?o[Math.ceil((o.length+1)/2)-1]:o[o.length-1],i.left=Math.floor(e.top+(e.bottom-e.top)/2)}return i}}}),t});\n","Magento_ConfigurableProduct/js/catalog-add-to-cart-mixin.js":"/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\ndefine([\n 'underscore',\n 'jquery',\n 'Magento_ConfigurableProduct/js/product/view/product-info-resolver'\n], function (_, $, productInfoResolver) {\n 'use strict';\n\n return function (widget) {\n\n $.widget('mage.catalogAddToCart', widget, {\n /**\n * @param {jQuery} form\n */\n ajaxSubmit: function (form) {\n var isConfigurable = !!_.find(form.serializeArray(), function (item) {\n return item.name.indexOf('super_attribute') !== -1;\n });\n\n if (isConfigurable) {\n this.options.productInfoResolver = productInfoResolver;\n }\n\n return this._super(form);\n }\n });\n\n return $.mage.catalogAddToCart;\n };\n});\n","Magento_ConfigurableProduct/js/configurable-customer-data.js":"require([\n 'jquery',\n 'Magento_ConfigurableProduct/js/options-updater'\n], function ($, Updater) {\n 'use strict';\n\n var selectors = {\n formSelector: '#product_addtocart_form'\n },\n configurableWidgetName = 'mageConfigurable',\n widgetInitEvent = 'configurable.initialized',\n\n /**\n * Sets all configurable attribute's selected values\n */\n updateConfigurableOptions = function () {\n var configurableWidget = $(selectors.formSelector).data(configurableWidgetName);\n\n if (!configurableWidget) {\n return;\n }\n configurableWidget.options.values = this.productOptions || {};\n configurableWidget._configureForValues();\n },\n updater = new Updater(widgetInitEvent, updateConfigurableOptions);\n\n updater.listen();\n});\n","Magento_ConfigurableProduct/js/options-updater.js":"define([\n 'jquery',\n 'underscore',\n 'Magento_Customer/js/customer-data',\n 'domReady!'\n], function ($, _, customerData) {\n 'use strict';\n\n var selectors = {\n formSelector: '#product_addtocart_form',\n productIdSelector: '#product_addtocart_form [name=\"product\"]',\n itemIdSelector: '#product_addtocart_form [name=\"item\"]'\n },\n cartData = customerData.get('cart'),\n productId = $(selectors.productIdSelector).val(),\n itemId = $(selectors.itemIdSelector).val(),\n\n /**\n * set productOptions according to cart data from customer-data\n *\n * @param {Object} data - cart data from customer-data\n * @returns {Boolean} - whether the new options differ from previous\n */\n setProductOptions = function (data) {\n var changedProductOptions;\n\n if (!(data && data.items && data.items.length && productId)) {\n return false;\n }\n changedProductOptions = _.find(data.items, function (item) {\n if (item['item_id'] === itemId) {\n return item['product_id'] === productId;\n }\n });\n changedProductOptions = changedProductOptions && changedProductOptions.options &&\n changedProductOptions.options.reduce(function (obj, val) {\n obj[val['option_id']] = val['option_value'];\n\n return obj;\n }, {});\n\n if (JSON.stringify(this.productOptions || {}) === JSON.stringify(changedProductOptions || {})) {\n return false;\n }\n\n this.productOptions = changedProductOptions;\n\n return true;\n },\n\n /**\n * Listens to update of cart data or options initialization and update selected option according to customer data\n *\n */\n listen = function () {\n cartData.subscribe(function (updateCartData) {\n if (this.setProductOptions(updateCartData)) {\n this.updateOptions();\n }\n }.bind(this));\n $(selectors.formSelector).on(this.eventName, function () {\n this.setProductOptions(cartData());\n this.updateOptions();\n }.bind(this));\n },\n\n /**\n * Updater constructor function\n *\n */\n Updater = function (eventName, updateOptionsCallback) {\n if (this instanceof Updater) {\n this.eventName = eventName;\n this.updateOptions = updateOptionsCallback;\n this.productOptions = {};\n }\n };\n\n Updater.prototype.setProductOptions = setProductOptions;\n Updater.prototype.listen = listen;\n\n return Updater;\n});\n"}
}});