!function(a){"object"==typeof module&&module.exports?module.exports=a():window.intlTelInput=a()}(function(a){"use strict";return function(){function b(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function c(a,b){for(var c=0;c<b.length;c++){var d=b[c];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(a,d.key,d)}}function d(a,b,d){return b&&c(a.prototype,b),d&&c(a,d),a}for(var e=[["Afghanistan (‫افغانستان‬‎)","af","93"],["Albania (Shqipëri)","al","355"],["Algeria (‫الجزائر‬‎)","dz","213"],["American Samoa","as","1",5,["684"]],["Andorra","ad","376"],["Angola","ao","244"],["Anguilla","ai","1",6,["264"]],["Antigua and Barbuda","ag","1",7,["268"]],["Argentina","ar","54"],["Armenia (Հայաստան)","am","374"],["Aruba","aw","297"],["Ascension Island","ac","247"],["Australia","au","61",0],["Austria (Österreich)","at","43"],["Azerbaijan (Azərbaycan)","az","994"],["Bahamas","bs","1",8,["242"]],["Bahrain (‫البحرين‬‎)","bh","973"],["Bangladesh (বাংলাদেশ)","bd","880"],["Barbados","bb","1",9,["246"]],["Belarus (Беларусь)","by","375"],["Belgium (België)","be","32"],["Belize","bz","501"],["Benin (Bénin)","bj","229"],["Bermuda","bm","1",10,["441"]],["Bhutan (འབྲུག)","bt","975"],["Bolivia","bo","591"],["Bosnia and Herzegovina (Босна и Херцеговина)","ba","387"],["Botswana","bw","267"],["Brazil (Brasil)","br","55"],["British Indian Ocean Territory","io","246"],["British Virgin Islands","vg","1",11,["284"]],["Brunei","bn","673"],["Bulgaria (България)","bg","359"],["Burkina Faso","bf","226"],["Burundi (Uburundi)","bi","257"],["Cambodia (កម្ពុជា)","kh","855"],["Cameroon (Cameroun)","cm","237"],["Canada","ca","1",1,["204","226","236","249","250","289","306","343","365","387","403","416","418","431","437","438","450","506","514","519","548","579","581","587","604","613","639","647","672","705","709","742","778","780","782","807","819","825","867","873","902","905"]],["Cape Verde (Kabu Verdi)","cv","238"],["Caribbean Netherlands","bq","599",1,["3","4","7"]],["Cayman Islands","ky","1",12,["345"]],["Central African Republic (République centrafricaine)","cf","236"],["Chad (Tchad)","td","235"],["Chile","cl","56"],["China (中国)","cn","86"],["Christmas Island","cx","61",2,["89164"]],["Cocos (Keeling) Islands","cc","61",1,["89162"]],["Colombia","co","57"],["Comoros (‫جزر القمر‬‎)","km","269"],["Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)","cd","243"],["Congo (Republic) (Congo-Brazzaville)","cg","242"],["Cook Islands","ck","682"],["Costa Rica","cr","506"],["Côte d’Ivoire","ci","225"],["Croatia (Hrvatska)","hr","385"],["Cuba","cu","53"],["Curaçao","cw","599",0],["Cyprus (Κύπρος)","cy","357"],["Czech Republic (Česká republika)","cz","420"],["Denmark (Danmark)","dk","45"],["Djibouti","dj","253"],["Dominica","dm","1",13,["767"]],["Dominican Republic (República Dominicana)","do","1",2,["809","829","849"]],["Ecuador","ec","593"],["Egypt (‫مصر‬‎)","eg","20"],["El Salvador","sv","503"],["Equatorial Guinea (Guinea Ecuatorial)","gq","240"],["Eritrea","er","291"],["Estonia (Eesti)","ee","372"],["Eswatini","sz","268"],["Ethiopia","et","251"],["Falkland Islands (Islas Malvinas)","fk","500"],["Faroe Islands (Føroyar)","fo","298"],["Fiji","fj","679"],["Finland (Suomi)","fi","358",0],["France","fr","33"],["French Guiana (Guyane française)","gf","594"],["French Polynesia (Polynésie française)","pf","689"],["Gabon","ga","241"],["Gambia","gm","220"],["Georgia (საქართველო)","ge","995"],["Germany (Deutschland)","de","49"],["Ghana (Gaana)","gh","233"],["Gibraltar","gi","350"],["Greece (Ελλάδα)","gr","30"],["Greenland (Kalaallit Nunaat)","gl","299"],["Grenada","gd","1",14,["473"]],["Guadeloupe","gp","590",0],["Guam","gu","1",15,["671"]],["Guatemala","gt","502"],["Guernsey","gg","44",1,["1481","7781","7839","7911"]],["Guinea (Guinée)","gn","224"],["Guinea-Bissau (Guiné Bissau)","gw","245"],["Guyana","gy","592"],["Haiti","ht","509"],["Honduras","hn","504"],["Hong Kong (香港)","hk","852"],["Hungary (Magyarország)","hu","36"],["Iceland (Ísland)","is","354"],["India (भारत)","in","91"],["Indonesia","id","62"],["Iran (‫ایران‬‎)","ir","98"],["Iraq (‫العراق‬‎)","iq","964"],["Ireland","ie","353"],["Isle of Man","im","44",2,["1624","74576","7524","7924","7624"]],["Israel (‫ישראל‬‎)","il","972"],["Italy (Italia)","it","39",0],["Jamaica","jm","1",4,["876","658"]],["Japan (日本)","jp","81"],["Jersey","je","44",3,["1534","7509","7700","7797","7829","7937"]],["Jordan (‫الأردن‬‎)","jo","962"],["Kazakhstan (Казахстан)","kz","7",1,["33","7"]],["Kenya","ke","254"],["Kiribati","ki","686"],["Kosovo","xk","383"],["Kuwait (‫الكويت‬‎)","kw","965"],["Kyrgyzstan (Кыргызстан)","kg","996"],["Laos (ລາວ)","la","856"],["Latvia (Latvija)","lv","371"],["Lebanon (‫لبنان‬‎)","lb","961"],["Lesotho","ls","266"],["Liberia","lr","231"],["Libya (‫ليبيا‬‎)","ly","218"],["Liechtenstein","li","423"],["Lithuania (Lietuva)","lt","370"],["Luxembourg","lu","352"],["Macau (澳門)","mo","853"],["North Macedonia (Македонија)","mk","389"],["Madagascar (Madagasikara)","mg","261"],["Malawi","mw","265"],["Malaysia","my","60"],["Maldives","mv","960"],["Mali","ml","223"],["Malta","mt","356"],["Marshall Islands","mh","692"],["Martinique","mq","596"],["Mauritania (‫موريتانيا‬‎)","mr","222"],["Mauritius (Moris)","mu","230"],["Mayotte","yt","262",1,["269","639"]],["Mexico (México)","mx","52"],["Micronesia","fm","691"],["Moldova (Republica Moldova)","md","373"],["Monaco","mc","377"],["Mongolia (Монгол)","mn","976"],["Montenegro (Crna Gora)","me","382"],["Montserrat","ms","1",16,["664"]],["Morocco (‫المغرب‬‎)","ma","212",0],["Mozambique (Moçambique)","mz","258"],["Myanmar (Burma) (မြန်မာ)","mm","95"],["Namibia (Namibië)","na","264"],["Nauru","nr","674"],["Nepal (नेपाल)","np","977"],["Netherlands (Nederland)","nl","31"],["New Caledonia (Nouvelle-Calédonie)","nc","687"],["New Zealand","nz","64"],["Nicaragua","ni","505"],["Niger (Nijar)","ne","227"],["Nigeria","ng","234"],["Niue","nu","683"],["Norfolk Island","nf","672"],["North Korea (조선 민주주의 인민 공화국)","kp","850"],["Northern Mariana Islands","mp","1",17,["670"]],["Norway (Norge)","no","47",0],["Oman (‫عُمان‬‎)","om","968"],["Pakistan (‫پاکستان‬‎)","pk","92"],["Palau","pw","680"],["Palestine (‫فلسطين‬‎)","ps","970"],["Panama (Panamá)","pa","507"],["Papua New Guinea","pg","675"],["Paraguay","py","595"],["Peru (Perú)","pe","51"],["Philippines","ph","63"],["Poland (Polska)","pl","48"],["Portugal","pt","351"],["Puerto Rico","pr","1",3,["787","939"]],["Qatar (‫قطر‬‎)","qa","974"],["Réunion (La Réunion)","re","262",0],["Romania (România)","ro","40"],["Russia (Россия)","ru","7",0],["Rwanda","rw","250"],["Saint Barthélemy","bl","590",1],["Saint Helena","sh","290"],["Saint Kitts and Nevis","kn","1",18,["869"]],["Saint Lucia","lc","1",19,["758"]],["Saint Martin (Saint-Martin (partie française))","mf","590",2],["Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)","pm","508"],["Saint Vincent and the Grenadines","vc","1",20,["784"]],["Samoa","ws","685"],["San Marino","sm","378"],["São Tomé and Príncipe (São Tomé e Príncipe)","st","239"],["Saudi Arabia (‫المملكة العربية السعودية‬‎)","sa","966"],["Senegal (Sénégal)","sn","221"],["Serbia (Србија)","rs","381"],["Seychelles","sc","248"],["Sierra Leone","sl","232"],["Singapore","sg","65"],["Sint Maarten","sx","1",21,["721"]],["Slovakia (Slovensko)","sk","421"],["Slovenia (Slovenija)","si","386"],["Solomon Islands","sb","677"],["Somalia (Soomaaliya)","so","252"],["South Africa","za","27"],["South Korea (대한민국)","kr","82"],["South Sudan (‫جنوب السودان‬‎)","ss","211"],["Spain (España)","es","34"],["Sri Lanka (ශ්‍රී ලංකාව)","lk","94"],["Sudan (‫السودان‬‎)","sd","249"],["Suriname","sr","597"],["Svalbard and Jan Mayen","sj","47",1,["79"]],["Sweden (Sverige)","se","46"],["Switzerland (Schweiz)","ch","41"],["Syria (‫سوريا‬‎)","sy","963"],["Taiwan (台灣)","tw","886"],["Tajikistan","tj","992"],["Tanzania","tz","255"],["Thailand (ไทย)","th","66"],["Timor-Leste","tl","670"],["Togo","tg","228"],["Tokelau","tk","690"],["Tonga","to","676"],["Trinidad and Tobago","tt","1",22,["868"]],["Tunisia (‫تونس‬‎)","tn","216"],["Turkey (Türkiye)","tr","90"],["Turkmenistan","tm","993"],["Turks and Caicos Islands","tc","1",23,["649"]],["Tuvalu","tv","688"],["U.S. Virgin Islands","vi","1",24,["340"]],["Uganda","ug","256"],["Ukraine (Україна)","ua","380"],["United Arab Emirates (‫الإمارات العربية المتحدة‬‎)","ae","971"],["United Kingdom","gb","44",0],["United States","us","1",0],["Uruguay","uy","598"],["Uzbekistan (Oʻzbekiston)","uz","998"],["Vanuatu","vu","678"],["Vatican City (Città del Vaticano)","va","39",1,["06698"]],["Venezuela","ve","58"],["Vietnam (Việt Nam)","vn","84"],["Wallis and Futuna (Wallis-et-Futuna)","wf","681"],["Western Sahara (‫الصحراء الغربية‬‎)","eh","212",1,["5288","5289"]],["Yemen (‫اليمن‬‎)","ye","967"],["Zambia","zm","260"],["Zimbabwe","zw","263"],["Åland Islands","ax","358",1,["18"]]],f=0;f<e.length;f++){var g=e[f];e[f]={name:g[0],iso2:g[1],dialCode:g[2],priority:g[3]||0,areaCodes:g[4]||null}}var h={getInstance:function(a){var b=a.getAttribute("data-intl-tel-input-id");return window.intlTelInputGlobals.instances[b]},instances:{},documentReady:function(){return"complete"===document.readyState}};"object"==typeof window&&(window.intlTelInputGlobals=h);var i=0,j={allowDropdown:!0,autoHideDialCode:!0,autoPlaceholder:"polite",customContainer:"",customPlaceholder:null,dropdownContainer:null,excludeCountries:[],formatOnDisplay:!0,geoIpLookup:null,hiddenInput:"",initialCountry:"",localizedCountries:null,nationalMode:!0,onlyCountries:[],placeholderNumberType:"MOBILE",preferredCountries:["us","gb"],separateDialCode:!1,utilsScript:""},k=["800","822","833","844","855","866","877","880","881","882","883","884","885","886","887","888","889"],l=function(a,b){for(var c=Object.keys(a),d=0;d<c.length;d++)b(c[d],a[c[d]])},m=function(a){l(window.intlTelInputGlobals.instances,function(b){window.intlTelInputGlobals.instances[b][a]()})},n=function(){function c(a,d){var e=this;b(this,c),this.id=i++,this.a=a,this.b=null,this.c=null;var f=d||{};this.d={},l(j,function(a,b){e.d[a]=f.hasOwnProperty(a)?f[a]:b}),this.e=Boolean(a.getAttribute("placeholder"))}return d(c,[{key:"_init",value:function(){var a=this;if(this.d.nationalMode&&(this.d.autoHideDialCode=!1),this.d.separateDialCode&&(this.d.autoHideDialCode=this.d.nationalMode=!1),this.g=/Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),this.g&&(document.body.classList.add("iti-mobile"),this.d.dropdownContainer||(this.d.dropdownContainer=document.body)),"undefined"!=typeof Promise){var b=new Promise(function(b,c){a.h=b,a.i=c}),c=new Promise(function(b,c){a.i0=b,a.i1=c});this.promise=Promise.all([b,c])}else this.h=this.i=function(){},this.i0=this.i1=function(){};this.s={},this._b(),this._f(),this._h(),this._i(),this._i3()}},{key:"_b",value:function(){this._d(),this._d2(),this._e(),this.d.localizedCountries&&this._d0(),(this.d.onlyCountries.length||this.d.localizedCountries)&&this.p.sort(this._d1)}},{key:"_c",value:function(b,c,d){c.length>this.countryCodeMaxLen&&(this.countryCodeMaxLen=c.length),this.q.hasOwnProperty(c)||(this.q[c]=[]);for(var e=0;e<this.q[c].length;e++)if(this.q[c][e]===b)return;var f=d!==a?d:this.q[c].length;this.q[c][f]=b}},{key:"_d",value:function(){if(this.d.onlyCountries.length){var a=this.d.onlyCountries.map(function(a){return a.toLowerCase()});this.p=e.filter(function(b){return a.indexOf(b.iso2)>-1})}else if(this.d.excludeCountries.length){var b=this.d.excludeCountries.map(function(a){return a.toLowerCase()});this.p=e.filter(function(a){return-1===b.indexOf(a.iso2)})}else this.p=e}},{key:"_d0",value:function(){for(var a=0;a<this.p.length;a++){var b=this.p[a].iso2.toLowerCase();this.d.localizedCountries.hasOwnProperty(b)&&(this.p[a].name=this.d.localizedCountries[b])}}},{key:"_d1",value:function(a,b){return a.name.localeCompare(b.name)}},{key:"_d2",value:function(){this.countryCodeMaxLen=0,this.dialCodes={},this.q={};for(var a=0;a<this.p.length;a++){var b=this.p[a];this.dialCodes[b.dialCode]||(this.dialCodes[b.dialCode]=!0),this._c(b.iso2,b.dialCode,b.priority)}for(var c=0;c<this.p.length;c++){var d=this.p[c];if(d.areaCodes)for(var e=this.q[d.dialCode][0],f=0;f<d.areaCodes.length;f++){for(var g=d.areaCodes[f],h=1;h<g.length;h++){var i=d.dialCode+g.substr(0,h);this._c(e,i),this._c(d.iso2,i)}this._c(d.iso2,d.dialCode+g)}}}},{key:"_e",value:function(){this.preferredCountries=[];for(var a=0;a<this.d.preferredCountries.length;a++){var b=this.d.preferredCountries[a].toLowerCase(),c=this._y(b,!1,!0);c&&this.preferredCountries.push(c)}}},{key:"_e2",value:function(a,b,c){var d=document.createElement(a);return b&&l(b,function(a,b){return d.setAttribute(a,b)}),c&&c.appendChild(d),d}},{key:"_f",value:function(){this.a.hasAttribute("autocomplete")||this.a.form&&this.a.form.hasAttribute("autocomplete")||this.a.setAttribute("autocomplete","off");var a="iti";this.d.allowDropdown&&(a+=" iti--allow-dropdown"),this.d.separateDialCode&&(a+=" iti--separate-dial-code"),this.d.customContainer&&(a+=" ",a+=this.d.customContainer);var b=this._e2("div",{"class":a});if(this.a.parentNode.insertBefore(b,this.a),this.k=this._e2("div",{"class":"iti__flag-container"},b),b.appendChild(this.a),this.selectedFlag=this._e2("div",{"class":"iti__selected-flag",role:"combobox","aria-controls":"iti-".concat(this.id,"__country-listbox"),"aria-owns":"iti-".concat(this.id,"__country-listbox"),"aria-expanded":"false"},this.k),this.l=this._e2("div",{"class":"iti__flag"},this.selectedFlag),this.d.separateDialCode&&(this.t=this._e2("div",{"class":"iti__selected-dial-code"},this.selectedFlag)),this.d.allowDropdown&&(this.selectedFlag.setAttribute("tabindex","0"),this.u=this._e2("div",{"class":"iti__arrow"},this.selectedFlag),this.m=this._e2("ul",{"class":"iti__country-list iti__hide",id:"iti-".concat(this.id,"__country-listbox"),role:"listbox","aria-label":"List of countries"}),this.preferredCountries.length&&(this._g(this.preferredCountries,"iti__preferred",!0),this._e2("li",{"class":"iti__divider",role:"separator","aria-disabled":"true"},this.m)),this._g(this.p,"iti__standard"),this.d.dropdownContainer?(this.dropdown=this._e2("div",{"class":"iti iti--container"}),this.dropdown.appendChild(this.m)):this.k.appendChild(this.m)),this.d.hiddenInput){var c=this.d.hiddenInput,d=this.a.getAttribute("name");if(d){var e=d.lastIndexOf("[");-1!==e&&(c="".concat(d.substr(0,e),"[").concat(c,"]"))}this.hiddenInput=this._e2("input",{type:"hidden",name:c}),b.appendChild(this.hiddenInput)}}},{key:"_g",value:function(a,b,c){for(var d="",e=0;e<a.length;e++){var f=a[e],g=c?"-preferred":"";d+="<li class='iti__country ".concat(b,"' tabIndex='-1' id='iti-").concat(this.id,"__item-").concat(f.iso2).concat(g,"' role='option' data-dial-code='").concat(f.dialCode,"' data-country-code='").concat(f.iso2,"' aria-selected='false'>"),d+="<div class='iti__flag-box'><div class='iti__flag iti__".concat(f.iso2,"'></div></div>"),d+="<span class='iti__country-name'>".concat(f.name,"</span>"),d+="<span class='iti__dial-code'>+".concat(f.dialCode,"</span>"),d+="</li>"}this.m.insertAdjacentHTML("beforeend",d)}},{key:"_h",value:function(){var a=this.a.getAttribute("value"),b=this.a.value,c=a&&"+"===a.charAt(0)&&(!b||"+"!==b.charAt(0)),d=c?a:b,e=this._5(d),f=this._w(d),g=this.d,h=g.initialCountry,i=g.nationalMode,j=g.autoHideDialCode,k=g.separateDialCode;e&&!f?this._v(d):"auto"!==h&&(h?this._z(h.toLowerCase()):e&&f?this._z("us"):(this.j=this.preferredCountries.length?this.preferredCountries[0].iso2:this.p[0].iso2,d||this._z(this.j)),d||i||j||k||(this.a.value="+".concat(this.s.dialCode))),d&&this._u(d)}},{key:"_i",value:function(){this._j(),this.d.autoHideDialCode&&this._l(),this.d.allowDropdown&&this._i2(),this.hiddenInput&&this._i0()}},{key:"_i0",value:function(){var a=this;this._a14=function(){a.hiddenInput.value=a.getNumber()},this.a.form&&this.a.form.addEventListener("submit",this._a14)}},{key:"_i1",value:function(){for(var a=this.a;a&&"LABEL"!==a.tagName;)a=a.parentNode;return a}},{key:"_i2",value:function(){var a=this;this._a9=function(b){a.m.classList.contains("iti__hide")?a.a.focus():b.preventDefault()};var b=this._i1();b&&b.addEventListener("click",this._a9),this._a10=function(){!a.m.classList.contains("iti__hide")||a.a.disabled||a.a.readOnly||a._n()},this.selectedFlag.addEventListener("click",this._a10),this._a11=function(b){a.m.classList.contains("iti__hide")&&-1!==["ArrowUp","Up","ArrowDown","Down"," ","Enter"].indexOf(b.key)&&(b.preventDefault(),b.stopPropagation(),a._n()),"Tab"===b.key&&a._2()},this.k.addEventListener("keydown",this._a11)}},{key:"_i3",value:function(){var a=this;this.d.utilsScript&&!window.intlTelInputUtils?window.intlTelInputGlobals.documentReady()?window.intlTelInputGlobals.loadUtils(this.d.utilsScript):window.addEventListener("load",function(){window.intlTelInputGlobals.loadUtils(a.d.utilsScript)}):this.i0(),"auto"===this.d.initialCountry?this._i4():this.h()}},{key:"_i4",value:function(){window.intlTelInputGlobals.autoCountry?this.handleAutoCountry():window.intlTelInputGlobals.startedLoadingAutoCountry||(window.intlTelInputGlobals.startedLoadingAutoCountry=!0,"function"==typeof this.d.geoIpLookup&&this.d.geoIpLookup(function(a){window.intlTelInputGlobals.autoCountry=a.toLowerCase(),setTimeout(function(){return m("handleAutoCountry")})},function(){return m("rejectAutoCountryPromise")}))}},{key:"_j",value:function(){var a=this;this._a12=function(){a._v(a.a.value)&&a._m2CountryChange()},this.a.addEventListener("keyup",this._a12),this._a13=function(){setTimeout(a._a12)},this.a.addEventListener("cut",this._a13),this.a.addEventListener("paste",this._a13)}},{key:"_j2",value:function(a){var b=this.a.getAttribute("maxlength");return b&&a.length>b?a.substr(0,b):a}},{key:"_l",value:function(){var a=this;this._a8=function(){a._l2()},this.a.form&&this.a.form.addEventListener("submit",this._a8),this.a.addEventListener("blur",this._a8)}},{key:"_l2",value:function(){if("+"===this.a.value.charAt(0)){var a=this._m(this.a.value);a&&this.s.dialCode!==a||(this.a.value="")}}},{key:"_m",value:function(a){return a.replace(/\D/g,"")}},{key:"_m2",value:function(a){var b=document.createEvent("Event");b.initEvent(a,!0,!0),this.a.dispatchEvent(b)}},{key:"_n",value:function(){this.m.classList.remove("iti__hide"),this.selectedFlag.setAttribute("aria-expanded","true"),this._o(),this.b&&(this._x(this.b,!1),this._3(this.b,!0)),this._p(),this.u.classList.add("iti__arrow--up"),this._m2("open:countrydropdown")}},{key:"_n2",value:function(a,b,c){c&&!a.classList.contains(b)?a.classList.add(b):!c&&a.classList.contains(b)&&a.classList.remove(b)}},{key:"_o",value:function(){var a=this;if(this.d.dropdownContainer&&this.d.dropdownContainer.appendChild(this.dropdown),!this.g){var b=this.a.getBoundingClientRect(),c=window.pageYOffset||document.documentElement.scrollTop,d=b.top+c,e=this.m.offsetHeight,f=d+this.a.offsetHeight+e<c+window.innerHeight,g=d-e>c;if(this._n2(this.m,"iti__country-list--dropup",!f&&g),this.d.dropdownContainer){var h=!f&&g?0:this.a.offsetHeight;this.dropdown.style.top="".concat(d+h,"px"),this.dropdown.style.left="".concat(b.left+document.body.scrollLeft,"px"),this._a4=function(){return a._2()},window.addEventListener("scroll",this._a4)}}}},{key:"_o2",value:function(a){for(var b=a;b&&b!==this.m&&!b.classList.contains("iti__country");)b=b.parentNode;return b===this.m?null:b}},{key:"_p",value:function(){var a=this;this._a0=function(b){var c=a._o2(b.target);c&&a._x(c,!1)},this.m.addEventListener("mouseover",this._a0),this._a1=function(b){var c=a._o2(b.target);c&&a._1(c)},this.m.addEventListener("click",this._a1);var b=!0;this._a2=function(){b||a._2(),b=!1},document.documentElement.addEventListener("click",this._a2);var c="",d=null;this._a3=function(b){b.preventDefault(),"ArrowUp"===b.key||"Up"===b.key||"ArrowDown"===b.key||"Down"===b.key?a._q(b.key):"Enter"===b.key?a._r():"Escape"===b.key?a._2():/^[a-zA-ZÀ-ÿа-яА-Я ]$/.test(b.key)&&(d&&clearTimeout(d),c+=b.key.toLowerCase(),a._s(c),d=setTimeout(function(){c=""},1e3))},document.addEventListener("keydown",this._a3)}},{key:"_q",value:function(a){var b="ArrowUp"===a||"Up"===a?this.c.previousElementSibling:this.c.nextElementSibling;b&&(b.classList.contains("iti__divider")&&(b="ArrowUp"===a||"Up"===a?b.previousElementSibling:b.nextElementSibling),this._x(b,!0))}},{key:"_r",value:function(){this.c&&this._1(this.c)}},{key:"_s",value:function(a){for(var b=0;b<this.p.length;b++)if(this._t(this.p[b].name,a)){var c=this.m.querySelector("#iti-".concat(this.id,"__item-").concat(this.p[b].iso2));this._x(c,!1),this._3(c,!0);break}}},{key:"_t",value:function(a,b){return a.substr(0,b.length).toLowerCase()===b}},{key:"_u",value:function(a){var b=a;if(this.d.formatOnDisplay&&window.intlTelInputUtils&&this.s){var c=!this.d.separateDialCode&&(this.d.nationalMode||"+"!==b.charAt(0)),d=intlTelInputUtils.numberFormat,e=d.NATIONAL,f=d.INTERNATIONAL,g=c?e:f;b=intlTelInputUtils.formatNumber(b,this.s.iso2,g)}b=this._7(b),this.a.value=b}},{key:"_v",value:function(a){var b=a,c=this.s.dialCode,d="1"===c;b&&this.d.nationalMode&&d&&"+"!==b.charAt(0)&&("1"!==b.charAt(0)&&(b="1".concat(b)),b="+".concat(b)),this.d.separateDialCode&&c&&"+"!==b.charAt(0)&&(b="+".concat(c).concat(b));var e=this._5(b,!0),f=this._m(b),g=null;if(e){var h=this.q[this._m(e)],i=-1!==h.indexOf(this.s.iso2)&&f.length<=e.length-1;if(!("1"===c&&this._w(f))&&!i)for(var j=0;j<h.length;j++)if(h[j]){g=h[j];break}}else"+"===b.charAt(0)&&f.length?g="":b&&"+"!==b||(g=this.j);return null!==g&&this._z(g)}},{key:"_w",value:function(a){var b=this._m(a);if("1"===b.charAt(0)){var c=b.substr(1,3);return-1!==k.indexOf(c)}return!1}},{key:"_x",value:function(a,b){var c=this.c;c&&c.classList.remove("iti__highlight"),this.c=a,this.c.classList.add("iti__highlight"),b&&this.c.focus()}},{key:"_y",value:function(a,b,c){for(var d=b?e:this.p,f=0;f<d.length;f++)if(d[f].iso2===a)return d[f];if(c)return null;throw new Error("No country data for '".concat(a,"'"))}},{key:"_z",value:function(a){var b=this.s.iso2?this.s:{};this.s=a?this._y(a,!1,!1):{},this.s.iso2&&(this.j=this.s.iso2),this.l.setAttribute("class","iti__flag iti__".concat(a));var c=a?"".concat(this.s.name,": +").concat(this.s.dialCode):"Unknown";if(this.selectedFlag.setAttribute("title",c),this.d.separateDialCode){var d=this.s.dialCode?"+".concat(this.s.dialCode):"";this.t.innerHTML=d;var e=this.selectedFlag.offsetWidth||this._z2();this.a.style.paddingLeft="".concat(e+6,"px")}if(this._0(),this.d.allowDropdown){var f=this.b;if(f&&(f.classList.remove("iti__active"),f.setAttribute("aria-selected","false")),a){var g=this.m.querySelector("#iti-".concat(this.id,"__item-").concat(a,"-preferred"))||this.m.querySelector("#iti-".concat(this.id,"__item-").concat(a));g.setAttribute("aria-selected","true"),g.classList.add("iti__active"),this.b=g,this.selectedFlag.setAttribute("aria-activedescendant",g.getAttribute("id"))}}return b.iso2!==a}},{key:"_z2",value:function(){var a=this.a.parentNode.cloneNode();a.style.visibility="hidden",document.body.appendChild(a);var b=this.k.cloneNode();a.appendChild(b);var c=this.selectedFlag.cloneNode(!0);b.appendChild(c);var d=c.offsetWidth;return a.parentNode.removeChild(a),d}},{key:"_0",value:function(){var a="aggressive"===this.d.autoPlaceholder||!this.e&&"polite"===this.d.autoPlaceholder;if(window.intlTelInputUtils&&a){var b=intlTelInputUtils.numberType[this.d.placeholderNumberType],c=this.s.iso2?intlTelInputUtils.getExampleNumber(this.s.iso2,this.d.nationalMode,b):"";c=this._7(c),"function"==typeof this.d.customPlaceholder&&(c=this.d.customPlaceholder(c,this.s)),this.a.setAttribute("placeholder",c)}}},{key:"_1",value:function(a){var b=this._z(a.getAttribute("data-country-code"));this._2(),this._4(a.getAttribute("data-dial-code"),!0),this.a.focus();var c=this.a.value.length;this.a.setSelectionRange(c,c),b&&this._m2CountryChange()}},{key:"_2",value:function(){this.m.classList.add("iti__hide"),this.selectedFlag.setAttribute("aria-expanded","false"),this.u.classList.remove("iti__arrow--up"),document.removeEventListener("keydown",this._a3),document.documentElement.removeEventListener("click",this._a2),this.m.removeEventListener("mouseover",this._a0),this.m.removeEventListener("click",this._a1),this.d.dropdownContainer&&(this.g||window.removeEventListener("scroll",this._a4),this.dropdown.parentNode&&this.dropdown.parentNode.removeChild(this.dropdown)),this._m2("close:countrydropdown")}},{key:"_3",value:function(a,b){var c=this.m,d=window.pageYOffset||document.documentElement.scrollTop,e=c.offsetHeight,f=c.getBoundingClientRect().top+d,g=f+e,h=a.offsetHeight,i=a.getBoundingClientRect().top+d,j=i+h,k=i-f+c.scrollTop,l=e/2-h/2;if(i<f)b&&(k-=l),c.scrollTop=k;else if(j>g){b&&(k+=l);var m=e-h;c.scrollTop=k-m}}},{key:"_4",value:function(a,b){var c,d=this.a.value,e="+".concat(a);if("+"===d.charAt(0)){var f=this._5(d);c=f?d.replace(f,e):e}else{if(this.d.nationalMode||this.d.separateDialCode)return;if(d)c=e+d;else{if(!b&&this.d.autoHideDialCode)return;c=e}}this.a.value=c}},{key:"_5",value:function(a,b){var c="";if("+"===a.charAt(0))for(var d="",e=0;e<a.length;e++){var f=a.charAt(e);if(!isNaN(parseInt(f,10))){if(d+=f,b)this.q[d]&&(c=a.substr(0,e+1));else if(this.dialCodes[d]){c=a.substr(0,e+1);break}if(d.length===this.countryCodeMaxLen)break}}return c}},{key:"_6",value:function(){var a=this.a.value.trim(),b=this.s.dialCode,c=this._m(a);return(this.d.separateDialCode&&"+"!==a.charAt(0)&&b&&c?"+".concat(b):"")+a}},{key:"_7",value:function(a){var b=a;if(this.d.separateDialCode){var c=this._5(b);if(c){c="+".concat(this.s.dialCode);var d=" "===b[c.length]||"-"===b[c.length]?c.length+1:c.length;b=b.substr(d)}}return this._j2(b)}},{key:"_m2CountryChange",value:function(){this._m2("countrychange")}},{key:"handleAutoCountry",value:function(){"auto"===this.d.initialCountry&&(this.j=window.intlTelInputGlobals.autoCountry,this.a.value||this.setCountry(this.j),this.h())}},{key:"handleUtils",value:function(){window.intlTelInputUtils&&(this.a.value&&this._u(this.a.value),this._0()),this.i0()}},{key:"destroy",value:function(){var a=this.a.form;if(this.d.allowDropdown){this._2(),this.selectedFlag.removeEventListener("click",this._a10),this.k.removeEventListener("keydown",this._a11);var b=this._i1();b&&b.removeEventListener("click",this._a9)}this.hiddenInput&&a&&a.removeEventListener("submit",this._a14),this.d.autoHideDialCode&&(a&&a.removeEventListener("submit",this._a8),this.a.removeEventListener("blur",this._a8)),this.a.removeEventListener("keyup",this._a12),this.a.removeEventListener("cut",this._a13),this.a.removeEventListener("paste",this._a13),this.a.removeAttribute("data-intl-tel-input-id");var c=this.a.parentNode;c.parentNode.insertBefore(this.a,c),c.parentNode.removeChild(c),delete window.intlTelInputGlobals.instances[this.id]}},{key:"getExtension",value:function(){return window.intlTelInputUtils?intlTelInputUtils.getExtension(this._6(),this.s.iso2):""}},{key:"getNumber",value:function(a){if(window.intlTelInputUtils){
var b=this.s.iso2;return intlTelInputUtils.formatNumber(this._6(),b,a)}return""}},{key:"getNumberType",value:function(){return window.intlTelInputUtils?intlTelInputUtils.getNumberType(this._6(),this.s.iso2):-99}},{key:"getSelectedCountryData",value:function(){return this.s}},{key:"getValidationError",value:function(){if(window.intlTelInputUtils){var a=this.s.iso2;return intlTelInputUtils.getValidationError(this._6(),a)}return-99}},{key:"isValidNumber",value:function(){var a=this._6().trim(),b=this.d.nationalMode?this.s.iso2:"";return window.intlTelInputUtils?intlTelInputUtils.isValidNumber(a,b):null}},{key:"setCountry",value:function(a){var b=a.toLowerCase();this.l.classList.contains("iti__".concat(b))||(this._z(b),this._4(this.s.dialCode,!1),this._m2CountryChange())}},{key:"setNumber",value:function(a){var b=this._v(a);this._u(a),b&&this._m2CountryChange()}},{key:"setPlaceholderNumberType",value:function(a){this.d.placeholderNumberType=a,this._0()}}]),c}();h.getCountryData=function(){return e};var o=function(a,b,c){var d=document.createElement("script");d.onload=function(){m("handleUtils"),b&&b()},d.onerror=function(){m("rejectUtilsScriptPromise"),c&&c()},d.className="iti-load-utils",d.async=!0,d.src=a,document.body.appendChild(d)};return h.loadUtils=function(a){if(!window.intlTelInputUtils&&!window.intlTelInputGlobals.startedLoadingUtilsScript){if(window.intlTelInputGlobals.startedLoadingUtilsScript=!0,"undefined"!=typeof Promise)return new Promise(function(b,c){return o(a,b,c)});o(a)}return null},h.defaults=j,h.version="17.0.19",function(a,b){var c=new n(a,b);return c._init(),a.setAttribute("data-intl-tel-input-id",c.id),window.intlTelInputGlobals.instances[c.id]=c,c}}()});
!function(){"use strict";!function(e,t,s){function i(e){return e.filter(((e,t,s)=>s.indexOf(e)===t))}function a(e,t){return e.filter((e=>-1!=t.indexOf(e)))}function r(e,t){let s=Math.min(e.length,t.length),i={};for(let a=0;a<s;a++)i[e[a]]=t[a];return i}function n(e,t,s=1){let i=s||1,a=Math.abs(Math.floor((t-e)/i))+1;return[...Array(a).keys()].map((t=>t*s+e))}let o="/motopress/appointment/v1";function l(e,t={},s="GET"){return new Promise(((i,a)=>{wp.apiRequest({path:o+e,type:s,data:t}).done((e=>i(e))).fail(((e,t)=>{let s="parsererror";s=e.responseJSON&&e.responseJSON.message?e.responseJSON.message:`Status: ${t}`,"parsererror"==s&&(s="REST request failed. Maybe PHP error on the server side. Check PHP logs."),a(new Error(s))}))}))}function h(e,t={}){return l(e,t,"GET")}function c(e,t){return l(e,t,"POST")}class p{constructor(){this.settings=this.getDefaults(),this.loadingPromise=this.load()}getDefaults(){return{plugin_name:"Appointment Booking",today:"2030-01-01",business_name:"",default_time_step:30,default_booking_status:"confirmed",confirmation_mode:"auto",terms_page_id_for_acceptance:0,allow_multibooking:!1,allow_coupons:!1,allow_customer_account_creation:!1,country:"",currency:"EUR",currency_symbol:"&euro;",currency_position:"before",decimal_separator:".",thousand_separator:",",number_of_decimals:2,timezone:"UTC",date_format:"F j, Y",time_format:"H:i",week_starts_on:0,thumbnail_size:{width:150,height:150},flatpickr_locale:"en",enable_payments:!1,active_gateways:[],reservation_received_page_url:"",failed_transaction_page_url:"",default_payment_gateway:""}}load(){return new Promise(((e,t)=>{h("/settings").then((e=>this.settings=e),(e=>console.error("Unable to load public settings.",e))).finally((()=>e(this.settings)))}))}ready(){return this.loadingPromise}getPluginName(){return this.settings.plugin_name}getBusinessDate(){return this.settings.today}getBusinessName(){return this.settings.business_name}getTimeStep(){return this.settings.default_time_step}getDefaultBookingStatus(){return this.settings.default_booking_status}getConfirmationMode(){return this.settings.confirmation_mode}getTermsPageIdForAcceptance(){return this.settings.terms_page_id_for_acceptance}isMultibookingEnabled(){return this.settings.allow_multibooking}isCouponsEnabled(){return this.settings.allow_coupons}isAllowCustomerAccountCreation(){return this.settings.allow_customer_account_creation}getCountry(){return this.settings.country}getCurrency(){return this.settings.currency}getCurrencySymbol(){return this.settings.currency_symbol}getCurrencyPosition(){return this.settings.currency_position}getDecimalSeparator(){return this.settings.decimal_separator}getThousandSeparator(){return this.settings.thousand_separator}getDecimalsCount(){return this.settings.number_of_decimals}getTimezone(){return this.settings.timezone}getDateFormat(){return this.settings.date_format}getTimeFormat(){return this.settings.time_format}getFirstDayOfWeek(){return this.settings.week_starts_on}getThumbnailSize(){return this.settings.thumbnail_size}getFlatpickrLocale(){return this.settings.flatpickr_locale}isPaymentsEnabled(){return this.settings.enable_payments}getActiveGateways(){return this.settings.active_gateways}getReservationReceivedPageUrl(){return this.settings.reservation_received_page_url}getFailedTransactionPageUrl(){return this.settings.failed_transaction_page_url}getDefaultPaymentGateway(){return this.settings.default_payment_gateway}}class d{constructor(){this.settingsCtrl=new p,this.loadingPromise=this.load()}load(){return Promise.all([this.settingsCtrl.ready()]).then((()=>this))}ready(){return this.loadingPromise}settings(){return this.settingsCtrl}static getInstance(){return null==d.instance&&(d.instance=new d),d.instance}}function m(){return d.getInstance()}const u="undefined"!=typeof wp&&wp.i18n&&wp.i18n.__?wp.i18n.__:(e,t="")=>e,g="undefined"!=typeof wp&&wp.i18n&&wp.i18n._x?wp.i18n._x:(e,t,s="")=>e;"undefined"!=typeof wp&&wp.i18n&&wp.i18n.sprintf&&wp.i18n.sprintf;const y={weekdays:{shorthand:[u("Sun","motopress-appointment"),u("Mon","motopress-appointment"),u("Tue","motopress-appointment"),u("Wed","motopress-appointment"),u("Thu","motopress-appointment"),u("Fri","motopress-appointment"),u("Sat","motopress-appointment")],longhand:[u("Sunday","motopress-appointment"),u("Monday","motopress-appointment"),u("Tuesday","motopress-appointment"),u("Wednesday","motopress-appointment"),u("Thursday","motopress-appointment"),u("Friday","motopress-appointment"),u("Saturday","motopress-appointment")]},months:{shorthand:[u("Jan","motopress-appointment"),u("Feb","motopress-appointment"),u("Mar","motopress-appointment"),u("Apr","motopress-appointment"),g("May","Month (short)","motopress-appointment"),u("Jun","motopress-appointment"),u("Jul","motopress-appointment"),u("Aug","motopress-appointment"),u("Sep","motopress-appointment"),u("Oct","motopress-appointment"),u("Nov","motopress-appointment"),u("Dec","motopress-appointment")],longhand:[u("January","motopress-appointment"),u("February","motopress-appointment"),u("March","motopress-appointment"),u("April","motopress-appointment"),g("May","Month","motopress-appointment"),u("June","motopress-appointment"),u("July","motopress-appointment"),u("August","motopress-appointment"),u("September","motopress-appointment"),u("October","motopress-appointment"),u("November","motopress-appointment"),u("December","motopress-appointment")]},amPM:["AM","PM"],firstDayOfWeek:m().settings().getFirstDayOfWeek()};function f(t,s="public"){if("string"==typeof t)return t;if("internal"==s)return f(t,"Y-m-d");if("public"==s)return e.format(m().settings().getDateFormat(),t);let i=(e,t=2)=>("00"+e).slice(-t),a=!1;return s.split("").map((e=>{if(a)return a=!1,e;switch(e){case"\\":return a=!0,"";case"j":return t.getDate();case"d":return i(t.getDate());case"D":return y.weekdays.shorthand[t.getDay()];case"l":return y.weekdays.longhand[t.getDay()];case"N":return t.getDay()||7;case"w":return t.getDay();case"z":let s=new Date(t.getFullYear(),0,1),r=s.getTimezoneOffset()-t.getTimezoneOffset(),n=t-s+60*r*1e3,o=864e5;return Math.floor(n/o);case"W":let l=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())),h=l.getUTCDay()||7;l.setUTCDate(l.getUTCDate()+4-h);let c=new Date(Date.UTC(l.getUTCFullYear(),0,1)),p=864e5;return Math.ceil(((l-c)/p+1)/7);case"F":return y.months.longhand[t.getMonth()];case"M":return y.months.shorthand[t.getMonth()];case"m":return i(t.getMonth()+1);case"n":return t.getMonth()+1;case"t":return new Date(t.getFullYear(),t.getMonth()+1,0).getDate();case"Y":return t.getFullYear();case"y":return String(t.getFullYear()).substring(2);case"L":return t.getFullYear()%4==0?1:0;case"A":return y.amPM[t.getHours()>11?1:0];case"a":return y.amPM[t.getHours()>11?1:0].toLowerCase();case"H":return i(t.getHours());case"h":return i(t.getHours()%12||12);case"G":return t.getHours();case"g":return t.getHours()%12||12;case"i":return i(t.getMinutes());case"s":return i(t.getSeconds());case"v":return i(t.getMilliseconds(),3);case"u":return i(t.getMilliseconds(),3)+"000";case"O":case"P":let d=-t.getTimezoneOffset(),m=d>=0?"+":"-",u=Math.floor(Math.abs(d)/60),g=Math.abs(d)%60,b="O"==e?"":":";return m+i(u)+b+i(g);case"Z":return 60*t.getTimezoneOffset();case"U":return Math.floor(t.getTime()/1e3);case"c":return f(t,"Y-m-d\\TH:i:sP");case"r":return f(t,"D, d M Y H:i:s O");case"S":case"o":case"B":case"e":case"T":case"I":return"";default:return e}})).join("")}function b(e){let t=e.match(/(\d{4})-(\d{2})-(\d{2})/);if(null!=t){let e=parseInt(t[1]),s=parseInt(t[2]),i=parseInt(t[3]);return new Date(e,s-1,i)}return null}function v(){let e=new Date;return e.setHours(0,0,0,0),e}function S(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _,P,C={exports:{}},w={exports:{}};_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",P={rotl:function(e,t){return e<<t|e>>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return 16711935&P.rotl(e,8)|4278255360&P.rotl(e,24);for(var t=0;t<e.length;t++)e[t]=P.endian(e[t]);return e},randomBytes:function(e){for(var t=[];e>0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],s=0,i=0;s<e.length;s++,i+=8)t[i>>>5]|=e[s]<<24-i%32;return t},wordsToBytes:function(e){for(var t=[],s=0;s<32*e.length;s+=8)t.push(e[s>>>5]>>>24-s%32&255);return t},bytesToHex:function(e){for(var t=[],s=0;s<e.length;s++)t.push((e[s]>>>4).toString(16)),t.push((15&e[s]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],s=0;s<e.length;s+=2)t.push(parseInt(e.substr(s,2),16));return t},bytesToBase64:function(e){for(var t=[],s=0;s<e.length;s+=3)for(var i=e[s]<<16|e[s+1]<<8|e[s+2],a=0;a<4;a++)8*s+6*a<=8*e.length?t.push(_.charAt(i>>>6*(3-a)&63)):t.push("=");return t.join("")},base64ToBytes:function(e){e=e.replace(/[^A-Z0-9+\/]/gi,"");for(var t=[],s=0,i=0;s<e.length;i=++s%4)0!=i&&t.push((_.indexOf(e.charAt(s-1))&Math.pow(2,-2*i+8)-1)<<2*i|_.indexOf(e.charAt(s))>>>6-2*i);return t}},w.exports=P;var $=w.exports,k={utf8:{stringToBytes:function(e){return k.bin.stringToBytes(unescape(encodeURIComponent(e)))},bytesToString:function(e){return decodeURIComponent(escape(k.bin.bytesToString(e)))}},bin:{stringToBytes:function(e){for(var t=[],s=0;s<e.length;s++)t.push(255&e.charCodeAt(s));return t},bytesToString:function(e){for(var t=[],s=0;s<e.length;s++)t.push(String.fromCharCode(e[s]));return t.join("")}}},T=k,I=function(e){return null!=e&&(D(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&D(e.slice(0,0))}(e)||!!e._isBuffer)};function D(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}!function(){var e=$,t=T.utf8,s=I,i=T.bin,a=function(r,n){r.constructor==String?r=n&&"binary"===n.encoding?i.stringToBytes(r):t.stringToBytes(r):s(r)?r=Array.prototype.slice.call(r,0):Array.isArray(r)||r.constructor===Uint8Array||(r=r.toString());for(var o=e.bytesToWords(r),l=8*r.length,h=1732584193,c=-271733879,p=-1732584194,d=271733878,m=0;m<o.length;m++)o[m]=16711935&(o[m]<<8|o[m]>>>24)|4278255360&(o[m]<<24|o[m]>>>8);o[l>>>5]|=128<<l%32,o[14+(l+64>>>9<<4)]=l;var u=a._ff,g=a._gg,y=a._hh,f=a._ii;for(m=0;m<o.length;m+=16){var b=h,v=c,S=p,_=d;h=u(h,c,p,d,o[m+0],7,-680876936),d=u(d,h,c,p,o[m+1],12,-389564586),p=u(p,d,h,c,o[m+2],17,606105819),c=u(c,p,d,h,o[m+3],22,-1044525330),h=u(h,c,p,d,o[m+4],7,-176418897),d=u(d,h,c,p,o[m+5],12,1200080426),p=u(p,d,h,c,o[m+6],17,-1473231341),c=u(c,p,d,h,o[m+7],22,-45705983),h=u(h,c,p,d,o[m+8],7,1770035416),d=u(d,h,c,p,o[m+9],12,-1958414417),p=u(p,d,h,c,o[m+10],17,-42063),c=u(c,p,d,h,o[m+11],22,-1990404162),h=u(h,c,p,d,o[m+12],7,1804603682),d=u(d,h,c,p,o[m+13],12,-40341101),p=u(p,d,h,c,o[m+14],17,-1502002290),h=g(h,c=u(c,p,d,h,o[m+15],22,1236535329),p,d,o[m+1],5,-165796510),d=g(d,h,c,p,o[m+6],9,-1069501632),p=g(p,d,h,c,o[m+11],14,643717713),c=g(c,p,d,h,o[m+0],20,-373897302),h=g(h,c,p,d,o[m+5],5,-701558691),d=g(d,h,c,p,o[m+10],9,38016083),p=g(p,d,h,c,o[m+15],14,-660478335),c=g(c,p,d,h,o[m+4],20,-405537848),h=g(h,c,p,d,o[m+9],5,568446438),d=g(d,h,c,p,o[m+14],9,-1019803690),p=g(p,d,h,c,o[m+3],14,-187363961),c=g(c,p,d,h,o[m+8],20,1163531501),h=g(h,c,p,d,o[m+13],5,-1444681467),d=g(d,h,c,p,o[m+2],9,-51403784),p=g(p,d,h,c,o[m+7],14,1735328473),h=y(h,c=g(c,p,d,h,o[m+12],20,-1926607734),p,d,o[m+5],4,-378558),d=y(d,h,c,p,o[m+8],11,-2022574463),p=y(p,d,h,c,o[m+11],16,1839030562),c=y(c,p,d,h,o[m+14],23,-35309556),h=y(h,c,p,d,o[m+1],4,-1530992060),d=y(d,h,c,p,o[m+4],11,1272893353),p=y(p,d,h,c,o[m+7],16,-155497632),c=y(c,p,d,h,o[m+10],23,-1094730640),h=y(h,c,p,d,o[m+13],4,681279174),d=y(d,h,c,p,o[m+0],11,-358537222),p=y(p,d,h,c,o[m+3],16,-722521979),c=y(c,p,d,h,o[m+6],23,76029189),h=y(h,c,p,d,o[m+9],4,-640364487),d=y(d,h,c,p,o[m+12],11,-421815835),p=y(p,d,h,c,o[m+15],16,530742520),h=f(h,c=y(c,p,d,h,o[m+2],23,-995338651),p,d,o[m+0],6,-198630844),d=f(d,h,c,p,o[m+7],10,1126891415),p=f(p,d,h,c,o[m+14],15,-1416354905),c=f(c,p,d,h,o[m+5],21,-57434055),h=f(h,c,p,d,o[m+12],6,1700485571),d=f(d,h,c,p,o[m+3],10,-1894986606),p=f(p,d,h,c,o[m+10],15,-1051523),c=f(c,p,d,h,o[m+1],21,-2054922799),h=f(h,c,p,d,o[m+8],6,1873313359),d=f(d,h,c,p,o[m+15],10,-30611744),p=f(p,d,h,c,o[m+6],15,-1560198380),c=f(c,p,d,h,o[m+13],21,1309151649),h=f(h,c,p,d,o[m+4],6,-145523070),d=f(d,h,c,p,o[m+11],10,-1120210379),p=f(p,d,h,c,o[m+2],15,718787259),c=f(c,p,d,h,o[m+9],21,-343485551),h=h+b>>>0,c=c+v>>>0,p=p+S>>>0,d=d+_>>>0}return e.endian([h,c,p,d])};a._ff=function(e,t,s,i,a,r,n){var o=e+(t&s|~t&i)+(a>>>0)+n;return(o<<r|o>>>32-r)+t},a._gg=function(e,t,s,i,a,r,n){var o=e+(t&i|s&~i)+(a>>>0)+n;return(o<<r|o>>>32-r)+t},a._hh=function(e,t,s,i,a,r,n){var o=e+(t^s^i)+(a>>>0)+n;return(o<<r|o>>>32-r)+t},a._ii=function(e,t,s,i,a,r,n){var o=e+(s^(t|~i))+(a>>>0)+n;return(o<<r|o>>>32-r)+t},a._blocksize=16,a._digestsize=16,C.exports=function(t,s){if(null==t)throw new Error("Illegal argument "+t);var r=e.wordsToBytes(a(t,s));return s&&s.asBytes?r:s&&s.asString?i.bytesToString(r):e.bytesToHex(r)}}();var E=S(C.exports);class A{setupProperties(){this.itemId="",this.service=null,this.serviceCategories={},this.employee=null,this.location=null,this.date=null,this.time=null,this.capacity=1,this.availableEmployees=[],this.availableLocations=[],this.bookingVariants=[]}constructor(e){this.setupProperties(),this.itemId=e}getDate(){return this.date}getTime(){return this.time}getItemId(){return this.itemId}getAvailableEmployeeIds(){return this.availableEmployees.map((e=>e.id))}getAvailableLocationIds(){return this.availableLocations.map((e=>e.id))}getAvailableIds(){return{service_id:null!==this.service?this.service.id:0,employee_id:null!==this.employee?this.employee.id:0,employee_ids:this.getAvailableEmployeeIds(),location_ids:this.getAvailableLocationIds()}}getIds(){return{service_id:null!==this.service?this.service.id:0,employee_id:null!==this.employee?this.employee.id:0,location_id:null!==this.location?this.location.id:0}}toArray(e="all"){return"ids"===e?this.getIds():"availability"===e?this.getAvailableIds():"period"===e?{date:null!==this.date?f(this.date,"internal"):"",time:null!==this.time?this.time.toString("internal"):""}:jQuery.extend(this.getIds(),{date:null!==this.date?f(this.date,"internal"):"",time:null!==this.time?this.time.toString("internal"):"",capacity:this.capacity})}isSet(e="all"){let t=!0;return"all"!==e&&"ids"!==e||(t=t&&null!==this.service&&null!==this.employee&&null!==this.location),"all"!==e&&"period"!==e||(t=t&&null!==this.date&&null!==this.time),t}isAtTime(e,t){return null!==this.date&&null!==this.time&&f(this.date,"internal")==f(e,"internal")&&this.time.toString("internal")==t.toString("internal")}getCapacity(){return this.capacity}getMinCapacity(){return null!==this.service?this.service.getMinCapacity(this.getEmployeeId()):1}getMaxCapacity(){return null!==this.service?this.service.getMaxCapacity(this.getEmployeeId()):1}getMinPossibleCapacity(){if(null===this.service)return 1;{let e=this.getMaxCapacity();for(let t of this.bookingVariants)e=Math.min(e,t.minCapacity);return e}}getMaxPossibleCapacity(){if(null===this.service)return 1;{let e=this.getMinCapacity();for(let t of this.bookingVariants)e=Math.max(e,t.maxCapacity);return e}}getCapacityOptions(){if(null===this.service)return[1];{let e=[];for(let t of this.bookingVariants)e=e.concat(n(t.minCapacity,t.maxCapacity));return i(e)}}getPrice(){if(!this.service)return 0;let e=this.employee?this.employee.id:0;return this.service.getPrice(e,this.capacity)}getDeposit(e){let t=0;switch(this.service.depositType){case"disabled":default:t=e;break;case"fixed":t=this.service.depositAmount;break;case"percentage":t=e*this.service.depositAmount/100}return t>e?e:t}getHash(e="all"){return E(JSON.stringify(this.toArray(e)))}didChange(e,t="all"){return e!==this.getHash(t)}getEmployeeId(){return this.employee?this.employee.getId():0}getEmployee(e){if(null!==this.employee&&this.employee.getId()==e)return this.employee;for(let t of this.availableEmployees)if(t.id==e)return t;return null}getLocationId(){return this.location?this.location.getId():0}getLocation(e){if(null!==this.location&&this.location.id==e)return this.location;for(let t of this.availableLocations)if(t.id==e)return t;return null}getService(){return this.service}hasMultipleAvailableEmployees(){return this.availableEmployees.length>1}hasMultipleAvailableLocations(){return this.availableLocations.length>1}hasMultipleAvailableVariants(){return this.hasMultipleAvailableEmployees()||this.hasMultipleAvailableLocations()}setService(e){this.service=e}setServiceCategories(e){this.serviceCategories=e}setEmployee(e,t=!0){"number"==typeof e&&(e=this.getEmployee(e)),this.employee=e,!0===t&&(this.availableEmployees=[e])}setAvailableEmployees(e,t=!0){this.availableEmployees=e,!0===t&&(this.employee=null)}setLocation(e,t=!0){"number"==typeof e&&(e=this.getLocation(e)),this.location=e,!0===t&&(this.availableLocations=[e])}setAvailableLocations(e,t=!0){this.availableLocations=e,!0===t&&(this.location=null)}setCapacity(e){this.capacity=e}setBookingVariants(e){this.bookingVariants=[];for(let t of e)this.bookingVariants.push({employeeId:t[0],locationId:t[1],minCapacity:t[2],maxCapacity:t[3]})}getBookingVariantForCapacity(e){for(let t of this.bookingVariants)if(e>=t.minCapacity&&e<=t.maxCapacity)return t;return{employeeId:this.getEmployeeId(),locationId:this.getLocationId(),minCapacity:this.getMinCapacity(),maxCapacity:this.getMaxCapacity()}}removeBookingVariatForEmployee(e){for(let t in this.bookingVariants){this.bookingVariants[t].employeeId==e&&this.bookingVariants.splice(t,1)}}}class M{constructor(e=null){this.setupProperties(),null!=e&&this.merge(e)}setupProperties(){this.keys=[],this.values={},this.length=0}merge(e){for(let t in e)this.push(t,e[t])}push(e,t){let s=!this.includesKey(e);return this.values[e]=t,s&&(this.keys.push(e),this.length++),s}find(e,t=null){return this.includesKey(e)?this.values[e]:t}findNext(e,t=null){let s=this.findNextKey(e);return""!==s?this.values[s]:t}findNextKey(e){let t=this.keys.indexOf(e);if(-1===t)return"";let s=t+1;return s<this.length?this.keys[s]:this.keys[t]}findPrevious(e,t=null){let s=this.findPreviousKey(e);return""!==s?this.values[s]:t}findPreviousKey(e){let t=this.keys.indexOf(e);if(-1===t)return"";let s=t-1;return s>=0?this.keys[s]:this.keys[t]}update(e,t){return this.push(e,t)}remove(e){if(!this.includesKey(e))return null;let t=this.values[e];delete this.values[e];let s=this.keys.indexOf(e);return this.keys.splice(s,1),this.length--,t}empty(){return this.keys=[],this.values={},this.length=0,this}isEmpty(){return 0==this.length}includesKey(e){return e in this.values}firstKey(){return this.keys.length>0?this.keys[0]:null}firstValue(){let e=this.firstKey();return null!==e?this.values[e]:null}lastValue(){let e=this.lastKey();return null!=e?this.values[e]:null}lastKey(){return this.isEmpty()?null:this.keys[this.length-1]}cloneKeys(){return[...this.keys]}getColumn(e){let t=[];for(let s of this.keys){let i=this.values[s][e];null!=i&&(Array.isArray(i)?t=t.concat(i):t.push(i))}return i(t)}forEach(e){let t=0;for(let s of this.keys){let i=e(this.values[s],t,s,this);if(t++,!1===i)break}}map(e){let t=[],s=0;for(let i of this.keys)t.push(e(this.values[i],s,i,this)),s++;return t}toArray(){let e=[];for(let t of this.keys)e.push(this.values[t]);return e}getLength(){return this.length}}let x={};function B(e,t=!1){return"object"==typeof e?0==function(e,t=!1){return"object"==typeof e?Array.isArray(e)?e.length:Object.keys(e).length:t?0:1}(e):!!t||!e}function F(e="",t=!1){let s=function(e,t){return t<(e=parseInt(e,10).toString(16)).length?e.slice(e.length-t):t>e.length?Array(t-e.length+1).join("0")+e:e};x.uniqid_seed||(x.uniqid_seed=Math.floor(123456789*Math.random())),x.uniqid_seed++;let i=e;return i+=s(parseInt((new Date).getTime()/1e3,10),8),i+=s(x.uniqid_seed,5),t&&(i+=(10*Math.random()).toFixed(8).toString()),i}class L{setupProperties(){this.items=new M,this.activeItem=null,this.customerDetails={name:"",email:"",phone:""},this.paymentDetails={booking_id:0,gateway_id:"none"},this.coupon=null}constructor(){this.setupProperties()}createItem(e=""){e||(e=F());let t=new A(e);return this.items.push(e,t),this.activeItem=t,t}getItem(e){return this.items.find(e)}getActiveItem(){return this.activeItem}getActiveItemId(){return null!==this.activeItem?this.activeItem.getItemId():""}getItems(){return this.items}getItemsCount(){return this.items.getLength()}setActiveItem(e){this.activeItem="string"==typeof e?this.getItem(e):e}removeItem(e){"string"==typeof e?this.items.remove(e):this.items.remove(e.getItemId())}isEmpty(){return 0===this.getItemsCount()}getProducts(){let e=[];return this.items.forEach((t=>{null!=t.service&&e.push({name:t.service.name,price:t.getPrice(),capacity:t.getCapacity(),quantity_label:t.getService().getQuantityLabel()})})),e}getSubtotalPrice(e=null){null===e&&(e=this.getProducts());let t=0;for(let s of e)t+=s.price;return t}getTotalPrice(e=null){let t=this.getSubtotalPrice(e);if(this.hasCoupon()){let e=this.coupon.calcDiscountAmount(this);return Math.max(0,t-e)}return t}getDeposit(){let e=0;return this.items.forEach((t=>{let s=t.getPrice();this.hasCoupon()&&(s-=this.coupon.calcDiscountForCartItem(t)),e+=t.getDeposit(s)})),e}getCustomer(){return this.customerDetails}getOrder(){let e=this.getProducts(),t={products:e,subtotal:this.getSubtotalPrice(e),total:this.getTotalPrice(e),customer:this.getCustomer()};return this.hasCoupon()&&(t.coupon={code:this.coupon.getCode(),amount:this.coupon.calcDiscountAmount(this)}),t.deposit=this.getDeposit(),t}getPaymentDetails(){return this.paymentDetails}toArray(e="all"){let t={items:[],customer:this.customerDetails};return this.items.forEach((e=>{e.isSet()&&t.items.push(e.toArray())})),m().settings().isPaymentsEnabled()&&(t.payment_details=this.paymentDetails),this.hasCoupon()&&(t.coupon=this.coupon.getCode()),"items"===e?t.items:t}getHash(e="all"){return E("order"!==e?JSON.stringify(this.toArray(e)):JSON.stringify(this.getOrder()))}didChange(e,t="all"){return e!==this.getHash(t)}setCustomerDetails(e){jQuery.extend(this.customerDetails,e)}setPaymentDetails(e){jQuery.extend(this.paymentDetails,e)}reset(){this.setupProperties()}getMinDate(){let e=null;return this.items.forEach((t=>{t.date&&(!e||e>t.date)&&(e=new Date(t.date.getTime()))})),e||v()}getServiceIds(){let e=this.items.map((e=>null!=e.service?e.service.id:0));return e=i(e),e}updateServices(e){for(let t of e)this.items.forEach((e=>{null!=e.service&&e.service.id===t.id&&(e.service=t)}))}setCoupon(e){this.coupon=e}removeCoupon(){this.coupon=null}hasCoupon(){return null!=this.coupon}testCoupon(){this.hasCoupon()&&!this.coupon.isApplicableForCart(this)&&this.removeCoupon()}}class R{constructor(e,t={}){this.id=e,this.setupProperties(),this.setupValues(t)}setupProperties(){}setupValues(e){for(let t in e)this[t]=e[t]}getId(){return this.id}}class O extends R{setupProperties(){super.setupProperties(),this.name=""}}class N extends R{setupProperties(){super.setupProperties(),this.name=""}}class V extends R{setupProperties(){super.setupProperties(),this.name="",this.price=0,this.depositType="disabled",this.depositAmount=0,this.duration=0,this.bufferTimeBefore=0,this.bufferTimeAfter=0,this.timeBeforeBooking="",this.maxAdvanceTimeBeforeReservation="",this.minCapacity=1,this.maxCapacity=1,this.multiplyPrice=!1,this.isGroupServiceEnabled=!1,this.customQuantityLabel="",this.variations={},this.image="",this.thumbnail=""}getName(){return this.name}getPrice(e=0,t=0){t||(t=this.minCapacity);let s=this.getVariation("price",e,this.price);return this.multiplyPrice&&(s*=t),s}getDuration(e=0){return this.getVariation("duration",e,this.duration)}getMinCapacity(e=0){return this.getVariation("min_capacity",e,this.minCapacity)}getMaxCapacity(e=0){return this.getVariation("max_capacity",e,this.maxCapacity)}getVariation(e,t,s){return t in this.variations?this.variations[t][e]:s}setName(e){this.name=e}isGroupService(){return this.isGroupServiceEnabled}getCustomQuantityLabel(){return this.customQuantityLabel}getQuantityLabel(){return""!==this.customQuantityLabel?this.getCustomQuantityLabel():u("Clients","motopress-appointment")}}class q{static loadInBackground(e,t,s=!1){return t.findById(e.id,s).then((t=>{if(null!==t)for(let s in t)e[s]=t[s];return t}))}}class U extends R{setupProperties(){super.setupProperties(),this.status="new",this.code="",this.description="",this.type="fixed",this.amount=0,this.expirationDate=null,this.serviceIds=[],this.minDate=null,this.maxDate=null,this.usageLimit=0,this.usageCount=0}setupValues(e){for(let t of["expirationDate","minDate","maxDate"]){let s=e[t];null!=s&&""!==s&&(this[t]=b(s)),delete e[t]}super.setupValues(e)}getCode(){return this.code}isApplicableForCart(e){let t=!1;return e.items.forEach((e=>{if(this.isApplicableForCartItem(e))return t=!0,!1})),t}isApplicableForCartItem(e){return!!e.isSet()&&(!(this.serviceIds.length>0&&-1==this.serviceIds.indexOf(e.service.id))&&(!(null!=this.minDate&&e.date<this.minDate)&&!(null!=this.maxDate&&e.date>this.maxDate)))}calcDiscountAmount(e){let t=this.calcDiscountForCart(e);return Math.min(t,e.getSubtotalPrice())}calcDiscountForCart(e){let t=0;return e.items.forEach((e=>{t+=this.calcDiscountForCartItem(e)})),t}calcDiscountForCartItem(e){let t=0;if(this.isApplicableForCartItem(e)){let s=e.getPrice();switch(this.type){case"fixed":t=this.amount;break;case"percentage":t=s*this.amount/100}t=Math.min(t,s)}return t}}function H(e){return!!e}function j(e){let t=parseInt(e);return isNaN(t)?e<<0:t}class W{constructor(e){var t;this.postType=e,this.entityType=0===(t=e).indexOf("mpa_")?t.substring(4):0===t.indexOf("_mpa_")?t.substring(5):t,this.savedEntities={}}findById(e,t=!1){return e?!t&&this.haveEntity(e)&&null!=this.getEntity(e)?Promise.resolve(this.getEntity(e)):this.requestEntity(e).then((t=>{let s=this.mapRestDataToEntity(t);return this.saveEntity(e,s),s}),(t=>(this.saveEntity(e,null),null))):Promise.resolve(null)}findAll(e,t=!1){let s=[],i=[];for(let a of e)this.haveEntity(a)&&!t?i.push(this.getEntity(a)):s.push(a);return 0===s.length?Promise.resolve(i):this.requestEntities(s).then((e=>{for(let t of e){let e=this.mapRestDataToEntity(t);this.saveEntity(e.id,e),i.push(e)}return i}),(e=>[]))}requestEntity(e){return h(this.getRoute(),{id:e})}requestEntities(e){return h(this.getRoute(),{id:e})}haveEntity(e){return e in this.savedEntities}getEntity(e){return this.savedEntities[e]||null}saveEntity(e,t){this.savedEntities[e]=t}mapRestDataToEntity(e){return null}getRoute(){return`/${this.entityType}s`}}class G extends W{findByCode(e,t=!1){return h(this.getRoute(),{code:e}).then((e=>{let t=this.mapRestDataToEntity(e);return this.saveEntity(t.getId(),t),t}),(e=>{if(t)return null;throw e}))}mapRestDataToEntity(e){return new U(e.id,e)}}function z(e,t="public"){return f(e,"internal"==t?"H:i":"public"==t?m().settings().getTimeFormat():t)}function Q(e){let t=e.split(":"),s=parseInt(t[0]),i=parseInt(t[1]),a=v();return a.setHours(s,i),a}class Y{constructor(e,t=null){this.setupProperties(),null==t?this.parsePeriod(e):(this.setStartTime(e),this.setEndTime(t))}setupProperties(){this.startTime=null,this.endTime=null}parsePeriod(e){let t=e.split(" - ");this.setStartTime(t[0]),this.setEndTime(t[1])}setStartTime(e){this.startTime="string"==typeof e?Q(e):new Date(e)}setEndTime(e){this.endTime="string"==typeof e?Q(e):new Date(e),0===this.endTime.getHours()&&0===this.endTime.getMinutes()&&this.startTime.getFullYear()===this.endTime.getFullYear()&&this.startTime.getMonth()===this.endTime.getMonth()&&this.startTime.getDate()===this.endTime.getDate()&&this.endTime.setDate(this.endTime.getDate()+1)}setDate(e){this.startTime.setFullYear(e.getFullYear()),this.startTime.setMonth(e.getMonth(),e.getDate()),this.endTime.setFullYear(e.getFullYear()),this.endTime.setMonth(e.getMonth(),e.getDate()),0===this.endTime.getHours()&&0===this.endTime.getMinutes()&&this.startTime.getFullYear()===this.endTime.getFullYear()&&this.startTime.getMonth()===this.endTime.getMonth()&&this.startTime.getDate()===this.endTime.getDate()&&this.endTime.setDate(this.endTime.getDate()+1)}intersectsWith(e){return this.startTime<e.endTime&&this.endTime>e.startTime}isSubperiodOf(e){return this.startTime>=e.startTime&&this.endTime<=e.endTime}mergePeriod(e){this.startTime.setTime(Math.min(this.startTime.getTime(),e.startTime.getTime())),this.endTime.setTime(Math.max(this.endTime.getTime(),e.endTime.getTime()))}diffPeriod(e){this.startTime<e.startTime?this.endTime.setTime(Math.min(e.startTime.getTime(),this.endTime.getTime())):this.startTime.setTime(Math.max(e.endTime.getTime(),this.startTime.getTime()))}splitByPeriod(e){let t=[];return e.startTime.getTime()-this.startTime.getTime()>0&&t.push(new Y(this.startTime,e.startTime)),this.endTime.getTime()-e.endTime.getTime()>0&&t.push(new Y(e.endTime,this.endTime)),t}isEmpty(){return this.endTime.getTime()-this.startTime.getTime()<=0}toString(e="public",t=" - "){"internal"==e&&(t=" - ");let s="short"==e?"public":e,i=z(this.startTime,s),a=z(this.endTime,s);return"internal"!==e&&0===this.startTime.getHours()&&0===this.startTime.getMinutes()&&i===a?u("All day","motopress-appointment"):"short"==e&&i==a?i:i+t+a}}class K extends R{setupProperties(){super.setupProperties(),this.serviceId=0,this.date=null,this.serviceTime=null,this.bufferTime=null}setupValues(e){for(let t in e)"date"==t?this.setDate(e[t]):"serviceTime"==t?this.setServiceTime(e[t]):"bufferTime"==t?this.setBufferTime(e[t]):this[t]=e[t]}setDate(e){this.date="string"==typeof e?b(e):e,null!=this.serviceTime&&this.serviceTime.setDate(this.date),null!=this.bufferTime&&this.bufferTime.setDate(this.date)}setServiceTime(e){this.serviceTime="string"==typeof e?new Y(e):e,null!=this.date&&this.serviceTime.setDate(this.date)}setBufferTime(e){this.bufferTime="string"==typeof e?new Y(e):e,null!=this.date&&this.bufferTime.setDate(this.date)}}class Z extends W{findAllByService(e,t={}){let s={service_id:e};return null!=t.from_date&&(s.from_date=f(t.from_date,"internal")),null!=t.to_date&&(s.to_date=f(t.to_date,"internal")),h("/bookings/reservations",s).then((e=>{let t=[];for(let s of e){let e=this.mapRestDataToEntity(s);this.saveEntity(e.id,e),t.push(e)}return t})).catch((e=>(console.error("No reservations found.",e.message),[])))}mapRestDataToEntity(e){return new K(e.id,e)}}class J{constructor(e,t=null){this.setupProperties(),null==t?this.parsePeriod(e):(this.setStartDate(e),this.setEndDate(t))}setupProperties(){this.startDate=null,this.endDate=null}parsePeriod(e){let t=e.split(" - ");this.setStartDate(t[0]),this.setEndDate(t[1])}setStartDate(e){this.startDate=this.convertToDate(e)}setEndDate(e){this.endDate=this.convertToDate(e)}convertToDate(e){return"string"==typeof e?b(e)||v():new Date(e)}calcDays(){let e=this.endDate.getTime()-this.startDate.getTime();return Math.round(e/1e3/3600/24)}inPeriod(e){return"string"==typeof e&&(e=b(e)),null!=e&&e>=this.startDate&&e<=this.endDate}splitToDates(){let e={};for(let t=new Date(this.startDate);t<=this.endDate;t.setDate(t.getDate()+1)){let s=f(t,"internal"),i=new Date(t);e[s]=i}return e}toString(){return f(this.startDate,"internal")+" - "+f(this.endDate,"internal")}}class X extends R{setupProperties(){super.setupProperties(),this.timetable=[],this.workTimetable=[],this.customWorkdays=[],this.daysOff={}}setupValues(e){for(let t in e)"timetable"==t?this.setTimetable(e[t]):"customWorkdays"==t?this.setCustomWorkdays(e[t]):"daysOff"==t?this.setDaysOff(e[t]):this[t]=e[t]}setTimetable(e){this.timetable=[],this.workTimetable=[],e.forEach((e=>{let t=[],s=[];e.forEach((e=>{let i=new Y(e.time_period);t.push({time_period:i,location:e.location,activity:e.activity}),"work"==e.activity&&s.push({time_period:i,location:e.location})})),this.timetable.push(t),this.workTimetable.push(s)}))}setCustomWorkdays(e){this.customWorkdays=[];for(let t of e)this.customWorkdays.push({date_period:new J(t.date_period),time_period:new Y(t.time_period)})}setDaysOff(e){this.daysOff={};for(let t of e){let e=new J(t).splitToDates();jQuery.extend(this.daysOff,e)}}isDayOff(e){return"string"!=typeof e&&(e=f(e,"internal")),e in this.daysOff}getWorkingHours(e,t=0){if(this.isDayOff(e))return[];if("string"==typeof e&&(e=b(e)),null==e)return[];let s=[],i=e.getDay();for(let e of this.workTimetable[i])0!=t&&e.location!=t||s.push(e.time_period);for(let t of this.customWorkdays)t.date_period.inPeriod(e)&&s.push(t.time_period);return s}}class ee extends W{mapRestDataToEntity(e){return new X(e.id,e)}}class te extends W{mapRestDataToEntity(e){return new V(e.id,e)}}class se{constructor(){this.repositories={}}schedule(){return null==this.repositories.schedule&&(this.repositories.schedule=new ee("mpa_schedule")),this.repositories.schedule}service(){return null==this.repositories.service&&(this.repositories.service=new te("mpa_service")),this.repositories.service}reservation(){return null==this.repositories.reservation&&(this.repositories.reservation=new Z("mpa_reservation")),this.repositories.reservation}coupon(){return null==this.repositories.coupon&&(this.repositories.coupon=new G("mpa_coupon")),this.repositories.coupon}customer(){return void 0===this.repositories.customer&&(this.repositories.customer=new CustomerRepository),this.repositories.customer}static getInstance(){return null==se.instance&&(se.instance=new se),se.instance}}function ie(){return se.getInstance()}let ae=null;function re(e){return H(e)}class ne{setupProperties(){this.availability={},this.services={},this.serviceCategories={},this.employees={},this.locations={},this.servicePromise=null,this.readyPromise=null}constructor(){this.setupProperties()}load(e=!1){return this.readyPromise=function(e=!1){return(e||null==ae)&&(ae=h("/services/available").catch((e=>(console.error("Unable to extract available services."),{})))),ae}(e).then((e=>(this.setAvailability(e),this))),this.readyPromise}setAvailability(e){this.availability=e;for(let t in e){let s=e[t];this.services[t]=s.name;for(let e in s.categories){let t=s.categories[e];this.serviceCategories[e]=t}for(let e in s.employees){let t=s.employees[e];this.employees[e]=t.name;for(let e in t.locations){let s=t.locations[e];this.locations[e]=s}}}}isEmpty(){return B(this.availability)}ready(){return null===this.readyPromise&&this.load(),this.readyPromise}getServicePromise(){return this.servicePromise}getService(e,t=!0,s=null){let i=new V(e);return this.services.hasOwnProperty(e)&&i.setName(this.services[e]),!0===t?(this.servicePromise=q.loadInBackground(i,ie().service()),null!==s&&this.servicePromise.then(s),this.servicePromise.then((()=>i))):this.servicePromise=null,i}getServiceCategories(e){return this.availability[e].categories}getEmployee(e){let t=new O(e);return this.employees.hasOwnProperty(e)&&(t.name=this.employees[e]),t}getLocation(e){let t=new N(e);return this.locations.hasOwnProperty(e)&&(t.name=this.locations[e]),t}getAvailableServices(e="",t=0,s=0){let i={};for(let a in this.availability){let r=this.availability[a];if(""===e||e in r.categories){if(0!==t){let e=!1;if(Object.keys(r.employees).forEach((s=>{r.employees[s].locations.hasOwnProperty(t)&&(e=!0)})),!e)continue}(0===s||s in r.employees)&&(i[a]=r.name)}}return i}getAvailableServiceCategories(){let e={};for(let t in this.availability){let s=this.availability[t];jQuery.extend(e,s.categories)}return e}getAvailableEmployees(e=0,t=0){let s={};for(let i in this.availability){if(0!=e&&i!=e)continue;let a=this.availability[i];for(let e in a.employees){let i=a.employees[e];(0===t||t in i.locations)&&(s[e]=i.name)}}return s}getAvailableLocations(e=0,t=0){let s={};for(let i in this.availability){if(0!=e&&i!=e)continue;let a=this.availability[i];for(let e in a.employees){if(0!=t&&e!=t)continue;let i=a.employees[e];jQuery.extend(s,i.locations)}}return s}isAvailableServiceCategory(e){return this.getAvailableServiceCategories().hasOwnProperty(e)}isAvailableService(e){return this.getAvailableServices().hasOwnProperty(e)}isAvailableLocation(e){return this.getAvailableLocations().hasOwnProperty(e)}isAvailableEmployee(e){return this.getAvailableEmployees().hasOwnProperty(e)}filterAvailableEmployees(e,t=0,s="ids"){if(!(e in this.availability))return[];let i=[];Array.isArray(t)?i=t.filter(re):0!==t&&i.push(t);let r=[];for(let t in this.availability[e].employees){t=j(t);let s=this.availability[e].employees[t];if(0===i.length)r.push(t);else{a(i,Object.keys(s.locations).map(j)).length>0&&r.push(t)}}return 0===r.length?[]:"entities"===s?r.map((e=>this.getEmployee(e))):r}filterAvailableLocations(e,t=0,s="ids"){if(!(e in this.availability))return[];let a=[];Array.isArray(t)?a=t.filter(re):0!==t&&a.push(t);let r=[];for(t in this.availability[e].employees){if(t=j(t),a.length>0&&-1===a.indexOf(t))continue;let s=this.availability[e].employees[t];for(let e in s.locations)r.push(j(e))}return r=i(r),0===r.length?[]:"entities"===s?r.map((e=>this.getLocation(e))):r}}class oe{constructor(e){this.cart=e,this.steps=new M,this.currentStep=null,this.currentStepId=""}addStep(e){return this.steps.push(e.stepId,e),this}getStep(e){return this.steps.find(e)}mount(e){this.addListeners(e)}addListeners(e){e.children(".mpa-booking-step").on("mpa_booking_step_next",((e,t)=>this.onStep("next",t))).on("mpa_booking_step_back",((e,t)=>this.onStep("back",t))).on("mpa_booking_step_new",((e,t)=>this.onStep("new",t))).on("mpa_reset_booking",((e,t)=>this.onStep("reset",t)))}onStep(e,t){if(!t||!t.step||t.step===this.currentStepId)switch(e){case"next":this.goToNextStep();break;case"back":this.goToPreviousStep();break;case"new":this.goToFirstStep();break;case"reset":this.reset()}}goToNextStep(){if(this.steps.isEmpty())return;let e=this.currentStep?this.steps.findNextKey(this.currentStepId):this.steps.firstKey();e!==this.currentStepId&&(this.switchStep(e),this.skipNextHiddenSteps())}skipNextHiddenSteps(){null!==this.currentStep&&this.currentStep.ready().finally((()=>{this.currentStep.isHiddenStep&&this.currentStep.submit()}))}goToPreviousStep(){if(this.steps.isEmpty())return;let e=this.currentStep?this.steps.findPreviousKey(this.currentStepId):"";e&&e!==this.currentStepId&&(this.switchStep(e),this.skipPreviousHiddenSteps())}skipPreviousHiddenSteps(){null!==this.currentStep&&this.currentStep.ready().finally((()=>{this.currentStep.isHiddenStep&&this.currentStep.cancel()}))}goToFirstStep(){if(this.steps.isEmpty())return;this.cart.createItem(),this.steps.forEach((e=>{"cart item"===e.getCartContext()&&e.reset()}));let e=this.steps.firstKey();this.switchStep(e),this.skipNextHiddenSteps()}goToStep(e){this.switchStep(e)}getFirstVisibleStepId(){let e=null;return this.steps.forEach((t=>{if(!1===t.isHiddenStep)return e=t.stepId,!1})),e}isFirstVisibleStepId(e){return this.getFirstVisibleStepId()===e}switchStep(e){let t=this.steps.find(e);null!=t&&(this.isFirstVisibleStepId(e)&&t.hideButtonBack(),null!=this.currentStep&&this.currentStep.hide(),this.currentStep=t,this.currentStepId=e,t.load(),t.ready().finally((()=>t.show())))}reset(){this.cart.reset(),this.goToFirstStep(),this.steps.forEach((e=>{"cart item"!==e.getCartContext()&&e.reset()}))}}class le{constructor(e,t){this.$element=e,this.cart=t,this.setupProperties(),this.addListeners()}setupProperties(){this.stepId=this.theId(),this.schema=this.propertiesSchema(),this.isActive=!1,this.isLoaded=!1,this.isHiddenStep=!1,this.preventReact=!1,this.preventUpdate=!1,this.hideButtons=!1,this.readyPromise=null,this.$buttons=this.$element.find(".mpa-actions"),this.$buttonBack=this.$buttons.find(".mpa-button-back"),this.$buttonNext=this.$buttons.find(".mpa-button-next")}theId(){return"abstract"}getCartContext(){return"cart"}propertiesSchema(){return{}}addListeners(){this.$buttonBack.on("click",this.cancel.bind(this)),this.$buttonNext.on("click",this.submit.bind(this))}load(){this.isLoaded?this.readyPromise=this.reload():(this.readyPromise=this.loadEntities(),this.isLoaded=!0)}loadEntities(){return Promise.resolve(this)}reload(){return Promise.resolve(this)}reset(){}ready(){return this.readyPromise}isValidInput(){return!1}setProperty(e,t){if(this.preventUpdate)return;let s=this.validateProperty(e,t);if(s===this[e])return;let i=this.preventReact;this.preventReact=!0,this.updateProperty(e,s),i||(this.isActive&&this.react(),this.preventReact=!1)}resetProperty(e){this.setProperty(e)}validateProperty(e,t){let s=t;if(e in this.schema){let i=this.schema[e];if(null==t)s=i.default;else{switch(i.type){case"bool":s=H(t);break;case"integer":s=j(t)}if(!B(s)&&null!=i.options){i.options.indexOf(s)>=0||(s=this[e])}}}else null==t&&(s=null);return s}updateProperty(e,t){let s=this[e];this[e]=t,this.afterUpdate(e,t,s)}afterUpdate(e,t,s){}react(){let e=this.isValidInput();this.$buttonNext.prop("disabled",!e),this.hideButtons&&this.$buttons.toggleClass("mpa-hide",!e)}show(){this.enable(),this.react(),this.$element.removeClass("mpa-hide"),this.readyPromise.finally((()=>this.showReady()))}showReady(){this.$element.addClass("mpa-loaded"),this.hideButtons||this.$buttons.removeClass("mpa-hide")}hide(){this.disable(),this.$element.addClass("mpa-hide")}enable(){this.isActive=!0,this.$buttonBack.prop("disabled",!1),this.$buttonNext.prop("disabled",!1)}disable(){this.isActive=!1,this.$buttonBack.prop("disabled",!0),this.$buttonNext.prop("disabled",!0)}cancel(e){void 0!==e&&e.stopPropagation(),this.isActive&&(this.disable(),this.triggerBack())}submit(e){if(void 0!==e&&e.stopPropagation(),!this.isActive||!this.isValidInput())return;this.disable();let t=this.maybeSubmit();null==t?this.triggerNext():"object"!=typeof t?t?this.triggerNext():this.cancelSubmission():t.then(this.triggerNext.bind(this),this.cancelSubmission.bind(this))}maybeSubmit(){}cancelSubmission(){this.enable(),this.react()}triggerBack(){this.$element.trigger("mpa_booking_step_back",{step:this.stepId})}triggerNext(){this.$element.trigger("mpa_booking_step_next",{step:this.stepId})}hideButtonBack(){this.$buttonBack.prop("disabled",!0),this.$buttonBack.toggleClass("mpa-hide",!0)}}class he{static calculateTimezoneOffset(e){if("UTC"===e)return 0;const[t,s]=e.split(":").map(Number);if(isNaN(t)||isNaN(s))throw new Error("Unknown timezone format: "+e);return 60*t+s}static applyTimezoneOffset(e,t){const s=new Date(e);return s.setMinutes(e.getMinutes()-t),s}static isTimezoneProvideByIANA(e){return/^[A-Za-z]+\/[A-Za-z_]+(\/[A-Za-z_]+)?$/.test(e)}static formatDateToCalendar(e){return e.toISOString().replace(/-|:|\.\d{3}/g,"")}static formatDateToCalendarLocal(e){return e.toISOString().replace(/-|:|\.\d{3}|Z/g,"")}static formatDateForOffsetTimeZone(e,t){const s=(new Date).getTimezoneOffset();let i=this.applyTimezoneOffset(e,s);const a=this.calculateTimezoneOffset(t);return i=this.applyTimezoneOffset(i,a),this.formatDateToCalendar(i)}static formatDateForIANATimeZone(e){const t=(new Date).getTimezoneOffset();let s=this.applyTimezoneOffset(e,t);return this.formatDateToCalendarLocal(s)}static formatDateForCalendar(e,t){return this.isTimezoneProvideByIANA(t)?this.formatDateForIANATimeZone(e):this.formatDateForOffsetTimeZone(e,t)}static createICSURL(e,t,s,i,a,r){const n=m().settings().getTimezone();let o=this.formatDateForCalendar(t,n),l=this.formatDateForCalendar(s,n);0===t.getHours()&&0===t.getMinutes()&&0===s.getHours()&&0===s.getMinutes()&&(o=o.replace(/T\d\d\d\d\d\d|Z/g,""),l=l.replace(/T\d\d\d\d\d\d|Z/g,""));const h=["BEGIN:VCALENDAR","VERSION:2.0",`PRODID:${m().settings().getBusinessName()}`];this.isTimezoneProvideByIANA(n)&&h.push("BEGIN:VTIMEZONE","TZID:"+n,"END:VTIMEZONE"),h.push("BEGIN:VEVENT","DTSTAMP:"+this.formatDateToCalendar(new Date),"UID:"+e,"DTSTART"+(this.isTimezoneProvideByIANA(n)?";TZID="+n+":":":")+o,"DTEND"+(this.isTimezoneProvideByIANA(n)?";TZID="+n+":":":")+l,"SUMMARY:"+i,"DESCRIPTION:"+a,"LOCATION:"+r,"END:VEVENT"),h.push("END:VCALENDAR");const c=h.join("\n"),p=new Blob([c],{type:"text/calendar"});return window.URL.createObjectURL(p)}static createGoogleCalendarURL(e,t,s,i,a){const r=new URL("https://www.google.com/calendar/render"),n=m().settings().getTimezone();let o=this.formatDateForCalendar(e,n),l=this.formatDateForCalendar(t,n);return 0===e.getHours()&&0===e.getMinutes()&&0===t.getHours()&&0===t.getMinutes()&&(o=o.replace(/T\d\d\d\d\d\d|Z/g,""),l=l.replace(/T\d\d\d\d\d\d|Z/g,"")),r.search=new URLSearchParams({action:"TEMPLATE",text:s,dates:`${o}/${l}`,details:i,location:a}).toString(),this.isTimezoneProvideByIANA(n)&&r.searchParams.append("ctz",n),r.toString()}static createYahooCalendarURL(e,t,s,i,a){const r=new URL("https://calendar.yahoo.com/"),n=m().settings().getTimezone();let o=this.formatDateForCalendar(e,n),l=this.formatDateForCalendar(t,n),h={v:"60",view:"d",type:"20",title:s,desc:i,in_loc:a};return 0===e.getHours()&&0===e.getMinutes()&&0===t.getHours()&&0===t.getMinutes()?(h.st=o.replace(/T\d\d\d\d\d\d|Z/g,""),h.dur="allday"):(h.st=o,h.et=l),r.search=new URLSearchParams(h).toString(),r.toString()}}class ce{constructor(e,t){this.cart=t,this.$bookingDetailsSection=e,this.$bookingCartItems=this.$bookingDetailsSection.find(".booking-reservations"),this.$bookingCartItem=this.$bookingCartItems.find(".reservation"),this.$addToCalendarGoogle=this.$bookingCartItem.find(".mpa-add-to-calendar-link--google"),this.$addToCalendarApple=this.$bookingCartItem.find(".mpa-add-to-calendar-link--apple"),this.$addToCalendarOutlook=this.$bookingCartItem.find(".mpa-add-to-calendar-link--outlook"),this.$addToCalendarYahoo=this.$bookingCartItem.find(".mpa-add-to-calendar-link--yahoo")}assignURL(e,t){e.attr("href",t)}initBookingCart(){this.$bookingCartItems.empty(),wp.hooks.doAction("mpa_booking_details_section_init",this.$bookingDetailsSection,this.cart),this.cart.items.forEach((e=>{let t=this.$bookingCartItem.clone();this.$bookingCartItems.append(t);const s=e.getService(),i=s.getName(),a=e.employee.name+". "+s.getQuantityLabel()+": "+e.getCapacity()+".";let r=i;e.getCapacity()>1&&(r+=" ",r+='<span class="mpa-reservation-capacity">',r+=s.getQuantityLabel()+": "+e.getCapacity(),r+="</span>"),t.find(".reservation-title").html(r),t.find(".reservation-date").html(f(e.date)),t.find(".reservation-time").html(e.time.toString());const n=he.createICSURL(e.getItemId(),e.time.startTime,e.time.endTime,i,a,e.location.name),o=he.createGoogleCalendarURL(e.time.startTime,e.time.endTime,i,a,e.location.name),l=he.createYahooCalendarURL(e.time.startTime,e.time.endTime,i,a,e.location.name);this.assignURL(t.find(".mpa-add-to-calendar-link--google"),o),this.assignURL(t.find(".mpa-add-to-calendar-link--apple"),n),this.assignURL(t.find(".mpa-add-to-calendar-link--outlook"),n),this.assignURL(t.find(".mpa-add-to-calendar-link--yahoo"),l)})),this.$bookingDetailsSection.toggleClass("mpa-hide",!1)}reset(){this.$bookingDetailsSection.toggleClass("mpa-hide",!0);const e="#";this.assignURL(this.$addToCalendarGoogle,e),this.assignURL(this.$addToCalendarApple,e),this.assignURL(this.$addToCalendarOutlook,e),this.assignURL(this.$addToCalendarYahoo,e)}}class pe extends le{setupProperties(){super.setupProperties(),this.hideButtons=!0,this.isPosted=!1,this.isBooked=!1,this.$message=this.$element.find(".mpa-message").first(),this.$buttonReset=this.$buttons.find(".mpa-button-reset"),this.$bookingDetails=this.$element.find(".mpa-booking-details").first(),this.$bookingDetails.length>0&&(this.bookingDetails=new ce(this.$bookingDetails,this.cart))}reload(){return this.isPosted=!1,this.isBooked=!1,this.setMessage(u("Making a reservation...","motopress-appointment")+' <span class="mpa-preloader"></span>'),this.bookingDetails&&this.bookingDetails.reset(),Promise.resolve(this)}addListeners(){super.addListeners(),this.$buttonReset.on("click",this.resetForm.bind(this))}theId(){return"booking"}react(){this.isPosted&&(this.$buttons.removeClass("mpa-hide"),this.$buttonBack.toggleClass("mpa-hide",this.isBooked),this.$buttonReset.toggleClass("mpa-hide",!this.isBooked||this.isRedirectNeeded()))}show(){super.show(),this.createBooking()}createBooking(){c("/bookings",wp.hooks.applyFilters("mpa_booking_cart_data",this.cart.toArray())).then((e=>{this.isRedirectNeeded()?this.redirectPayment():(this.isPosted=this.isBooked=!0,this.cart.paymentDetails.booking_id=e.booking_id,this.setMessage(e.message),this.bookingDetails&&this.bookingDetails.initBookingCart(),this.react())}),(e=>{this.isPosted=!0,this.setMessage(e.message),this.react()}))}showReady(){super.showReady(),this.$buttonBack.addClass("mpa-hide"),this.$buttonReset.addClass("mpa-hide")}setMessage(e){this.$message.html(e)}redirectPayment(){this.setMessage(u("You will be redirected to a secure page to complete the payment.","motopress-appointment"));let e=this.cart.getPaymentDetails();window.location.href=e.redirect_url}isRedirectNeeded(){let e=this.cart.getPaymentDetails();return"redirect_url"in e&&""!=e.redirect_url}resetForm(e){e.preventDefault(),this.isPosted&&this.isBooked&&this.$element.trigger("mpa_reset_booking")}}function de(e){let t="";for(let s in e)t+=" "+s+'="'+e[s]+'"';return t}function me(e,t={}){return"<button"+de(t=jQuery.extend({},{type:"button",class:"button"},t))+">"+e+"</button>"}function ue(e,t){let s={service_id:".mpa-service-id",service_name:".mpa-service-name",service_thumbnail:".mpa-service-thumbnail",employee_id:".mpa-employee-id",employee_name:".mpa-employee-name",location_id:".mpa-location-id",location_name:".mpa-location-name",reservation_date:".mpa-reservation-date",reservation_save_date:".mpa-reservation-save-date",reservation_time:".mpa-reservation-time",reservation_period:".mpa-reservation-period",reservation_save_period:".mpa-reservation-save-period",reservation_capacity:".mpa-reservation-capacity",reservation_clients:".mpa-reservation-clients",reservation_clients_count:".mpa-reservation-clients-count",reservation_price:".mpa-reservation-price"},i=t.clone();i.attr("data-id",e.getItemId());let a=e.getCapacityOptions();for(let t in s){let n=s[t],o=i.find(n).first(),l="{"+t+"}";if(!(o.length>0?o.html():"").includes(l))continue;let h="";switch(t){case"service_id":h=e.service.id;break;case"service_name":h=e.service.name;break;case"service_thumbnail":h=Pe(e.service.thumbnail);break;case"employee_id":h=e.employee.id;break;case"employee_name":h=e.employee.name;break;case"location_id":h=e.location.id;break;case"location_name":h=e.location.name;break;case"reservation_date":h=f(e.date);break;case"reservation_save_date":h=f(e.date,"internal");break;case"reservation_time":h=e.time.toString("short");break;case"reservation_period":h=e.time.toString();break;case"reservation_save_period":h=e.time.toString("internal");break;case"reservation_capacity":h=be(r(a,a),e.capacity);break;case"reservation_clients":h=Se(r(a,a),e.capacity);break;case"reservation_clients_count":h=e.capacity;break;case"reservation_price":let t=e.employee.id;h=ye(e.service.getPrice(t,e.capacity))}o.html(o.html().replace(l,h))}return i.find(".cell-people .cell-title").html(e.getService().getQuantityLabel()),i.find('[name*="{item_id}"]').each(((t,s)=>{s.name=s.name.replace("{item_id}",e.getItemId())})),1===a.length&&i.find(".cell-people").addClass("mpa-hide"),i}function ge(e){let t="";t+='<table class="mpa-order widefat">',t+="<tbody>";for(let s of e.products)t+='<tr class="mpa-order-service">',t+='<td class="column-service">',t+='<span class="mpa-service-name">'+s.name+"</span>",s.capacity>1&&(t+='<span class="mpa-reservation-capacity">',t+=s.quantity_label+": "+s.capacity,t+="</span>"),t+="</td>",t+='<td class="column-price">'+fe(s.price)+"</td>",t+="</tr>";return t+='<tr class="mpa-order-subtotal">',t+='<th class="column-subtotal">'+u("Subtotal","motopress-appointment")+"</th>",t+='<th class="column-price">'+fe(e.subtotal)+"</th>",t+="</tr>",t+="</tbody>",t+="<tfoot>",e.coupon&&(t+='<tr class="mpa-order-coupon">',t+='<th class="column-coupon">',t+=u("Coupon: %s","motopress-appointment").replace("%s",e.coupon.code),t+="</th>",t+='<td class="column-price">',t+=fe(-e.coupon.amount),t+=" ",t+='<a href="#" class="mpa-remove-coupon">'+u("Remove","motopress-appointment")+"</a>",t+="</td>",t+="</tr>"),t+='<tr class="mpa-order-total">',t+='<th class="column-total">'+u("Total","motopress-appointment")+"</th>",t+='<th class="column-price">'+fe(e.total)+"</th>",t+="</tr>",t+="</tfoot>",t+="</table>",t}function ye(e,t={}){let s=m().settings();t=jQuery.extend({currency_symbol:s.getCurrencySymbol(),currency_position:s.getCurrencyPosition(),decimal_separator:s.getDecimalSeparator(),thousand_separator:s.getThousandSeparator(),decimals:s.getDecimalsCount(),literal_free:!0,trim_zeros:!0},t);let i=function(e,t=0,s=".",i=","){let a,r,n,o,l,h="";return e<0&&(h="-",e*=-1),a=parseInt(e=(+e||0).toFixed(t))+"",(r=a.length)>3?r%=3:r=0,l=r?a.substr(0,r)+i:"",n=a.substr(r).replace(/(\d{3})(?=\d)/g,"$1"+i),o=t?s+Math.abs(e-a).toFixed(t).replace(/-/,0).slice(2):"",h+l+n+o}(Math.abs(e),t.decimals,t.decimal_separator,t.thousand_separator),a="mpa-price";if(0==e&&(a+=" mpa-zero-price"),0==e&&t.literal_free)a+=" mpa-price-free",i=g("Free","Zero price","motopress-appointment");else{t.trim_zeros&&(i=function(e,t=null){null==t&&(t=m().settings().getDecimalSeparator());let s=new RegExp("\\"+t+"0+$");return e.replace(s,"")}(i));let s='<span class="mpa-currency">'+t.currency_symbol+"</span>";switch(t.currency_position){case"before":i=s+i;break;case"after":i+=s;break;case"before_with_space":i=s+"&nbsp;"+i;break;case"after_with_space":i=i+"&nbsp;"+s}e<0&&(i="-"+i)}return'<span class="'+a+'">'+i+"</span>"}function fe(e,t={}){return t.literal_free=!1,ye(e,t)}function be(e,t,s={}){let i="<select"+de(s)+">";return i+=Se(e,t),i+="</select>",i}function ve(e,t,s=!1){let i="";return i='<option value="'+e+'"'+(s?' selected="selected"':"")+">",i+=t,i+="</option>",i}function Se(e,t){let s="";for(let i in e)s+=ve(i,e[i],i==t);return s}function _e(e,t,s,i){let a=Se(t,i)+Se(s,i);e.empty().append(a).val(i)}function Pe(e){let{width:t,height:s}=m().settings().getThumbnailSize();return"<img"+de({width:t,height:s,src:e,class:"attachment-thumbnail size-thumbnail"})+">"}class Ce extends le{setupProperties(){super.setupProperties(),this.isBeginCheckoutEventSent=!1,this.$cart=this.$element.find(".mpa-cart"),this.$items=this.$cart.find(".mpa-cart-items"),this.$itemTemplate=this.$cart.find(".mpa-cart-item-template"),this.$noItems=this.$element.find(".no-items"),this.$totalPrice=this.$element.find(".mpa-cart-total-price"),this.$buttonNew=this.$buttons.find(".mpa-button-new")}theId(){return"cart"}addListeners(){super.addListeners(),this.$buttonNew.on("click",this.createNew.bind(this))}load(){if(this.$itemTemplate.remove(),this.$itemTemplate.removeClass("mpa-cart-item-template"),null!==this.cart.getActiveItem()){let e=this.cart.getActiveItem(),t=e.getItemId(),s=e.getDate(),i=e.getTime();this.cart.getItems().forEach((a=>{a.isSet()&&a.getItemId()!=t&&a.isAtTime(s,i)&&a.removeBookingVariatForEmployee(e.getEmployeeId())}))}this.updateActiveItemCapacity(),this.refreshCart(),this.isLoaded=!0,this.readyPromise=Promise.resolve(this)}reset(){this.$items.find(".mpa-cart-item").remove(),this.$noItems.removeClass("mpa-hide"),this.isBeginCheckoutEventSent=!1}updateActiveItemCapacity(){let e=this.cart.getActiveItem();if(!e)return;let t=e.getMinCapacity(),s=e.getMaxCapacity();var i,a,r;e.setCapacity((i=e.getCapacity(),a=t,r=s,Math.max(a,Math.min(i,r))))}refreshCart(){this.cart.getActiveItemId(),this.cart.items.forEach(((e,t,s)=>{let i='.mpa-cart-item[data-id="'+s+'"]',a=this.$items.find(i);0===a.length?(a=this.addItem(e),this.bindListeners(a)):(a=this.updateItem(a,e),this.bindListeners(a))})),this.updateTotalPrice()}addItem(e){let t=ue(e,this.$itemTemplate);return this.$items.append(t),this.$noItems.addClass("mpa-hide"),t}updateItem(e,t){let s=ue(t,this.$itemTemplate);return e.replaceWith(s),s}bindListeners(e){let t=e.data("id"),s=this.cart.getItem(t),i=e.find(".mpa-reservation-capacity select, .mpa-reservation-clients select"),a=e.find(".mpa-reservation-price"),r=e.find(".mpa-button-remove, .mpa-button-edit-or-remove"),n=e.find(".mpa-button-edit, .mpa-button-edit-or-remove");i.on("change",(t=>{let i=j(t.target.value);s.setCapacity(i);let r=s.getBookingVariantForCapacity(i),n=r.employeeId,o=r.locationId;if(s.getEmployeeId()!=n)s.setEmployee(n,!1),s.setLocation(o,!1),e=this.updateItem(e,s),this.bindListeners(e);else{let e=s.service.getPrice(n,i);a.html(ye(e))}this.updateTotalPrice()})),this.isMultibookingEnabled()&&r.on("click",(s=>{s.stopPropagation(),e.remove();let i=this.cart.getItem(t);this.cart.removeItem(t),this.cart.isEmpty()&&this.$noItems.removeClass("mpa-hide"),this.updateTotalPrice(),this.react(),document.dispatchEvent(new CustomEvent("mpa_remove_from_cart",{detail:{cartItem:i,currencyCode:m().settings().getCurrency()}}))})),this.isMultibookingEnabled()||n.on("click",(()=>{this.cart.setActiveItem(t),this.cancel()}))}updateTotalPrice(){this.$totalPrice.html(fe(this.cart.getTotalPrice()))}isMultibookingEnabled(){return m().settings().isMultibookingEnabled()}isValidInput(){return!this.cart.isEmpty()}createNew(){this.isActive&&(this.disable(),this.triggerNew())}triggerNew(){this.$element.trigger("mpa_booking_step_new",{step:this.stepId})}maybeSubmit(){this.isBeginCheckoutEventSent||(document.dispatchEvent(new CustomEvent("mpa_begin_checkout",{detail:{cart:this.cart,currencyCode:m().settings().getCurrency()}})),this.isBeginCheckoutEventSent=!0)}}class we{constructor(e,t){this.cart=t,this.$element=e,this.$couponCode=e.find('[name="coupon_code"]'),this.$applyButton=e.find(".mpa-apply-coupon-button"),this.$messageHolder=e.find(".mpa-message-wrapper"),this.$preloader=e.find(".mpa-preloader"),this.$parentForm=e.parents(".mpa-booking-step").first(),this.addListeners(),this.reset()}addListeners(){this.$couponCode.on("keydown",(e=>{"Enter"===e.code&&this.onEnter(e)})),this.$applyButton.on("click",this.onSubmit.bind(this))}onEnter(e){e.preventDefault(),e.stopPropagation(),this.applyCouponCode(e.target.value)}onSubmit(e){e.preventDefault(),e.stopPropagation(),this.applyCouponCode(this.$couponCode.val())}applyCouponCode(e){this.clearMessage(),e?(this.pauseAll(),ie().coupon().findByCode(e).then((e=>{e.isApplicableForCart(this.cart)?(this.cart.setCoupon(e),this.reset(),this.triggerApplied(e),this.setMessage(u("Coupon code applied successfully.","motopress-appointment"))):this.setMessage(u("Sorry, your booking is not eligible for this coupon.","motopress-appointment")),this.unpauseAll()}),(e=>{this.setMessage(e.message),this.unpauseAll()}))):this.setMessage(u("Coupon code is empty.","motopress-appointment"))}reset(){this.$couponCode.val(""),this.clearMessage(),0===this.cart.getTotalPrice()?(this.disable(),this.$element.addClass("mpa-hide")):(this.enable(),this.$element.removeClass("mpa-hide"))}disable(){this.$couponCode.prop("disabled",!0),this.$applyButton.prop("disabled",!0)}enable(){this.$couponCode.prop("disabled",!1),this.$applyButton.prop("disabled",!1)}pauseAll(){this.disable(),this.showPreloader(),this.$parentForm.trigger("mpa_booking_step_disable")}unpauseAll(){this.enable(),this.hidePreloader(),this.$parentForm.trigger("mpa_booking_step_enable")}triggerApplied(e){this.$parentForm.trigger("mpa_booking_coupon_applied",{coupon:e})}setMessage(e){this.$messageHolder.html(e).removeClass("mpa-hide")}clearMessage(){this.$messageHolder.html("").addClass("mpa-hide")}showPreloader(){this.$preloader.removeClass("mpa-hide")}hidePreloader(){this.$preloader.addClass("mpa-hide")}}function $e(e){const i=jQuery("<span/>",{id:e.attr("id")+"_error",class:"mpa-phone-field-error mpa-hide",text:u("Phone number is invalid.","motopress-appointment")});e.after("<br>",i);const a=s(e[0],{separateDialCode:!0,initialCountry:t.settings.country,hiddenInput:e.attr("name"),utilsScript:t.urls.plugin+"assets/js/intl-tel-input-17.0.19/js/utils.js"});a.promise.then((()=>{e.val()&&r(),e.on("countrychange",(e=>{r()})),e.on("input",(e=>{r()}))}));const r=()=>{a.isValidNumber()?(jQuery("input[type='hidden'][name='"+e.attr("name")+"']").val(a.getNumber(intlTelInputUtils.numberFormat.E164)),e.removeClass("mpa-phone-number--invalid"),i.addClass("mpa-hide")):(e.addClass("mpa-phone-number--invalid"),i.removeClass("mpa-hide"))};return a}window.mpa_intl_tel_input=$e;class ke extends le{setupProperties(){super.setupProperties(),this.name="",this.email="",this.phone="",this.notes="",this.acceptTerms=!1,this.createAccount=!1,this.$checkoutForm=this.$element.find(".mpa-checkout-form"),this.$name=this.$element.find(".mpa-customer-name"),this.$email=this.$element.find(".mpa-customer-email"),this.$phone=this.$element.find(".mpa-customer-phone"),this.$notes=this.$element.find(".mpa-customer-notes"),this.$order=this.$element.find(".mpa-order"),wp.hooks.doAction("mpa_step_checkout_form",this.$checkoutForm),0!==this.$phone.length&&(this.phoneValidator=$e(this.$phone)),m().settings().getTermsPageIdForAcceptance()&&(this.$acceptTerms=this.$element.find(".mpa-accept-terms")),this.$messageHolder=this.$element.find(".mpa-message").first(),this.$preloader=this.$element.find(".mpa-loading"),m().settings().isAllowCustomerAccountCreation()&&(this.$createAccount=this.$element.find(".mpa-customer-create-account"),this.$createAccountDescription=this.$element.find(".mpa-customer-create-account-description"),this.setProperty("createAccount",this.$createAccount.prop("checked"))),t&&t.currentCustomer&&t.currentCustomer.name&&(this.setProperty("name",t.currentCustomer.name),this.$name.val(t.currentCustomer.name)),t&&t.currentCustomer&&t.currentCustomer.email&&(this.setProperty("email",t.currentCustomer.email),this.$email.val(t.currentCustomer.email)),t&&t.currentCustomer&&"undefined"!==t.currentCustomer.phone&&(this.setProperty("phone",t.currentCustomer.phone),this.phoneValidator.setNumber(t.currentCustomer.phone),this.$phone.trigger("input")),this.service=null,this.couponSection=null}theId(){return"checkout"}propertiesSchema(){return{name:{type:"string",default:""},email:{type:"string",default:""},phone:{type:"string",default:""},notes:{type:"string",default:""},acceptTerms:{type:"bool",default:!1},$createAccount:{type:"bool",default:!1}}}addListeners(){super.addListeners(),this.$checkoutForm.on("submit",(e=>!1)),this.$name.on("input",(e=>this.setProperty("name",e.target.value))),this.$email.on("input",(e=>this.setProperty("email",e.target.value))),this.$phone.on("input",(e=>{this.setProperty("phone",""),this.phoneValidator.isValidNumber()&&this.setProperty("phone",this.phoneValidator.getNumber(intlTelInputUtils.numberFormat.E164))})),this.$phone.on("countrychange",(e=>{this.setProperty("phone",""),this.phoneValidator.isValidNumber()&&this.setProperty("phone",this.phoneValidator.getNumber(intlTelInputUtils.numberFormat.E164))})),this.$notes.on("input",(e=>this.setProperty("notes",e.target.value))),m().settings().getTermsPageIdForAcceptance()&&this.$acceptTerms.on("input",(e=>this.setProperty("acceptTerms",e.target.checked))),m().settings().isAllowCustomerAccountCreation()&&this.$createAccount.on("input",(e=>{this.setProperty("createAccount",e.target.checked),e.target.checked?this.$createAccountDescription.removeClass("mpa-hide"):this.$createAccountDescription.addClass("mpa-hide")})),this.$element.on("mpa_booking_step_disable",this.disable.bind(this)),this.$element.on("mpa_booking_step_enable",this.enable.bind(this)),this.$element.on("mpa_booking_coupon_applied",(()=>this.updateOrder()))}load(){this.couponSection?this.couponSection.reset():m().settings().isCouponsEnabled()&&(this.couponSection=new we(this.$element.find(".mpa-coupon-details"),this.cart)),this.cart.hasCoupon()&&this.cart.testCoupon(),this.updateOrder(),this.isLoaded=!0,this.readyPromise=Promise.resolve(this)}reset(){wp.hooks.doAction("mpa_step_checkout_reset",this.$checkoutForm),this.$notes.val(""),this.resetProperty("notes"),m().settings().getTermsPageIdForAcceptance()&&(this.$acceptTerms.prop("checked",!1),this.resetProperty("acceptTerms")),m().settings().isAllowCustomerAccountCreation()&&(this.clearMessage(),this.$createAccount.prop("checked",!1),this.resetProperty("createAccount")),this.couponSection&&this.couponSection.reset()}updateOrder(){if(0===this.$order.length)return;this.$order.empty(),this.$order.html(ge(this.cart.getOrder()));let e=this.$order.find(".mpa-remove-coupon");e.length>0&&e.on("click",this.removeCoupon.bind(this))}removeCoupon(e){e.preventDefault(),e.stopPropagation(),this.cart.removeCoupon(),this.couponSection.clearMessage(),this.updateOrder()}isValidInput(){return this.isValidName()&&this.isValidEmail()&&this.isValidPhone()&&this.isValidAcceptTerms()&&wp.hooks.applyFilters("mpa_step_checkout_form_valid",!0,this.$checkoutForm)}isValidName(){return!(this.$name.length>0&&this.$name.is("[required]"))||""!==this.name}isValidEmail(){return!(this.$email.length>0&&this.$email.is("[required]"))||""!==this.email&&!!this.email.match(/.+@.+/)}isValidPhone(){return!(this.$phone.length>0&&this.$phone.is("[required]"))||this.phoneValidator.isValidNumber()}isValidAcceptTerms(){return!m().settings().getTermsPageIdForAcceptance()||m().settings().isPaymentsEnabled()||this.acceptTerms}react(){super.react(),this.$buttonNext.prop("disabled",!1)}setMessage(e){this.$messageHolder.html(e).removeClass("mpa-hide")}clearMessage(){this.$messageHolder.html("").addClass("mpa-hide")}showPreloader(){this.$preloader.removeClass("mpa-hide")}hidePreloader(){this.$preloader.addClass("mpa-hide")}async maybeSubmit(){if(wp.hooks.hasFilter("mpa_step_checkout_maybe_submit")&&await wp.hooks.applyFilters("mpa_step_checkout_maybe_submit",{},this.$checkoutForm),this.couponSection&&this.couponSection.disable(),this.cart.setCustomerDetails({name:this.name,email:this.email,phone:this.phone,notes:this.notes,acceptTerms:this.acceptTerms}),this.createAccount&&""!==this.email){this.showPreloader();return c("/customers/create",{name:this.name,email:this.email,phone:this.phone}).then((e=>{this.hidePreloader(),this.clearMessage()}),(e=>{throw this.hidePreloader(),this.setMessage(e),e}))}}}class Te{setupProperties(){this.gatewayId="basic",this.settings=this.getDefaults(),this.$mountWrapper=null,this.loadPromise=null,this.isEnabled=!1,this.isMounted=!1,this.haveErrors=!1}constructor(e,t){this.setupProperties(),this.$mountWrapper=e,this.cart=t}load(){return this.addListeners(),this.loadPromise=Promise.resolve(this),this.loadPromise}addListeners(){}onCartChange(e){}mount(e){}ready(){return this.loadPromise}enable(){this.isEnabled||(this.isMounted||(this.mount(this.$mountWrapper),this.isMounted=!0),this.$mountWrapper.removeClass("mpa-hide"),this.isEnabled=!0)}disable(){this.isEnabled&&(this.$mountWrapper.addClass("mpa-hide"),this.isEnabled=!1)}isValid(){return!this.haveErrors}processPayment(e,t){return c("/payments/prepare",{payment_details:e.paymentDetails})}getDefaults(){return{country:m().settings().getCountry(),redirect_url:{payment_received:m().settings().getReservationReceivedPageUrl(),failed_transaction:m().settings().getFailedTransactionPageUrl()}}}reset(){}}class Ie extends Te{enable(){}}class De{setupProperties(){this.methods=null,this.uid="",this.paymentMethods=new M,this.selectedMethod="",this.$mountWrapper=null,this.$errorsWrapper=null,this.$gatewayPreloader=null,this.mountedMethods=[]}constructor(e){this.setupProperties(),this.methods=e,this.uid=F(),this.addPaymentMethods(this.methods)}mountedMethod(){let e=!1;Object.entries(this.mountedMethods).forEach(((t,s)=>{s||(e=!0)})),e&&this.$gatewayPreloader.addClass("mpa-hide")}addPaymentMethods(e){for(const t in e)this.paymentMethods.includesKey(t)||(this.paymentMethods.push(t,{$nav:null,$fields:null}),this.selectedMethod||(this.selectedMethod=t))}isMounted(){return null!==this.$mountWrapper}mount(e){e.append(this.render()),this.$gatewayPreloader=e.parent().find(".mpa-payment-gateway-title .mpa-preloader"),this.$gatewayPreloader.removeClass("mpa-hide"),this.paymentMethods.forEach(((t,s,i)=>{t.$nav=e.find(".mpa-stripe-payment-method."+i),t.$fields=e.find(".mpa-stripe-payment-fields."+i);const a=this.methods[i].getControl();if(null!==a){const e=this.getElementSelector(i);this.mountedMethods[i]=!1,a.mount(e),a.on("ready",(t=>{this.mountedMethod(t),document.querySelector(e).classList.remove("mpa-preloader-skeleton-pulsate")}))}"card"===i&&this.methods.card.isCanMakePaymentRequest().then((e=>{const t=this.getElementSelector("payment-request-button"),s=document.querySelector(t);s&&(e?(this.mountedMethods.payment_request_button=!1,this.methods.card.paymentRequestButton.mount(t),this.methods.card.paymentRequestButton.on("ready",(e=>{this.mountedMethod("payment_request_button"),s.classList.remove("mpa-preloader-skeleton-pulsate")}))):(s.classList.add("mpa-hide"),document.querySelector(".mpa-stripe-payment-request-button-separator").classList.add("mpa-hide")))}))})),e.find('input[name="stripe_payment_method"]').on("change",this.onPaymentMethodChange.bind(this)),this.$mountWrapper=e,this.$errorsWrapper=e.find(".mpa-errors")}onPaymentMethodChange(e){let t=null;switch(this.selectedMethod){case"payment":case"card":case"ideal":case"sepa_debit":t=this.methods[this.selectedMethod].getControl()}null!==t&&t.clear(),this.selectPaymentMethod(e.target.value)}selectPaymentMethod(e){e!==this.selectedMethod&&(this.togglePaymentMethod(this.selectedMethod,!1),this.togglePaymentMethod(e,!0),this.selectedMethod=e)}togglePaymentMethod(e,t){if(this.isMounted()&&this.paymentMethods.includesKey(e)){let s=this.paymentMethods.find(e);s.$nav.toggleClass("active",t),s.$fields.toggleClass("mpa-hide",!t)}}getElementSelector(e){return"sepa_debit"===e&&(e="iban"),"#mpa-stripe-"+e+"-element-"+this.uid}render(){let e="";e+='<section class="mpa-stripe-payment-container">',this.paymentMethods.length>1&&(e+=this.renderNavigation());for(let t of this.paymentMethods.keys)e+=this.renderFields(t);return e+='<div class="mpa-errors"></div>',e+="</section>",e}renderNavigation(){let e="";e+='<nav class="mpa-stripe-payment-methods">',e+="<ul>";for(let t of this.paymentMethods.keys){let s=t===this.selectedMethod;e+='<li class="mpa-stripe-payment-method '+t+(s?" active":"")+'">',e+="<label>",e+='<input type="radio" name="stripe_payment_method" value="'+t+'"'+(s?' checked="checked"':"")+">",e+=" "+this.methods[t].title,e+="</label>",e+="</li>"}return e+="</ul>",e+="</nav>",e}renderFields(e){let t="";switch(t+='<div class="mpa-stripe-payment-fields '+e+(e===this.selectedMethod?"":" mpa-hide")+'">',t+="<fieldset>",e){case"payment":t+=this.renderPaymentFields();break;case"card":t+=this.renderCardFields();break;case"ideal":t+=this.renderIdealFields();break;case"sepa_debit":t+=this.renderSepaDebitFields();break;default:t+=this.renderRedirectNotice()}return t+="</fieldset>","sepa_debit"===e&&(t+='<p class="notice">',t+=u("By providing your IBAN and confirming this payment, you authorise (A) %s and Stripe, our payment service provider, to send instructions to your bank to debit your account and (B) your bank to debit your account in accordance with those instructions. You are entitled to a refund from your bank under the terms and conditions of your agreement with your bank. A refund must be claimed within 8 weeks starting from the date on which your account was debited.","motopress-appointment").replace("%s",m().settings().getBusinessName()),t+="</p>"),t+="</div>",t}renderPaymentFields(){let e="";return e+='<div id="mpa-stripe-payment-element-'+this.uid+'" class="mpa-stripe-element mpa-stripe-payment-element"></div>',e}renderCardFields(){let e="";return e+='<label for="mpa-stripe-card-element-'+this.uid+'">',e+=u("Credit or debit card","motopress-appointment"),e+="</label>",this.methods.card.isEnabledWallets()&&(e+='<div id="mpa-stripe-payment-request-button-element-'+this.uid+'" class="mpa-stripe-element mpa-stripe-payment-request-button-element mpa-preloader-skeleton-pulsate StripeElement"></div>',e+='<div class="mpa-stripe-payment-request-button-separator">'+u("or","motopress-appointment")+"</div>"),e+='<div id="mpa-stripe-card-element-'+this.uid+'" class="mpa-stripe-element mpa-stripe-card-element mpa-preloader-skeleton-pulsate"></div>',e}renderIdealFields(){let e="";return e+='<label for="mpa-stripe-ideal-element-'+this.uid+'">',e+=u("Select iDEAL Bank","motopress-appointment"),e+="</label>",e+='<div id="mpa-stripe-ideal-element-'+this.uid+'" class="mpa-stripe-element mpa-stripe-ideal-element mpa-preloader-skeleton-pulsate"></div>',e}renderSepaDebitFields(){let e="";return e+='<label for="mpa-stripe-iban-element-'+this.uid+'">',e+=u("IBAN","motopress-appointment"),e+="</label>",e+='<div id="mpa-stripe-iban-element-'+this.uid+'" class="mpa-stripe-element mpa-stripe-iban-element mpa-preloader-skeleton-pulsate"></div>',e}renderRedirectNotice(){let e="";return e+='<p class="notice">',e+=u("You will be redirected to a secure page to complete the payment.","motopress-appointment"),e+="</p>",e}showError(e){this.isMounted()&&this.$errorsWrapper.html(e).removeClass("mpa-hide")}hideErrors(){this.isMounted()&&this.$errorsWrapper.addClass("mpa-hide").html("")}reset(){let e=this.paymentMethods.firstKey();this.selectPaymentMethod(e)}}class Ee extends Te{load(){return this.loadPromise=h("/payments/settings",{gateway_id:this.gatewayId}).catch((e=>console.error(e.message)||{})).then((e=>(jQuery.extend(this.settings,e),this))),this.loadPromise}}class Ae{name=null;title=null;control=null;api=null;elements=null;constructor(e,t,s){if(this.api=e,this.settings=s,this.elements=t,new.target===Ae)throw new Error("Cannot construct Abstract instances directly");if(void 0===this.setupProperties)throw new Error("Must override method: setupProperties()");if(this.setupProperties(),null===this.name||void 0===this.name)throw new Error('"name" must be defined in a non-abstract payment method class');if(null===this.title||void 0===this.title)throw new Error('"title" must be defined in a non-abstract payment method class')}createControl(){return null}getControl(){return this.control||(this.control=this.createControl()),this.control}reset(){null!==this.control&&this.control.clear()}createPaymentMethodData(e,t,s){let i={type:this.name,billing_details:{name:e.padEnd(3," "),email:t,phone:s}};return null!==this.control&&(i[this.name]=this.control),i}createPaymentMethod(e){return this.api.createPaymentMethod(e)}confirmPayment(e,t){throw new Error("Abstract Method has no implementation")}processPayment(e,t,s){const i=e.getCustomer(),a=this.createPaymentMethodData(i.name,i.email,i.phone);return this.createPaymentMethod(a).then((t=>{if(t.error)throw new Error(t.error.message);return c("/payments/prepare",{payment_details:jQuery.extend(e.paymentDetails,{payment_method_id:t.paymentMethod.id})})})).then((({client_secret:e,return_url:t})=>this.confirmPayment(e,t).then((e=>{if(e.error)throw new Error(e.error.message);return e.paymentIntent})))).then((e=>{let t={payment_method:this.name,payment_intent_id:e.id};return"requires_action"==e.status&&"redirect_to_url"==e.next_action.type&&(t.redirect_url=e.next_action.redirect_to_url.url),t})).catch((e=>{throw console.error("Unable to process payment.",e.message),null!=s.error_handler&&s.error_handler(e.message),e}))}}class Me extends Ae{setupProperties(){this.name="payment",this.title=u("Payment methods","motopress-appointment"),this.customerDetails={name:"",email:"",phone:""}}provideCart(e){this.cart=e}getCustomerDetails(){return this.cart?this.cart.getCustomer():{name:"",email:"",phone:""}}confirmPayment(e,t){const s=this.getCustomerDetails(),i=this.elements;return new Promise(((e,t)=>{i.submit().then((({error:s})=>{if(s){const e=s.message||"";t(new Error(e))}else e()})).catch((e=>{t(e)}))})).then((()=>{var a,r,n;return this.api.confirmPayment({elements:i,clientSecret:e,confirmParams:{payment_method_data:{billing_details:{name:null!==(a=s?.name)&&void 0!==a?a:null,email:null!==(r=s?.email)&&void 0!==r?r:null,phone:null!==(n=s?.phone)&&void 0!==n?n:null,address:{line1:null,line2:null,city:null,state:null,country:null,postal_code:null}}},return_url:t},redirect:"if_required"})})).catch((e=>{throw console.error("Error during payment confirmation:",e),e}))}processPayment(e,t,s){return c("/payments/prepare",{payment_details:e.paymentDetails}).then((({client_secret:e,return_url:t})=>this.confirmPayment(e,t).then((e=>{if(e.error)throw new Error(e.error.message);return e.paymentIntent})))).then((e=>{let t={payment_method:this.name,payment_intent_id:e.id};if("requires_action"===e.status){if("redirect_to_url"!==e.next_action.type)throw new Error("The user has cancelled or failed to complete the payment.");t.redirect_url=e.next_action.redirect_to_url.url}return t})).catch((e=>{if(e.message)throw console.error("Unable to process payment.",e.message),e;throw new Error("Unable to process payment.")}))}createControl(){const e=this.getCustomerDetails();return this.elements.create("payment",{defaultValues:{billingDetails:{address:{country:this.settings.country}}},fields:{billingDetails:{name:e?.name?"never":"auto",email:e?.email?"never":"auto",phone:e?.phone?"never":"auto",address:{line1:"auto",line2:"auto",city:"auto",state:"auto",country:"auto",postalCode:"auto"}}}})}}class xe extends Ae{setupProperties(){this.name="card",this.title=u("Card","motopress-appointment"),this.paymentRequestButtonEvent=null,this.canMakePaymentRequest=Promise.resolve(null),this.isEnabledWallets()&&(this.paymentRequest=this.createPaymentRequest(),this.canMakePaymentRequest=this.paymentRequest.canMakePayment())}createPaymentRequest(){return this.paymentRequest?this.paymentRequest:this.api.paymentRequest({country:this.settings.country,currency:m().settings().getCurrency().toLowerCase(),total:{label:u("Total","motopress-appointment"),amount:0,pending:!0},requestPayerName:!1,requestPayerEmail:!1,requestPayerPhone:!1,requestShipping:!1,disableWallets:this.getDisabledWallets()})}isCanMakePaymentRequest(){return this.canMakePaymentRequest}getPossibleWallets(){return["apple_pay","google_pay","link"]}isEnabledWallets(){let e=!1;return this.getPossibleWallets().forEach((t=>{this.settings.payment_methods.includes(t)&&(e=!0)})),e}getDisabledWallets(){let e=[];return this.getPossibleWallets().forEach((t=>{if(!this.settings.payment_methods.includes(t)){const s=t.toLowerCase().replace(/([-_][a-z])/g,(e=>e.toUpperCase().replace("-","").replace("_","")));e.push(s)}})),e}createPaymentRequestButton(){return this.elements.create("paymentRequestButton",{paymentRequest:this.paymentRequest,style:{paymentRequestButton:{height:"50px"}}})}processPaymentRequestButton(e){this.paymentRequestButtonEvent=e,jQuery(".mpa-booking-step-payment .mpa-actions .mpa-button-next").trigger("click")}proccessPaymentRequestButtonHandler(e,t){const s=e.getCustomer();return this.api.createPaymentMethod({type:"card",card:{token:this.paymentRequestButtonEvent.token.id},billing_details:{name:s.name,email:s.email,phone:s.phone}}).then((t=>{if(t.error)throw this.paymentRequestButtonEvent.complete("fail"),new Error(t.error.message);return c("/payments/prepare",{payment_details:jQuery.extend(e.paymentDetails,{payment_method_id:t.paymentMethod.id})})})).then((({client_secret:e})=>this.confirmPayment(e).then((e=>{if(e.error)throw this.paymentRequestButtonEvent.complete("fail"),this.paymentRequestButtonEvent=null,new Error(e.error.message);return e.paymentIntent})))).then((e=>{let t={payment_method:this.name,payment_intent_id:e.id};return this.paymentRequestButtonEvent.complete("success"),this.paymentRequestButtonEvent=null,t})).catch((e=>{throw this.paymentRequestButtonEvent.complete("fail"),this.paymentRequestButtonEvent=null,console.error("Unable to process payment.",e.message),null!=t.error_handler&&t.error_handler(e.message),e}))}confirmPayment(e){return this.api.confirmCardPayment(e)}processPayment(e,t,s){return this.paymentRequestButtonEvent?this.proccessPaymentRequestButtonHandler(e,s):super.processPayment(e,t,s)}createControl(){return this.elements.create(this.name,{style:this.settings.style,hidePostalCode:this.settings.hide_postal_code})}}class Be extends Ae{setupProperties(){this.name="sepa_debit",this.title=u("SEPA Direct Debit","motopress-appointment")}confirmPayment(e,t){return this.api.confirmSepaDebitPayment(e)}createControl(){return this.elements.create("iban",{style:this.settings.style,supportedCountries:["SEPA"]})}}class Fe extends Ae{setupProperties(){this.name="bancontact",this.title=u("Bancontact","motopress-appointment")}confirmPayment(e,t){return this.api.confirmBancontactPayment(e,{return_url:t},{handleActions:!1})}}class Le extends Ae{setupProperties(){this.name="ideal",this.title=u("iDEAL","motopress-appointment")}confirmPayment(e,t){return this.api.confirmIdealPayment(e,{return_url:t},{handleActions:!1})}createControl(){return this.elements.create("idealBank",{style:this.settings.style})}}class Re extends Ae{setupProperties(){this.name="giropay",this.title=u("Giropay","motopress-appointment")}confirmPayment(e,t){return this.api.confirmGiropayPayment(e,{return_url:t},{handleActions:!1})}}class Oe extends Ae{setupProperties(){this.name="sofort",this.title=u("SOFORT","motopress-appointment")}confirmPayment(e,t){return this.api.confirmSofortPayment(e,{return_url:t},{handleActions:!1})}createPaymentMethodData(e,t,s){let i=super.createPaymentMethodData(e,t,s);return i.sofort={country:this.settings.country},i}}class Ne extends Ee{setupProperties(){super.setupProperties(),this.$gatewayPreloader=null,this.gatewayId="stripe",this.methods=null,this.view=null}constructor(e,t){super(e,t),this.$gatewayPreloader=e.parent().find(".mpa-payment-gateway-title .mpa-preloader")}isValidAcceptTerms(){if(!m().settings().getTermsPageIdForAcceptance())return!0;const e=this.$mountWrapper.closest("form").find(".mpa-accept-terms")[0];return!!e.checkValidity()||(e.reportValidity(),!1)}convertToSmallestUnit(e,t){switch(t||(t=m().settings().getCurrency()),t.toUpperCase()){case"BIF":case"CLP":case"DJF":case"GNF":case"JPY":case"KMF":case"KRW":case"MGA":case"PYG":case"RWF":case"UGX":case"VND":case"VUV":case"XAF":case"XOF":case"XPF":e=Math.floor(e);break;default:e=Math.round(100*e)}return e}getFormattedTotalPrice(){const e=this.cart.getOrder();let t=parseFloat(e.total);return this.cart.paymentDetails.deposit&&(t=parseFloat(e.deposit)),this.convertToSmallestUnit(t,m().settings().getCurrency().toLowerCase())}onClickPaymentRequestButton(e){this.isValidAcceptTerms()?this.methods.card.paymentRequest.update({total:{amount:this.getFormattedTotalPrice(),label:u("Total","motopress-appointment"),pending:!1}}):e.preventDefault()}onChange(e){this.haveErrors=!!e.error,this.haveErrors?this.view.showError(e.error.message):this.view.hideErrors()}onCartChange(e){this.isMounted&&0<this.getFormattedTotalPrice()&&0===Object.keys(this.methods).length&&(this.$mountWrapper.empty(),this.mount(this.$mountWrapper))}mount(e){this.ready().then((()=>{this.methods=[],0<this.getFormattedTotalPrice()&&(this.methods=this.createPaymentMethods()),this.view=new De(this.methods),this.view.mount(e),this.addListeners()}))}processPayment(e,t){if(!this.isValid())return Promise.reject(new Error("The payment gateway is not valid."));this.$gatewayPreloader.removeClass("mpa-hide");let s=this.view.selectedMethod,i=jQuery.extend({payment_method:s},this.settings,t),a={error_handler:this.view.showError.bind(this.view)};return this.methods[s].processPayment(e,i,a).then((e=>(this.$gatewayPreloader.addClass("mpa-hide"),e)),(e=>{throw this.$gatewayPreloader.addClass("mpa-hide"),e}))}getDefaults(){return jQuery.extend(super.getDefaults(),{hide_postal_code:!0,locale:"auto",payment_methods:[],public_key:"",style:{}})}createPaymentMethods(){let e=[];const t=Stripe(this.settings.public_key,{apiVersion:"2023-10-16"}),s=t.elements({mode:"payment",locale:this.settings.locale,currency:m().settings().getCurrency().toLowerCase(),amount:this.getFormattedTotalPrice(),payment_method_configuration:this.settings.payment_method_configuration});return this.settings.payment_methods.forEach((i=>{switch(i){case"payment":e.payment=new Me(t,s,this.settings),e.payment.provideCart(this.cart);break;case"card":e.card=new xe(t,s,this.settings),e.card.getControl().on("change",this.onChange.bind(this)),e.card.isCanMakePaymentRequest().then((t=>{t&&(e.card.paymentRequest.on("token",(async t=>e.card.processPaymentRequestButton(t))),e.card.paymentRequest.on("cancel",(()=>{e.card.paymentRequestButtonEvent=null})),e.card.paymentRequestButton=e.card.createPaymentRequestButton(),e.card.paymentRequestButton.on("click",this.onClickPaymentRequestButton.bind(this)))}));break;case"sepa_debit":e.sepa_debit=new Be(t,s,this.settings),e.sepa_debit.getControl().on("change",this.onChange.bind(this));break;case"bancontact":e.bancontact=new Fe(t,s,this.settings);break;case"ideal":e.ideal=new Le(t,s,this.settings);break;case"giropay":e.giropay=new Re(t,s,this.settings);break;case"sofort":e.sofort=new Oe(t,s,this.settings)}})),e}reset(){this.methods&&Object.entries(this.methods).forEach((([e,t])=>{t.reset()})),this.view&&this.view.reset()}}class Ve extends Ee{setupProperties(){super.setupProperties(),this.gatewayId="paypal"}enable(){super.enable(),this.isEnabled&&this.$mountWrapper.closest("form").find(".mpa-button-next").hide()}disable(){super.disable(),this.isEnabled||this.$mountWrapper.closest("form").find(".mpa-button-next").show()}mount(e){let t=this;t.$errorWrapper=e.find(".mpa-paypal-error"),t.$gatewayPreloader=e.parent().find(".mpa-payment-gateway-title .mpa-preloader"),paypal.Buttons({onInit(e,s){if(m().settings().getTermsPageIdForAcceptance()){const e=t.$mountWrapper.closest("form").find(".mpa-accept-terms")[0];e.checkValidity()||s.disable(),e.addEventListener("change",(e=>{e.target.checked?s.enable():s.disable()}))}},onClick:function(e,s){if(m().settings().getTermsPageIdForAcceptance()){const e=t.$mountWrapper.closest("form").find(".mpa-accept-terms")[0];e.checkValidity()||e.reportValidity()}0===t.cart.getTotalPrice()&&(t.paypalDetails={},jQuery(".mpa-booking-step-payment .mpa-actions .mpa-button-next").trigger("click"))},createOrder:function(e,s){return t.$errorWrapper.addClass("mpa-hide"),t.$gatewayPreloader.removeClass("mpa-hide"),c("/payments/prepare",{payment_details:t.cart.paymentDetails}).then((e=>(t.$gatewayPreloader.addClass("mpa-hide"),e)))},onApprove:function(e,s){return s.order.capture().then((function(e){t.paypalDetails=e,jQuery(".mpa-booking-step-payment .mpa-actions .mpa-button-next").trigger("click")}))},onCancel:function(e){},onError:function(e){console.log(e),t.$errorWrapper.text(t.settings.paypal_error_message),t.$errorWrapper.removeClass("mpa-hide")}}).render(e.find(".mpa-paypal-container")[0])}processPayment(e,t){return Promise.resolve({paypalDetails:this.paypalDetails})}}class qe{static createGateways(e,t){let s={};for(let i of m().settings().getActiveGateways()){let a=e.find(".mpa-"+i+"-payment-gateway .mpa-billing-fields"),r=0!==a.length?qe.createGateway(i,a,t):null;null!==r&&(s[i]=r)}return s.free=new Ie({},t),s}static createGateway(e,t,s){switch(e){case"manual":case"test":case"cash":case"bank":return new Te(t,s);case"paypal":return new Ve(t,s);case"stripe":return new Ne(t,s);default:return wp.hooks.applyFilters("mpa_create_gateway",null,e,t,s)}}}class Ue extends le{setupProperties(){super.setupProperties(),this.lastCartHash="",this.gatewayId="",this.gateways={},this.bookingDetails={},this.$form=this.$element.find(".mpa-checkout-form"),this.$order=this.$element.find(".mpa-order"),this.$billingSection=this.$element.find(".mpa-billing-details"),this.$paymentGateways=this.$billingSection.find(".mpa-payment-gateway"),this.$paymentGatewayButtons=this.$paymentGateways.find('input[name="payment_gateway_id"]'),this.$message=this.$element.find(".mpa-message").first(),this.acceptTerms=!1,this.onlinePayment=!1,this.isDepositDisabled=!1,this.$deposit=this.$element.find(".mpa-deposit-section"),this.$depositSwitcher=this.$element.find('input[name="mpa-deposit-switcher"]'),this.$depositTable=this.$element.find("#mpa-deposit-table"),m().settings().getTermsPageIdForAcceptance()&&(this.$acceptTerms=this.$element.find(".mpa-accept-terms")),this.couponSection=null}theId(){return"payment"}propertiesSchema(){return{gatewayId:{type:"string",default:""},isDepositDisabled:{type:"bool",default:!1},acceptTerms:{type:"bool",default:!1}}}setErrorMessage(e){this.$message.html(e),this.$message.toggleClass("mpa-hide",!e.trim().length)}clearErrorMessage(){this.setErrorMessage("")}hideDeposit(){this.$deposit.addClass("mpa-hide"),this.$depositSwitcher.prop("disabled",!0),this.isDepositDisabled=!0}showDeposit(){this.$deposit.removeClass("mpa-hide"),this.$depositSwitcher.prop("disabled",!1),this.setProperty("isDepositDisabled",this.$depositSwitcher.prop("checked"))}toggleDepositSection(){const e=this.cart.getOrder();parseFloat(e.total)-parseFloat(e.deposit)&&this.onlinePayment?this.showDeposit():this.hideDeposit()}setGatewayId(e,t){this.setProperty("gatewayId",e),this.onlinePayment=parseInt(t),this.toggleDepositSection(),this.cart.setPaymentDetails({gateway_id:this.gatewayId,deposit:!this.isDepositDisabled})}addListeners(){super.addListeners(),this.$form.on("submit",(e=>!1)),this.$paymentGatewayButtons.on("change",(e=>{this.setGatewayId(e.target.value,e.target.dataset.isOnlinePayment)})),m().settings().getTermsPageIdForAcceptance()&&this.$acceptTerms.on("input",(e=>this.setProperty("acceptTerms",e.target.checked))),this.$depositSwitcher.length>0&&this.$depositSwitcher.on("input",(e=>{this.$depositTable.toggleClass("mpa-hide",e.target.checked),this.setProperty("isDepositDisabled",e.target.checked),this.cart.setPaymentDetails({deposit:!this.isDepositDisabled})})),this.$element.on("mpa_booking_step_disable",this.disable.bind(this)),this.$element.on("mpa_booking_step_enable",this.enable.bind(this)),this.$element.on("mpa_booking_coupon_applied",(()=>{this.notifyCartChanged(),this.updateOrderDetails(),this.cart.setPaymentDetails({coupon_code:this.cart.hasCoupon()?this.cart.coupon.getCode():""})}))}loadEntities(){this.isLoaded||this.$element.removeClass("mpa-hide"),this.lastCartHash=this.cart.getHash("order"),m().settings().isCouponsEnabled()&&(this.couponSection=new we(this.$element.find(".mpa-coupon-details"),this.cart)),this.updateOrderDetails();let e=[];return"free"!==this.gatewayId?e.push(this.loadGateways()):this.loadGateways(),e.push(this.loadDrafts()),Promise.all(e).then((()=>(this.initDefaultGateway(),this)))}reload(){return this.clearErrorMessage(),this.cart.hasCoupon()&&this.cart.testCoupon(),this.couponSection&&(this.cart.hasCoupon()?this.couponSection.clearMessage():this.couponSection.reset()),this.updateOrderDetails(),this.cart.didChange(this.lastCartHash,"order")?(this.lastCartHash=this.cart.getHash("order"),this.notifyCartChanged(),this.loadDrafts()):wp.hooks.applyFilters("mpa_booking_reload_drafts",!1)?this.loadDrafts():Promise.resolve(this)}reset(){m().settings().getTermsPageIdForAcceptance()&&(this.$acceptTerms.prop("checked",!1),this.resetProperty("acceptTerms")),this.lastCartHash="";let e=m().settings().getDefaultPaymentGateway();this.$paymentGatewayButtons.filter(":checked").prop("checked",!1),e in this.gateways?(this.setProperty("gatewayId",e),this.$paymentGatewayButtons.filter('[value="'+e+'"]').prop("checked",!0)):this.resetProperty("gatewayId");for(let e in this.gateways)this.gateways[e].reset();this.couponSection&&this.couponSection.reset()}notifyCartChanged(){for(let e in this.gateways)this.gateways[e].onCartChange(this.cart)}updateOrderDetails(){if(this.$order.empty(),this.$order.html(ge(this.cart.getOrder())),this.$depositTable.length>0){const e=function(e){const t=parseFloat(e.total)-parseFloat(e.deposit);let s="";return t>0&&(s+='<table class="widefat">',s+="<tbody>",s+='<tr class="mpa-deposit-title">',s+='<td class="column-title" colspan="2">',s+=u("Deposit","motopress-appointment"),s+="</td>",s+="</tr>",s+='<tr class="mpa-deposit-now">',s+='<th class="column-title">',s+=u("Paying now","motopress-appointment"),s+="</th>",s+='<th class="column-price">',s+=fe(e.deposit),s+="</th>",s+="</tr>",s+='<tr class="mpa-deposit-left">',s+='<th class="column-title">',s+=u("Left to pay","motopress-appointment"),s+="</th>",s+='<th class="column-price">',s+=fe(t),s+="</th>",s+="</tr>",s+="</tbody>",s+="</table>"),s}(this.cart.getOrder());this.$depositTable.html(e),this.$paymentGatewayButtons.filter(":checked").length>0&&this.toggleDepositSection()}let e=this.$order.find(".mpa-remove-coupon");e.length>0&&e.on("click",this.removeCoupon.bind(this)),this.toggleAvailablePaymentMethods()}removeCoupon(e){e.preventDefault(),e.stopPropagation(),this.cart.removeCoupon(),this.couponSection.clearMessage(),this.cart.setPaymentDetails({coupon_code:""}),this.notifyCartChanged(),this.updateOrderDetails(),this.couponSection.reset()}toggleAvailablePaymentMethods(){const e=0===this.cart.getTotalPrice();if(e)this.setGatewayId("free",!1);else{const e=this.$paymentGatewayButtons.filter(":checked");e.length>0&&this.setGatewayId(e[0].value,e[0].dataset.isOnlinePayment)}this.$billingSection.toggleClass("mpa-hide",e),this.$paymentGatewayButtons.prop("required",!e)}loadGateways(){let e=this.$billingSection.find(".mpa-payment-gateways");this.gateways=qe.createGateways(e,this.cart);let t=[];for(let e in this.gateways)t.push(this.gateways[e].load());return t}loadDrafts(){let e=this.cart.toArray();return e.payment=!0,c("/bookings/draft",wp.hooks.applyFilters("mpa_booking_draft_data",e)).then((e=>{this.bookingDetails=e;const t={booking_id:e.booking_id,payment_id:e.payment_id};this.cart.setPaymentDetails(t)}),(e=>{this.setErrorMessage(e.message)})).then((()=>(this.enableGateways(),this)))}enableGateways(){this.$paymentGatewayButtons.prop("disabled",!1)}initDefaultGateway(){let e=this.$paymentGatewayButtons.filter(":checked");e.length>0&&this.gateways[e.val()].enable()}isValidInput(){return this.isValidGatewayId()&&this.isValidGateway()&&this.isValidAcceptTerms()}isValidGatewayId(){return""!==this.gatewayId}isValidGateway(){return!(this.gatewayId in this.gateways)||this.gateways[this.gatewayId].isValid()}isValidAcceptTerms(){return!m().settings().getTermsPageIdForAcceptance()||this.acceptTerms}afterUpdate(e,t,s){s in this.gateways&&this.gateways[s].disable(),t in this.gateways&&this.gateways[t].enable()}react(){super.react(),this.$buttonNext.prop("disabled",!1)}maybeSubmit(){if(this.couponSection&&this.couponSection.disable(),this.gatewayId in this.gateways){let e=this.gateways[this.gatewayId].processPayment(this.cart,this.bookingDetails);return"object"==typeof e&&"function"==typeof e.then&&e.then((e=>(this.cart.setPaymentDetails(e),e)),(e=>{this.setErrorMessage(e.message)})),e}}cancelSubmission(){super.cancelSubmission(),this.couponSection&&this.couponSection.enable()}}class He extends le{setupProperties(){super.setupProperties(),this.cartItem=null,this.lastHash="",this.monthSlots={},this.date="",this.time="",this.datepicker=null,this.$dateWrapper=this.$element.find(".mpa-date-wrapper"),this.$dateInput=this.$element.find(".mpa-date"),this.$timeWrapper=this.$element.find(".mpa-time-wrapper"),this.$times=this.$timeWrapper.find(".mpa-times"),this.lookedAheadMonths=0,this.maxLookAheadMonths=12,this.isSelectedFirstAvailableSlot=!1,this.availabilityService=null}setAvailabilityService(e){this.availabilityService=e}theId(){return"period"}getCartContext(){return"cart item"}propertiesSchema(){return{date:{type:"string",default:""},time:{type:"string",default:""}}}addListeners(){super.addListeners(),this.$dateInput.on("change",(e=>this.setProperty("date",e.target.value)))}loadEntities(){return this.cartItem=this.cart.getActiveItem(),this.lastHash=this.cartItem.getHash("availability"),Promise.resolve(this)}reload(){return this.cartItem.didChange(this.lastHash,"availability")?(this.$element.removeClass("mpa-loaded"),this.resetDate(),this.readyPromise=this.loadEntities(),this.monthSlots={},null!=this.datepicker&&(this.setEnabledDays([]),this.readyPromise.finally((()=>this.resetEnabledDays()))),this.readyPromise):Promise.resolve(this)}reset(){this.cartItem=this.cart.getActiveItem(),this.lastHash="",this.monthSlots={},this.resetDate()}isValidInput(){return""!=this.date&&""!=this.time}resetDate(){this.resetProperty("date")}resetTime(){this.$times.empty(),this.resetProperty("time")}setEnabledDays(e){B(e,!0)?this.datepicker.set("enable",["2000-01-01"]):this.datepicker.set("enable",e)}afterUpdate(e,t,s){"date"==e&&(""==t?this.resetTime():this.resetTimeSlots())}react(){super.react(),this.$timeWrapper.toggleClass("mpa-hide",""==this.date)}showReady(){super.showReady(),null==this.datepicker&&(this.showDatepicker(),this.resetEnabledDays())}showDatepicker(){this.datepicker=function(e,t){let s=t.locale||m().settings().getFlatpickrLocale(),i=flatpickr.l10ns[s]||s;"object"==typeof i&&(i.firstDayOfWeek=m().settings().getFirstDayOfWeek());let a={formatDate:f,inline:!0,locale:i,monthSelectorType:"static",showMonths:1};t=jQuery.extend({},a,t);let r=null;return r=e instanceof jQuery?flatpickr(e[0],t):flatpickr(e,t),r}(this.$dateInput,this.getDatepickerArgs())}getDatepickerArgs(){return{minDate:m().settings().getBusinessDate(),onMonthChange:()=>this.resetEnabledDays()}}maybeSubmit(){let e=this.cartItem;if(e.date=b(this.date),e.time=new Y(this.time),e.date&&e.time&&e.time.setDate(e.date),null===e.employee||null===e.location){let t=this.autoselectIds(),s=t[0],i=t[1];null===e.employee&&e.setEmployee(s,!1),null===e.location&&e.setLocation(i,!1)}let t=this.getCurrentMonthKey();this.cartItem.setBookingVariants(this.monthSlots[t][this.date][this.time]),document.dispatchEvent(new CustomEvent("mpa_add_to_cart",{detail:{cartItem:e,currencyCode:m().settings().getCurrency()}})),document.dispatchEvent(new CustomEvent("mpa_view_cart",{detail:{cart:this.cart,currencyCode:m().settings().getCurrency()}}))}selectFirstDateTimeSlot(){let e=this.datepicker.currentYear,t=this.datepicker.currentMonth,s=this.getMonthKey(e,t);const i=this.monthSlots[s];if(i&&Object.keys(i).length>0){const e=Object.keys(i)[0],t=Object.keys(i[e])[0];this.datepicker.setDate(e,!0);this.$times.children(".mpa-time-period").filter(((e,s)=>s.getAttribute("date-time")===t)).trigger("click"),this.isSelectedFirstAvailableSlot=!0}else{if(!0===this.isSelectedFirstAvailableSlot)return;if(this.lookedAheadMonths>=this.maxLookAheadMonths)return this.datepicker.changeMonth(-this.lookedAheadMonths),void(this.isSelectedFirstAvailableSlot=!0);this.lookedAheadMonths+=1,this.datepicker.changeMonth(1),this.reload()}}autoselectIds(){let e=[0,0],t=this.getCurrentMonthKey();if(this.monthSlots[t]&&this.monthSlots[t][this.date]){let s=this.monthSlots[t][this.date];for(let t in s)if(t===this.time){let i=s[t];e[0]=i[0][0],e[1]=i[0][1];break}}return e}waitForServiceToLoad(){let e=this.availabilityService.getServicePromise();return null!==e?e:Promise.resolve(this.cartItem.getService())}resetEnabledDays(){this.resetDate(),this.setEnabledDays([]),this.$dateWrapper.removeClass("mpa-loaded");let e=this.datepicker.currentYear,t=this.datepicker.currentMonth,s=this.getMonthKey(e,t),i=null;if(this.monthSlots[s])i=Promise.resolve(this.monthSlots[s]);else{i=function(e,t,s,i){return h("/calendar/time",{service_id:e,employee_in:i.employee_in?i.employee_in.join(","):"",location_in:i.location_in?i.location_in.join(","):"",date_from:f(t,"internal"),date_to:f(s,"internal"),exclude_cart:i.exclude_cart?i.exclude_cart:[]}).catch((e=>console.error("Failed to make time slots in mpa_time_slots().",e.message)||{}))}(this.cartItem.service.id,new Date(e,t,1),new Date(e,t+1,1),this.getTimeSlotsQueryArgs())}Promise.all([i,this.waitForServiceToLoad()]).then((e=>{let t=e[0];this.monthSlots[s]=t,this.setEnabledDays(Object.keys(t)),this.$dateWrapper.addClass("mpa-loaded"),this.selectFirstDateTimeSlot()}))}getTimeSlotsQueryArgs(){let e=this.cartItem.getEmployeeId(),t=this.cartItem.getLocationId();return{employee_in:e?[e]:this.cartItem.getAvailableEmployeeIds(),location_in:t?[t]:this.cartItem.getAvailableLocationIds(),exclude_cart:this.cart.toArray("items")}}resetTimeSlots(){this.resetTime();let e={},t=this.getCurrentMonthKey();null!=this.monthSlots[t][this.date]&&(e=this.monthSlots[t][this.date]);let s=0;for(let t in e){let i=new Y(t).toString("public",'<span class="mpa-period-end-time"> - ')+"</span>",a=this.cartItem.getService();if(a.isGroupService()){let s=a.getMinCapacity();for(let i of e[t])s=Math.max(s,i[3]);i+=" ",i+='<span class="mpa-slot-capacity">',i+='<span class="mpa-slot-capacity-label">'+a.getQuantityLabel()+":</span>",i+="&nbsp;",i+='<span class="mpa-slot-capacity-number">'+s+"</span>",i+="</span>"}let r=me(i,{class:"button button-secondary mpa-time-period","date-time":t});this.$times.append(r),s++}s>0?this.$times.children(".mpa-time-period").on("click",(e=>this.onTime(e,e.currentTarget))):this.$times.text(u("Sorry, but we were unable to allocate time slots for the date you selected.","motopress-appointment"))}getMonthKey(e,t){return t<=8?e+"-0"+(t+1):e+"-"+(t+1)}getCurrentMonthKey(){if(""!==this.date){let e=b(this.date);return this.getMonthKey(e.getFullYear(),e.getMonth())}return"2000-01"}onTime(e,t){this.$times.children(".mpa-time-period-selected").removeClass("mpa-time-period-selected"),t.classList.add("mpa-time-period-selected"),this.setProperty("time",t.getAttribute("date-time"))}}class je extends le{setupProperties(){super.setupProperties(),this.availabilityService=null,this.category="",this.serviceId=0,this.employeeId=0,this.locationId=0,this.isHiddenStep=!0,this.$form=this.$element.find(".mpa-service-form"),this.$categories=this.$element.find(".mpa-service-category-wrapper"),this.$services=this.$element.find(".mpa-service-wrapper"),this.$employees=this.$element.find(".mpa-employee-wrapper"),this.$locations=this.$element.find(".mpa-location-wrapper"),this.$selects=this.$element.find(".mpa-input-wrapper select"),this.$categoriesSelect=this.$selects.filter(".mpa-service-category"),this.$servicesSelect=this.$selects.filter(".mpa-service"),this.$employeesSelect=this.$selects.filter(".mpa-employee"),this.$locationsSelect=this.$selects.filter(".mpa-location"),this.unselectedServiceText=this.$servicesSelect.children('[value=""]').text(),this.unselectedOptionText=this.$selects.filter(".mpa-optional-select").first().find("option:first").text()}setAvailabilityService(e){this.availabilityService=e}theId(){return"service-form"}getCartContext(){return"cart item"}propertiesSchema(){return{category:{type:"string",default:""},serviceId:{type:"integer",default:0},employeeId:{type:"integer",default:0},locationId:{type:"integer",default:0}}}addListeners(){super.addListeners(),this.$form.on("submit",this.submitForm.bind(this)),this.$categoriesSelect.on("change",(e=>this.setProperty("category",e.target.value))),this.$servicesSelect.on("change",(e=>this.setProperty("serviceId",e.target.value))),this.$employeesSelect.on("change",(e=>this.setProperty("employeeId",e.target.value))),this.$locationsSelect.on("change",(e=>this.setProperty("locationId",e.target.value)))}isHiddenElementByProp(e){const t=e.attr("data-is-hidden");return void 0!==t&&"false"!==t}initCategoriesSelect(){if(0==this.$categoriesSelect.length)return;this.updateCategorySchema();let e=this.$categoriesSelect.val(),t=this.isHiddenElementByProp(this.$categoriesSelect);if(this.$categoriesSelect.attr("data-default")){const s=this.$categoriesSelect.attr("data-default");this.isValidCategoryBySchema(s)?e=s:t=!1}this.setProperty("category",e),this.renderCategorySelect(),t||(this.isHiddenStep=!1),this.$categories.toggleClass("mpa-hide",t)}initServicesSelect(){if(0==this.$servicesSelect.length)return;this.updateServiceSchema();let e=this.$servicesSelect.val(),t=this.isHiddenElementByProp(this.$servicesSelect);if(this.$servicesSelect.attr("data-default")){const s=j(this.$servicesSelect.attr("data-default"));this.isValidServiceBySchema(s)?e=s:t=!1}this.setProperty("serviceId",e),this.renderServiceSelect(),t||(this.isHiddenStep=!1),this.$services.toggleClass("mpa-hide",t)}initEmployeesSelect(){if(0==this.$employeesSelect.length)return;this.updateEmployeeSchema();let e=this.$employeesSelect.val(),t=this.isHiddenElementByProp(this.$employeesSelect);if(this.$employeesSelect.attr("data-default")){const s=j(this.$employeesSelect.attr("data-default"));this.isValidEmployeeBySchema(s)?e=s:t=!1}this.setProperty("employeeId",e),this.renderEmployeeSelect(),t||(this.isHiddenStep=!1),this.$employees.toggleClass("mpa-hide",t)}initLocationsSelect(){if(0==this.$locationsSelect.length)return;this.updateLocationSchema();let e=this.$locationsSelect.val(),t=this.isHiddenElementByProp(this.$locationsSelect);if(this.$locationsSelect.attr("data-default")){const s=j(this.$locationsSelect.attr("data-default"));this.isValidLocationBySchema(s)?e=s:t=!1}this.setProperty("locationId",e),this.renderLocationSelect(),t||(this.isHiddenStep=!1),this.$locations.toggleClass("mpa-hide",t)}loadEntities(){return this.availabilityService.ready().finally((()=>(this.initServicesSelect(),this.initCategoriesSelect(),this.initEmployeesSelect(),this.initLocationsSelect(),this)))}reset(){let e={category:this.$categoriesSelect,serviceId:this.$servicesSelect,employeeId:this.$employeesSelect,locationId:this.$locationsSelect};this.preventReact=!0;for(let t in e){let s=e[t].attr("data-default");s?this.setProperty(t,s):this.resetProperty(t)}this.preventReact=!1,this.isActive&&this.react()}isValidInput(){return 0!=this.serviceId}updateCategorySchema(){const e=this.availabilityService.getAvailableServiceCategories();this.schema.category.options=Object.keys(e)}updateServiceSchema(){const e=this.availabilityService.getAvailableServices(this.category,this.locationId,this.employeeId);this.schema.serviceId.options=Object.keys(e).map(j)}updateEmployeeSchema(){const e=this.availabilityService.getAvailableEmployees(this.serviceId,this.locationId);this.schema.employeeId.options=Object.keys(e).map(j)}updateLocationSchema(){const e=this.availabilityService.getAvailableLocations(this.serviceId,this.employeeId);this.schema.locationId.options=Object.keys(e).map(j)}isValidCategoryBySchema(e){return this.schema.category.options.includes(e)}isValidServiceBySchema(e){return this.schema.serviceId.options.includes(e)}isValidLocationBySchema(e){return this.schema.locationId.options.includes(e)}isValidEmployeeBySchema(e){return this.schema.employeeId.options.includes(e)}afterUpdate(e,t,s){if(this.updateCategorySchema(),this.updateServiceSchema(),this.updateEmployeeSchema(),this.updateLocationSchema(),"category"===e){let e=this.availabilityService.getAvailableServices(this.category,this.locationId,this.employeeId);this.serviceId in e||(this.resetProperty("serviceId"),this.resetProperty("employeeId"),this.resetProperty("locationId"))}}react(){super.react(),this.$categoriesSelect.val(this.category||""),this.$servicesSelect.val(this.serviceId||""),this.$employeesSelect.val(this.employeeId),this.$locationsSelect.val(this.locationId),this.$categoriesSelect.toggleClass("mpa-selected",""!=this.category),this.$servicesSelect.toggleClass("mpa-selected",0!=this.serviceId),this.$employeesSelect.toggleClass("mpa-selected",0!=this.employeeId),this.$locationsSelect.toggleClass("mpa-selected",0!=this.locationId),this.renderCategorySelect(),this.renderServiceSelect(),this.renderEmployeeSelect(),this.renderLocationSelect(),this.$buttonNext.prop("disabled",!1)}renderCategorySelect(){this.preventUpdate=!0,_e(this.$categoriesSelect,{"":this.unselectedOptionText},this.availabilityService.getAvailableServiceCategories(),this.category||""),this.preventUpdate=!1}renderServiceSelect(){this.preventUpdate=!0;let e=this.availabilityService.getAvailableServices(this.category,this.locationId,this.employeeId);_e(this.$servicesSelect,{"":this.unselectedServiceText},e,this.serviceId in e?this.serviceId:""),this.preventUpdate=!1}renderEmployeeSelect(){this.preventUpdate=!0,_e(this.$employeesSelect,{0:this.unselectedOptionText},this.availabilityService.getAvailableEmployees(this.serviceId,this.locationId),this.employeeId),this.preventUpdate=!1}renderLocationSelect(){this.preventUpdate=!0,_e(this.$locationsSelect,{0:this.unselectedOptionText},this.availabilityService.getAvailableLocations(this.serviceId,this.employeeId),this.locationId),this.preventUpdate=!1}show(){this.$servicesSelect.prop("required",!0),super.show()}hide(){super.hide(),this.$servicesSelect.prop("required",!1)}enable(){super.enable(),this.$selects.prop("disabled",!1)}disable(){super.disable(),this.$selects.prop("disabled",!0)}submitForm(e){this.isActive&&!this.isValidInput()||e.preventDefault()}maybeSubmit(){let e=this.cart.getActiveItem();if(null===e)return console.error("Unable to get active cart item in StepServiceForm.maybeSubmit().");if(e.setService(this.availabilityService.getService(this.serviceId,!0,(()=>{document.dispatchEvent(new CustomEvent("mpa_view_item",{detail:{cartItem:e,currencyCode:m().settings().getCurrency()}}))}))),e.setServiceCategories(this.availabilityService.getServiceCategories(this.serviceId)),0!==this.employeeId?e.setEmployee(this.availabilityService.getEmployee(this.employeeId)):e.setAvailableEmployees(this.availabilityService.filterAvailableEmployees(this.serviceId,this.locationId,"entities")),0!==this.locationId)e.setLocation(this.availabilityService.getLocation(this.locationId));else{let t=this.employeeId||e.getAvailableEmployeeIds();e.setAvailableLocations(this.availabilityService.filterAvailableLocations(this.serviceId,t,"entities"))}}}class We{constructor(e){this.$element=e,this.$message=this.$element.children(".mpa-message"),this.cart=new L,this.steps=new oe(this.cart),this.load()}setupSteps(){this.steps.addStep(new je(this.$element.find(".mpa-booking-step-service-form"),this.cart)).addStep(new He(this.$element.find(".mpa-booking-step-period"),this.cart)).addStep(new Ce(this.$element.find(".mpa-booking-step-cart"),this.cart)).addStep(new ke(this.$element.find(".mpa-booking-step-checkout"),this.cart)),m().settings().isPaymentsEnabled()&&this.steps.addStep(new Ue(this.$element.find(".mpa-booking-step-payment"),this.cart)),this.steps.addStep(new pe(this.$element.find(".mpa-booking-step-booking"),this.cart)),this.steps.mount(this.$element)}load(){this.cart.createItem();let e=new ne;Promise.all([e.load(),m().settings().ready()]).finally((()=>{this.setupSteps(),this.steps.getStep("service-form").setAvailabilityService(e),this.steps.getStep("period").setAvailabilityService(e),this.show(),e.isEmpty()?(this.$message.html(u("Sorry, there are no services, employees or locations to book.","motopress-appointment")),this.$message.removeClass("mpa-hide")):this.steps.goToNextStep()}))}show(){this.$element.addClass("mpa-loaded")}}class Ge extends We{constructor(e){super(e.children(".widget-body").first())}}jQuery(".appointment-form-shortcode").each(((e,t)=>{new We(jQuery(t))})),jQuery(".appointment-form-widget").each(((e,t)=>{new Ge(jQuery(t))})),jQuery(document).ready((function(){m().settings().ready().then((()=>{jQuery(".mpa-booking-details-section [data-reservation-id]").each(((e,t)=>{let s=jQuery(t);const i=s.data("reservation-id"),a=new Date(s.data("start-time")),r=new Date(s.data("end-time")),n=s.data("service-name"),o=s.data("employee-name")+". "+s.data("quantity-label")+": "+s.data("capacity")+".",l=s.data("location-name"),h=he.createICSURL(i,a,r,n,o,l),c=he.createGoogleCalendarURL(a,r,n,o,l),p=he.createYahooCalendarURL(a,r,n,o,l);s.find(".mpa-add-to-calendar-link--google").attr("href",c),s.find(".mpa-add-to-calendar-link--apple").attr("href",h),s.find(".mpa-add-to-calendar-link--outlook").attr("href",h),s.find(".mpa-add-to-calendar-link--yahoo").attr("href",p)}))}))}))}(wp.date,mpaData,intlTelInput)}();
(function(){
wp.hooks.addAction('mpa_step_checkout_form', 'mpacf', function ($element){
new mpaCheckoutFields($element);
});
class mpaCheckoutFields {
constructor($element){
this.$element=$element;
this.$fields=$element.find('.mpa-input-wrapper[class*="mpa-"][class*="-control"] [class^="mpa-customer-"]');
Array.from(this.$fields).forEach(field=> {
if(field.getAttribute('type')==='tel'){
mpa_intl_tel_input(jQuery(field));
}});
this.$buttonNext=this.$element.find('.mpa-button-next');
this.addListeners();
wp.hooks.addFilter('mpa_step_checkout_form_valid', 'mpacf', ($bool, $currentform)=> {
let isvalidform=true;
Array.from($currentform.find('.mpa-input-wrapper[class*="mpa-"][class*="-control"] [class^="mpa-customer-"]')).forEach(field=> {
if(!this.validateField(field)){
isvalidform=false;
}});
return isvalidform;
});
}
addListeners(){
this.$buttonNext.on('click', ()=> {
wp.hooks.addFilter('mpa_booking_cart_data', 'mpacf', (cart_data)=> {
if(!cart_data.hasOwnProperty('checkout_fields')){
cart_data.checkout_fields={};}
cart_data.checkout_fields={};
Array.from(this.$fields).forEach(field=> {
if(this.getFieldValue(field)){
cart_data.checkout_fields[field.getAttribute('name')]=this.getFieldValue(field);
}});
return cart_data;
});
});
}
validateField(field){
switch (field.getAttribute('type')){
case 'email':
return field.checkValidity();
case 'country':
return field.checkValidity();
case 'date_of_birth':
let dob_validity=false;
var dayReqControl=jQuery(field).siblings(".mpa-day-control-component[required]");
var monthReqControl=jQuery(field).siblings(".mpa-month-control-component[required]");
var yearReqControl=jQuery(field).siblings(".mpa-year-control-component[required]");
if(dayReqControl.val()===''||monthReqControl.val()===''||yearReqControl.val()===''){
dob_validity=false;
jQuery(field).focus();
return dob_validity;
}
dob_validity=true;
return dob_validity;
case 'tel':
let validity=false;
if(( jQuery(field).is('[required]')&&jQuery(field).is('.mpa-phone-number--invalid'))||(jQuery(field).is('[required]')&&jQuery(field).val()==='')){
validity=false;
return validity;
}else{
validity=true;
return validity;
}
default:
return field.checkValidity();
}}
getFieldValue(field){
switch (field.getAttribute('type')){
case 'tel':
return jQuery(field).parent().children('input[type="hidden"][name="' + field.name + '"]').val();
break;
case 'email':
return jQuery(field).val();
break;
case 'file':
return false;
break;
case 'checkbox':
if(jQuery(field).is(':checked')){
jQuery(field).val('1');
}else{
jQuery(field).val('0');
}
return jQuery(field).val();
break;
default:
return jQuery(field).val();
break;
}}
}})();
jQuery(function (){
'use strict';
jQuery('.mpa-date_of_birth-control, .mpa-ctrl-date-of-birth, .mpa-date-of-birth-ctrl').each(function (i, element){
var $control=jQuery(element);
var $day=$control.find('.mpa-day-control-component');
var $month=$control.find('.mpa-month-control-component');
var $year=$control.find('.mpa-year-control-component');
var $holder=$control.find('.mpa-dob-holder-control-component');
$month.on('change', onMonthOrYearUpdate);
$year.on('change', onMonthOrYearUpdate);
function onMonthOrYearUpdate(){
var month=$month.val();
var year=$year.val()||mpa_cf_current_year();
var daysInMonth=month!=='' ? mpa_cf_days_in_month(parseInt(month), parseInt(year)):31;
mpa_cf_reset_options_number($day, daysInMonth);
}
$day.on('change', onBdateDataUpdate);
$month.on('change', onBdateDataUpdate);
$year.on('change', onBdateDataUpdate);
function onBdateDataUpdate(){
var day=$day.val();
var month=$month.val();
var year=$year.val();
if(day&&month&&year&&$holder[0]){
$holder.val(year + '-' + month + '-' + day);
}}
});
function mpa_cf_current_year(){
var currentDate=new Date();
return currentDate.getFullYear();
}
function mpa_cf_days_in_month(month, year){
var date=new Date(year, month, 0);
return date.getDate();
}
function mpa_cf_reset_options_number($select, limit){
var optionsCount=$select.children('[value!=""]').length;
if(optionsCount < limit){
for (var i=optionsCount + 1; i <=limit; i++){
var $option=jQuery('<option value="' + i + '">' + i + '</option>');
$select.append($option);
}}else if(optionsCount > limit){
$select.children().each(function (i, option){
if(option.value!==''&&parseInt(option.value) > limit){
option.remove();
}});
}}
});
jQuery(document).ready(function($){
const { __ }=wp.i18n;
let draft_cart_data={};
function showLoadingIndicator(form){
form.parent().siblings('.mpa-loading').show();
}
function hideLoadingIndicator(form){
form.parent().siblings('.mpa-loading').hide();
}
function reloadDrafts(reloadcondition){
wp.hooks.addFilter('mpa_booking_reload_drafts', 'mpacf', (initialValue)=> reloadcondition);
}
function resetFileInputs(form){
form.find('.mpa-file_upload-control input[type="file"]').each(function(){
const $input=$(this);
$input.siblings('.mpa-upload-status').text('');
$input.data('uploaded', false).removeData('reset-attached').val('');
});
}
function handleFileInputChange($input){
$input.data('changed', true);
$input.siblings('.mpa-upload-status').text('');
if($input.data('uploaded')){
$input.data('uploaded', false);
}
if(!$input.val()){
$input.data('uploaded', false);
}
reloadDrafts(true);
}
function prepareFormData(form){
let formData=new FormData();
let fileCount=0;
form.find('.mpa-file_upload-control input[type=file]').each(function(){
const $input=$(this);
const files=$input.prop('files');
if(!$input.data('reset-attached')){
draft_cart_data={};
$input.data('reset-attached', true);
wp.hooks.addAction('mpa_step_checkout_reset', 'mpacf', resetFileInputs);
}
$input.on('change', function(){
handleFileInputChange($input);
});
if(!$input.val()){
wp.hooks.addFilter('mpa_booking_draft_data', 'mpacf', (cart_data)=> {
if(!cart_data.hasOwnProperty('checkout_fields')){
cart_data.checkout_fields={};}
cart_data.checkout_fields[$input.prop('name')]=null;
return cart_data;
});
reloadDrafts(false);
}
if($input.data('uploaded')){
reloadDrafts(false);
return;
}
const fileFields=$input.data('changed')===true ? $input:files;
for (let i=0; i < fileFields.length; i++){
formData.append($input.attr('name'), files[i]);
fileCount++;
}
if($input.data('changed')===true){
$input.data('changed', false);
}});
if(draft_cart_data.payment_details){
formData.append('booking_id', draft_cart_data.payment_details.booking_id);
}
formData.append('action', 'mpa_cf_uploadFile');
return { formData, fileCount };}
function handleSuccess(response, form, resolve, reject){
if(response.success&&!response.data.error){
let checkoutFields={};
reloadDrafts(true);
Object.keys(response.data).forEach(function(key){
if(key!=='confirmation_mode'){
let $input=form.find('input[name="' + key + '"]');
$input.siblings('.mpa-upload-status').text(__('Upload successful', 'mpa-checkout-fields')).removeClass('mpa-error');
if(!$input.data('uploaded')){
checkoutFields[key]=response.data[key];
$input.data('uploaded', true);
}}
});
if(response.data.confirmation_mode==='auto'){
wp.hooks.addFilter('mpa_booking_cart_data', 'mpacf', (cart_data)=> {
if(!cart_data.hasOwnProperty('checkout_fields')){
cart_data.checkout_fields={};}
Object.assign(cart_data.checkout_fields, checkoutFields);
return cart_data;
});
}else{
wp.hooks.addFilter('mpa_booking_draft_data', 'mpacf', (cart_data)=> {
draft_cart_data=cart_data;
if(!cart_data.hasOwnProperty('checkout_fields')){
cart_data.checkout_fields={};}
Object.assign(cart_data.checkout_fields, checkoutFields);
return cart_data;
});
}
resolve(response);
}else{
form.find('input[name="' + response.data.fieldWithError + '"]').siblings('.mpa-upload-status').addClass('mpa-error').text(response.data.message);
reject();
}}
function handleError(xhr, status, error, form, reject){
form.find('.mpa-file_upload-control input[type=file]').each(function(){
$(this).siblings('.mpa-upload-status').addClass('mpa-error').text(error);
});
reject(error);
}
wp.hooks.addFilter('mpa_step_checkout_maybe_submit', 'mpacf', function(promise, form){
return new Promise((resolve, reject)=> {
const { formData, fileCount }=prepareFormData(form);
if(fileCount > 0){
showLoadingIndicator(form);
formData.append('file_upload_nonce', MPAFileUploadData.fileUploadNonce);
$.ajax({
url: MPAFileUploadData.ajax_url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response){
handleSuccess(response, form, resolve, reject);
},
error: function(xhr, status, error){
handleError(xhr, status, error, form, reject);
},
complete: function(){
hideLoadingIndicator(form);
}});
}else{
resolve();
}});
});
});
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof exports?e(require("jquery")):e(window.jQuery||window.Zepto)}(function(c){function e(){}function d(e,t){f.ev.on(x+e+I,t)}function u(e,t,n,o){var i=document.createElement("div");return i.className="mfp-"+e,n&&(i.innerHTML=n),o?t&&t.appendChild(i):(i=c(i),t&&i.appendTo(t)),i}function p(e,t){f.ev.triggerHandler(x+e,t),f.st.callbacks&&(e=e.charAt(0).toLowerCase()+e.slice(1),f.st.callbacks[e])&&f.st.callbacks[e].apply(f,Array.isArray(t)?t:[t])}function m(e){return e===A&&f.currTemplate.closeBtn||(f.currTemplate.closeBtn=c(f.st.closeMarkup.replace(/%title%/g,f.st.tClose)),A=e),f.currTemplate.closeBtn}function r(){c.magnificPopup.instance||((f=new e).init(),c.magnificPopup.instance=f)}function a(){y&&(v.after(y.addClass(l)).detach(),y=null)}function i(){n&&c(document.body).removeClass(n)}function t(){i(),f.req&&f.req.abort()}var f,o,g,s,h,A,l,v,y,n,w="Close",F="BeforeClose",C="MarkupParse",b="Open",j="Change",x="mfp",I="."+x,k="mfp-ready",N="mfp-removing",T="mfp-prevent-close",P=!!window.jQuery,_=c(window),S=(c.magnificPopup={instance:null,proto:e.prototype={constructor:e,init:function(){var e=navigator.appVersion;f.isLowIE=f.isIE8=document.all&&!document.addEventListener,f.isAndroid=/android/gi.test(e),f.isIOS=/iphone|ipad|ipod/gi.test(e),f.supportsTransition=function(){var e=document.createElement("p").style,t=["ms","O","Moz","Webkit"];if(void 0!==e.transition)return!0;for(;t.length;)if(t.pop()+"Transition"in e)return!0;return!1}(),f.probablyMobile=f.isAndroid||f.isIOS||/(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent),g=c(document),f.popupsCache={}},open:function(e){if(!1===e.isObj){f.items=e.items.toArray(),f.index=0;for(var t,n=e.items,o=0;o<n.length;o++)if((t=(t=n[o]).parsed?t.el[0]:t)===e.el[0]){f.index=o;break}}else f.items=Array.isArray(e.items)?e.items:[e.items],f.index=e.index||0;if(!f.isOpen){f.types=[],h="",e.mainEl&&e.mainEl.length?f.ev=e.mainEl.eq(0):f.ev=g,e.key?(f.popupsCache[e.key]||(f.popupsCache[e.key]={}),f.currTemplate=f.popupsCache[e.key]):f.currTemplate={},f.st=c.extend(!0,{},c.magnificPopup.defaults,e),f.fixedContentPos="auto"===f.st.fixedContentPos?!f.probablyMobile:f.st.fixedContentPos,f.st.modal&&(f.st.closeOnContentClick=!1,f.st.closeOnBgClick=!1,f.st.showCloseBtn=!1,f.st.enableEscapeKey=!1),f.bgOverlay||(f.bgOverlay=u("bg").on("click"+I,function(){f.close()}),f.wrap=u("wrap").attr("tabindex",-1).attr("role","dialog").attr("aria-modal",!0).attr("aria-label","Popup Image").on("click"+I,function(e){f._checkIfClose(e.target)&&f.close()}),f.container=u("container",f.wrap)),f.contentContainer=u("content"),f.st.preloader&&(f.preloader=u("preloader",f.container,f.st.tLoading));var i=c.magnificPopup.modules;for(o=0;o<i.length;o++){var r=(r=i[o]).charAt(0).toUpperCase()+r.slice(1);f["init"+r].call(f)}p("BeforeOpen"),f.st.showCloseBtn&&(f.st.closeBtnInside?(d(C,function(e,t,n,o){n.close_replaceWith=m(o.type)}),h+=" mfp-close-btn-in"):f.wrap.append(m())),f.st.alignTop&&(h+=" mfp-align-top"),f.fixedContentPos?f.wrap.css({overflow:f.st.overflowY,overflowX:"hidden",overflowY:f.st.overflowY}):f.wrap.css({top:_.scrollTop(),position:"absolute"}),!1!==f.st.fixedBgPos&&("auto"!==f.st.fixedBgPos||f.fixedContentPos)||f.bgOverlay.css({height:g.height(),position:"absolute"}),f.st.enableEscapeKey&&g.on("keyup"+I,function(e){27===e.keyCode&&f.close()}),_.on("resize"+I,function(){f.updateSize()}),f.st.closeOnContentClick||(h+=" mfp-auto-cursor"),h&&f.wrap.addClass(h);var a=f.wH=_.height(),s={},l=(f.fixedContentPos&&f._hasScrollBar(a)&&(l=f._getScrollbarSize())&&(s.marginRight=l),f.fixedContentPos&&(f.isIE7?c("body, html").css("overflow","hidden"):s.overflow="hidden"),f.st.mainClass);return f.isIE7&&(l+=" mfp-ie7"),l&&f._addClassToMFP(l),f.updateItemHTML(),p("BuildControls"),c("html").css(s),f.bgOverlay.add(f.wrap).prependTo(f.st.prependTo||c(document.body)),f._lastFocusedEl=document.activeElement,setTimeout(function(){f.content?(f._addClassToMFP(k),f._setFocus()):f.bgOverlay.addClass(k),g.on("focusin"+I,f._onFocusIn)},16),f.isOpen=!0,f.updateSize(a),p(b),e}f.updateItemHTML()},close:function(){f.isOpen&&(p(F),f.isOpen=!1,f.st.removalDelay&&!f.isLowIE&&f.supportsTransition?(f._addClassToMFP(N),setTimeout(function(){f._close()},f.st.removalDelay)):f._close())},_close:function(){p(w);var e=N+" "+k+" ";f.bgOverlay.detach(),f.wrap.detach(),f.container.empty(),f.st.mainClass&&(e+=f.st.mainClass+" "),f._removeClassFromMFP(e),f.fixedContentPos&&(e={marginRight:""},f.isIE7?c("body, html").css("overflow",""):e.overflow="",c("html").css(e)),g.off("keyup.mfp focusin"+I),f.ev.off(I),f.wrap.attr("class","mfp-wrap").removeAttr("style"),f.bgOverlay.attr("class","mfp-bg"),f.container.attr("class","mfp-container"),!f.st.showCloseBtn||f.st.closeBtnInside&&!0!==f.currTemplate[f.currItem.type]||f.currTemplate.closeBtn&&f.currTemplate.closeBtn.detach(),f.st.autoFocusLast&&f._lastFocusedEl&&c(f._lastFocusedEl).trigger("focus"),f.currItem=null,f.content=null,f.currTemplate=null,f.prevHeight=0,p("AfterClose")},updateSize:function(e){var t;f.isIOS?(t=document.documentElement.clientWidth/window.innerWidth,t=window.innerHeight*t,f.wrap.css("height",t),f.wH=t):f.wH=e||_.height(),f.fixedContentPos||f.wrap.css("height",f.wH),p("Resize")},updateItemHTML:function(){var e=f.items[f.index],t=(f.contentContainer.detach(),f.content&&f.content.detach(),(e=e.parsed?e:f.parseEl(f.index)).type),n=(p("BeforeChange",[f.currItem?f.currItem.type:"",t]),f.currItem=e,f.currTemplate[t]||(n=!!f.st[t]&&f.st[t].markup,p("FirstMarkupParse",n),f.currTemplate[t]=!n||c(n)),s&&s!==e.type&&f.container.removeClass("mfp-"+s+"-holder"),f["get"+t.charAt(0).toUpperCase()+t.slice(1)](e,f.currTemplate[t]));f.appendContent(n,t),e.preloaded=!0,p(j,e),s=e.type,f.container.prepend(f.contentContainer),p("AfterChange")},appendContent:function(e,t){(f.content=e)?f.st.showCloseBtn&&f.st.closeBtnInside&&!0===f.currTemplate[t]?f.content.find(".mfp-close").length||f.content.append(m()):f.content=e:f.content="",p("BeforeAppend"),f.container.addClass("mfp-"+t+"-holder"),f.contentContainer.append(f.content)},parseEl:function(e){var t,n=f.items[e];if((n=n.tagName?{el:c(n)}:(t=n.type,{data:n,src:n.src})).el){for(var o=f.types,i=0;i<o.length;i++)if(n.el.hasClass("mfp-"+o[i])){t=o[i];break}n.src=n.el.attr("data-mfp-src"),n.src||(n.src=n.el.attr("href"))}return n.type=t||f.st.type||"inline",n.index=e,n.parsed=!0,f.items[e]=n,p("ElementParse",n),f.items[e]},addGroup:function(t,n){function e(e){e.mfpEl=this,f._openClick(e,t,n)}var o="click.magnificPopup";(n=n||{}).mainEl=t,n.items?(n.isObj=!0,t.off(o).on(o,e)):(n.isObj=!1,n.delegate?t.off(o).on(o,n.delegate,e):(n.items=t).off(o).on(o,e))},_openClick:function(e,t,n){var o=(void 0!==n.midClick?n:c.magnificPopup.defaults).midClick;if(o||!(2===e.which||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey)){o=(void 0!==n.disableOn?n:c.magnificPopup.defaults).disableOn;if(o)if("function"==typeof o){if(!o.call(f))return!0}else if(_.width()<o)return!0;e.type&&(e.preventDefault(),f.isOpen)&&e.stopPropagation(),n.el=c(e.mfpEl),n.delegate&&(n.items=t.find(n.delegate)),f.open(n)}},updateStatus:function(e,t){var n;f.preloader&&(o!==e&&f.container.removeClass("mfp-s-"+o),n={status:e,text:t=t||"loading"!==e?t:f.st.tLoading},p("UpdateStatus",n),e=n.status,t=n.text,f.st.allowHTMLInStatusIndicator?f.preloader.html(t):f.preloader.text(t),f.preloader.find("a").on("click",function(e){e.stopImmediatePropagation()}),f.container.addClass("mfp-s-"+e),o=e)},_checkIfClose:function(e){if(!c(e).closest("."+T).length){var t=f.st.closeOnContentClick,n=f.st.closeOnBgClick;if(t&&n)return!0;if(!f.content||c(e).closest(".mfp-close").length||f.preloader&&e===f.preloader[0])return!0;if(e===f.content[0]||c.contains(f.content[0],e)){if(t)return!0}else if(n&&c.contains(document,e))return!0;return!1}},_addClassToMFP:function(e){f.bgOverlay.addClass(e),f.wrap.addClass(e)},_removeClassFromMFP:function(e){this.bgOverlay.removeClass(e),f.wrap.removeClass(e)},_hasScrollBar:function(e){return(f.isIE7?g.height():document.body.scrollHeight)>(e||_.height())},_setFocus:function(){(f.st.focus?f.content.find(f.st.focus).eq(0):f.wrap).trigger("focus")},_onFocusIn:function(e){if(e.target!==f.wrap[0]&&!c.contains(f.wrap[0],e.target))return f._setFocus(),!1},_parseMarkup:function(i,e,t){var r;t.data&&(e=c.extend(t.data,e)),p(C,[i,e,t]),c.each(e,function(e,t){if(void 0===t||!1===t)return!0;var n,o;1<(r=e.split("_")).length?0<(n=i.find(I+"-"+r[0])).length&&("replaceWith"===(o=r[1])?n[0]!==t[0]&&n.replaceWith(t):"img"===o?n.is("img")?n.attr("src",t):n.replaceWith(c("<img>").attr("src",t).attr("class",n.attr("class"))):n.attr(r[1],t)):f.st.allowHTMLInTemplate?i.find(I+"-"+e).html(t):i.find(I+"-"+e).text(t)})},_getScrollbarSize:function(){var e;return void 0===f.scrollbarSize&&((e=document.createElement("div")).style.cssText="width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;",document.body.appendChild(e),f.scrollbarSize=e.offsetWidth-e.clientWidth,document.body.removeChild(e)),f.scrollbarSize}},modules:[],open:function(e,t){return r(),(e=e?c.extend(!0,{},e):{}).isObj=!0,e.index=t||0,this.instance.open(e)},close:function(){return c.magnificPopup.instance&&c.magnificPopup.instance.close()},registerModule:function(e,t){t.options&&(c.magnificPopup.defaults[e]=t.options),c.extend(this.proto,t.proto),this.modules.push(e)},defaults:{disableOn:0,key:null,midClick:!1,mainClass:"",preloader:!0,focus:"",closeOnContentClick:!1,closeOnBgClick:!0,closeBtnInside:!0,showCloseBtn:!0,enableEscapeKey:!0,modal:!1,alignTop:!1,removalDelay:0,prependTo:null,fixedContentPos:"auto",fixedBgPos:"auto",overflowY:"auto",closeMarkup:'<button title="%title%" type="button" class="mfp-close" aria-label="%title%"><span aria-hidden="true">&times;</span></button>',tClose:"Close (Esc)",tLoading:"Loading...",autoFocusLast:!0,allowHTMLInStatusIndicator:!1,allowHTMLInTemplate:!1}},c.fn.magnificPopup=function(e){r();var t,n,o,i=c(this);return"string"==typeof e?"open"===e?(t=P?i.data("magnificPopup"):i[0].magnificPopup,n=parseInt(arguments[1],10)||0,o=t.items?t.items[n]:(o=i,(o=t.delegate?o.find(t.delegate):o).eq(n)),f._openClick({mfpEl:o},i,t)):f.isOpen&&f[e].apply(f,Array.prototype.slice.call(arguments,1)):(e=c.extend(!0,{},e),P?i.data("magnificPopup",e):i[0].magnificPopup=e,f.addGroup(i,e)),i},"inline"),E=(c.magnificPopup.registerModule(S,{options:{hiddenClass:"hide",markup:"",tNotFound:"Content not found"},proto:{initInline:function(){f.types.push(S),d(w+"."+S,function(){a()})},getInline:function(e,t){var n,o,i;return a(),e.src?(n=f.st.inline,(o=c(e.src)).length?((i=o[0].parentNode)&&i.tagName&&(v||(l=n.hiddenClass,v=u(l),l="mfp-"+l),y=o.after(v).detach().removeClass(l)),f.updateStatus("ready")):(f.updateStatus("error",n.tNotFound),o=c("<div>")),e.inlineElement=o):(f.updateStatus("ready"),f._parseMarkup(t,{},e),t)}}}),"ajax");c.magnificPopup.registerModule(E,{options:{settings:null,cursor:"mfp-ajax-cur",tError:"The content could not be loaded."},proto:{initAjax:function(){f.types.push(E),n=f.st.ajax.cursor,d(w+"."+E,t),d("BeforeChange."+E,t)},getAjax:function(o){n&&c(document.body).addClass(n),f.updateStatus("loading");var e=c.extend({url:o.src,success:function(e,t,n){e={data:e,xhr:n};p("ParseAjax",e),f.appendContent(c(e.data),E),o.finished=!0,i(),f._setFocus(),setTimeout(function(){f.wrap.addClass(k)},16),f.updateStatus("ready"),p("AjaxContentAdded")},error:function(){i(),o.finished=o.loadError=!0,f.updateStatus("error",f.st.ajax.tError.replace("%url%",o.src))}},f.st.ajax.settings);return f.req=c.ajax(e),""}}});var z;c.magnificPopup.registerModule("image",{options:{markup:'<div class="mfp-figure"><div class="mfp-close"></div><figure><div class="mfp-img"></div><figcaption><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></figcaption></figure></div>',cursor:"mfp-zoom-out-cur",titleSrc:"title",verticalFit:!0,tError:"The image could not be loaded."},proto:{initImage:function(){var e=f.st.image,t=".image";f.types.push("image"),d(b+t,function(){"image"===f.currItem.type&&e.cursor&&c(document.body).addClass(e.cursor)}),d(w+t,function(){e.cursor&&c(document.body).removeClass(e.cursor),_.off("resize"+I)}),d("Resize"+t,f.resizeImage),f.isLowIE&&d("AfterChange",f.resizeImage)},resizeImage:function(){var e,t=f.currItem;t&&t.img&&f.st.image.verticalFit&&(e=0,f.isLowIE&&(e=parseInt(t.img.css("padding-top"),10)+parseInt(t.img.css("padding-bottom"),10)),t.img.css("max-height",f.wH-e))},_onImageHasSize:function(e){e.img&&(e.hasSize=!0,z&&clearInterval(z),e.isCheckingImgSize=!1,p("ImageHasSize",e),e.imgHidden)&&(f.content&&f.content.removeClass("mfp-loading"),e.imgHidden=!1)},findImageSize:function(t){function n(e){z&&clearInterval(z),z=setInterval(function(){0<i.naturalWidth?f._onImageHasSize(t):(200<o&&clearInterval(z),3===++o?n(10):40===o?n(50):100===o&&n(500))},e)}var o=0,i=t.img[0];n(1)},getImage:function(e,t){function n(){e&&(e.img.off(".mfploader"),e===f.currItem&&(f._onImageHasSize(e),f.updateStatus("error",a.tError.replace("%url%",e.src))),e.hasSize=!0,e.loaded=!0,e.loadError=!0)}function o(){e&&(e.img[0].complete?(e.img.off(".mfploader"),e===f.currItem&&(f._onImageHasSize(e),f.updateStatus("ready")),e.hasSize=!0,e.loaded=!0,p("ImageLoadComplete")):++r<200?setTimeout(o,100):n())}var i,r=0,a=f.st.image,s=t.find(".mfp-img");return s.length&&((i=document.createElement("img")).className="mfp-img",e.el&&e.el.find("img").length&&(i.alt=e.el.find("img").attr("alt")),e.img=c(i).on("load.mfploader",o).on("error.mfploader",n),i.src=e.src,s.is("img")&&(e.img=e.img.clone()),0<(i=e.img[0]).naturalWidth?e.hasSize=!0:i.width||(e.hasSize=!1)),f._parseMarkup(t,{title:function(e){if(e.data&&void 0!==e.data.title)return e.data.title;var t=f.st.image.titleSrc;if(t){if("function"==typeof t)return t.call(f,e);if(e.el)return e.el.attr(t)||""}return""}(e),img_replaceWith:e.img},e),f.resizeImage(),e.hasSize?(z&&clearInterval(z),e.loadError?(t.addClass("mfp-loading"),f.updateStatus("error",a.tError.replace("%url%",e.src))):(t.removeClass("mfp-loading"),f.updateStatus("ready"))):(f.updateStatus("loading"),e.loading=!0,e.hasSize||(e.imgHidden=!0,t.addClass("mfp-loading"),f.findImageSize(e))),t}}});function O(e){var t;f.currTemplate[L]&&(t=f.currTemplate[L].find("iframe")).length&&(e||(t[0].src="//about:blank"),f.isIE8)&&t.css("display",e?"block":"none")}function M(e){var t=f.items.length;return t-1<e?e-t:e<0?t+e:e}function D(e,t,n){return e.replace(/%curr%/gi,t+1).replace(/%total%/gi,n)}c.magnificPopup.registerModule("zoom",{options:{enabled:!1,easing:"ease-in-out",duration:300,opener:function(e){return e.is("img")?e:e.find("img")}},proto:{initZoom:function(){var e,t,n,o,i,r,a=f.st.zoom,s=".zoom";a.enabled&&f.supportsTransition&&(t=a.duration,n=function(e){var e=e.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),t="all "+a.duration/1e3+"s "+a.easing,n={position:"fixed",zIndex:9999,left:0,top:0,"-webkit-backface-visibility":"hidden"},o="transition";return n["-webkit-"+o]=n["-moz-"+o]=n["-o-"+o]=n[o]=t,e.css(n),e},o=function(){f.content.css("visibility","visible")},d("BuildControls"+s,function(){f._allowZoom()&&(clearTimeout(i),f.content.css("visibility","hidden"),(e=f._getItemToZoom())?((r=n(e)).css(f._getOffset()),f.wrap.append(r),i=setTimeout(function(){r.css(f._getOffset(!0)),i=setTimeout(function(){o(),setTimeout(function(){r.remove(),e=r=null,p("ZoomAnimationEnded")},16)},t)},16)):o())}),d(F+s,function(){if(f._allowZoom()){if(clearTimeout(i),f.st.removalDelay=t,!e){if(!(e=f._getItemToZoom()))return;r=n(e)}r.css(f._getOffset(!0)),f.wrap.append(r),f.content.css("visibility","hidden"),setTimeout(function(){r.css(f._getOffset())},16)}}),d(w+s,function(){f._allowZoom()&&(o(),r&&r.remove(),e=null)}))},_allowZoom:function(){return"image"===f.currItem.type},_getItemToZoom:function(){return!!f.currItem.hasSize&&f.currItem.img},_getOffset:function(e){var e=e?f.currItem.img:f.st.zoom.opener(f.currItem.el||f.currItem),t=e.offset(),n=parseInt(e.css("padding-top"),10),o=parseInt(e.css("padding-bottom"),10),e=(t.top-=c(window).scrollTop()-n,{width:e.width(),height:(P?e.innerHeight():e[0].offsetHeight)-o-n});return(B=void 0===B?void 0!==document.createElement("p").style.MozTransform:B)?e["-moz-transform"]=e.transform="translate("+t.left+"px,"+t.top+"px)":(e.left=t.left,e.top=t.top),e}}});var B,L="iframe",H=(c.magnificPopup.registerModule(L,{options:{markup:'<div class="mfp-iframe-scaler"><div class="mfp-close"></div><iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe></div>',srcAction:"iframe_src",patterns:{youtube:{index:"youtube.com",id:"v=",src:"//www.youtube.com/embed/%id%?autoplay=1"},youtu_be:{index:"youtu.be",id:"/",src:"//www.youtube.com/embed/%id%?autoplay=1"},youtube_nocookie:{index:"youtube-nocookie.com",id:"/",src:"//www.youtube-nocookie.com/embed/%id%?autoplay=1"},vimeo:{index:"vimeo.com/",id:"/",src:"//player.vimeo.com/video/%id%?autoplay=1"},gmaps:{index:"//maps.google.",src:"%id%&output=embed"}}},proto:{initIframe:function(){f.types.push(L),d("BeforeChange",function(e,t,n){t!==n&&(t===L?O():n===L&&O(!0))}),d(w+"."+L,function(){O()})},getIframe:function(e,t){var n=e.src,o=f.st.iframe,i=(c.each(o.patterns,function(){if(-1<n.indexOf(this.index))return this.id&&(n="string"==typeof this.id?n.substr(n.lastIndexOf(this.id)+this.id.length,n.length):this.id.call(this,n)),n=this.src.replace("%id%",n),!1}),{});return o.srcAction&&(i[o.srcAction]=n),f._parseMarkup(t,i,e),f.updateStatus("ready"),t}}}),c.magnificPopup.registerModule("gallery",{options:{enabled:!1,arrowMarkup:'<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%",langDir:null,loop:!0},proto:{initGallery:function(){var r=f.st.gallery,e=".mfp-gallery";if(f.direction=!0,!r||!r.enabled)return!1;r.langDir||(r.langDir=document.dir||"ltr"),h+=" mfp-gallery",d(b+e,function(){r.navigateByImgClick&&f.wrap.on("click"+e,".mfp-img",function(){if(1<f.items.length)return f.next(),!1}),g.on("keydown"+e,function(e){37===e.keyCode?"rtl"===r.langDir?f.next():f.prev():39===e.keyCode&&("rtl"===r.langDir?f.prev():f.next())}),f.updateGalleryButtons()}),d("UpdateStatus"+e,function(){f.updateGalleryButtons()}),d("UpdateStatus"+e,function(e,t){t.text&&(t.text=D(t.text,f.currItem.index,f.items.length))}),d(C+e,function(e,t,n,o){var i=f.items.length;n.counter=1<i?D(r.tCounter,o.index,i):""}),d("BuildControls"+e,function(){var e,t,n,o,i;1<f.items.length&&r.arrows&&!f.arrowLeft&&(t="rtl"===r.langDir?(i=r.tNext,e=r.tPrev,o="next","prev"):(i=r.tPrev,e=r.tNext,o="prev","next"),n=r.arrowMarkup,o=f.arrowLeft=c(n.replace(/%title%/gi,i).replace(/%action%/gi,o).replace(/%dir%/gi,"left")).attr("aria-label",i).addClass(T),i=f.arrowRight=c(n.replace(/%title%/gi,e).replace(/%action%/gi,t).replace(/%dir%/gi,"right")).attr("aria-label",e).addClass(T),"rtl"===r.langDir?(f.arrowNext=o,f.arrowPrev=i):(f.arrowNext=i,f.arrowPrev=o),o.on("click",function(){"rtl"===r.langDir?f.next():f.prev()}),i.on("click",function(){"rtl"===r.langDir?f.prev():f.next()}),f.container.append(o.add(i)),f.container.attr("role","region").attr("aria-label","carousel"))}),d(j+e,function(){f._preloadTimeout&&clearTimeout(f._preloadTimeout),f._preloadTimeout=setTimeout(function(){f.preloadNearbyImages(),f._preloadTimeout=null},16)}),d(w+e,function(){g.off(e),f.wrap.off("click"+e),f.arrowRight=f.arrowLeft=null})},next:function(){var e=M(f.index+1);if(!f.st.gallery.loop&&0===e)return!1;f.direction=!0,f.index=e,f.updateItemHTML()},prev:function(){var e=f.index-1;if(!f.st.gallery.loop&&e<0)return!1;f.direction=!1,f.index=M(e),f.updateItemHTML()},goTo:function(e){f.direction=e>=f.index,f.index=e,f.updateItemHTML()},preloadNearbyImages:function(){for(var e=f.st.gallery.preload,t=Math.min(e[0],f.items.length),n=Math.min(e[1],f.items.length),o=1;o<=(f.direction?n:t);o++)f._preloadItem(f.index+o);for(o=1;o<=(f.direction?t:n);o++)f._preloadItem(f.index-o)},_preloadItem:function(e){var t;e=M(e),f.items[e].preloaded||((t=f.items[e]).parsed||(t=f.parseEl(e)),p("LazyLoad",t),"image"===t.type&&(t.img=c('<img class="mfp-img" />').on("load.mfploader",function(){t.hasSize=!0}).on("error.mfploader",function(){t.hasSize=!0,t.loadError=!0,p("LazyLoadError",t)}).attr("src",t.src)),t.preloaded=!0)},updateGalleryButtons:function(){f.st.gallery.loop||"object"!=typeof f.arrowPrev||null===f.arrowPrev||(0===f.index?f.arrowPrev.hide():f.arrowPrev.show(),f.index===f.items.length-1?f.arrowNext.hide():f.arrowNext.show())}}}),"retina");c.magnificPopup.registerModule(H,{options:{replaceSrc:function(e){return e.src.replace(/\.\w+$/,function(e){return"@2x"+e})},ratio:1},proto:{initRetina:function(){var n,o;1<window.devicePixelRatio&&(n=f.st.retina,o=n.ratio,1<(o=isNaN(o)?o():o))&&(d("ImageHasSize."+H,function(e,t){t.img.css({"max-width":t.img[0].naturalWidth/o,width:"100%"})}),d("ElementParse."+H,function(e,t){t.src=n.replaceSrc(t,o)}))}}}),r()});
(r=>{FLTheme={init:function(){this._bind()},_bind:function(){var a=this;r(".navbar-toggle").on("click",this.navbarToggleClick),0!=r(".fl-page-bar-nav ul.sub-menu").length&&(this._setupDropDowns(),this._enableTopNavDropDowns()),0!=r(".fl-page-nav ul.sub-menu").length&&(r(window).on("resize.fl-page-nav-sub-menu",r.throttle(500,this._enablePageNavDropDowns)),this._setupDropDowns(),this._enablePageNavDropDowns()),0!=r(".fl-page-nav ul.menu").length&&(r(".fl-page-nav ul.menu").find(".menu-item").on("click",'> a[href*="#"]:not([href="#"])',this._setupCurrentNavItem),this._setupCurrentNavItem()),0!=r(".fl-page-nav-search").length&&r(".fl-page-nav-search a.fa-search").on("click",this._toggleNavSearch),0!=r(".fl-nav-vertical").length&&(r(window).on("resize",r.throttle(500,this._navVertical)),this._navVertical()),0!=r(".fl-fixed-width.fl-nav-vertical-right").length&&(r(window).on("resize",r.throttle(500,this._updateVerticalRightPos)),this._updateVerticalRightPos()),0!=r(".fl-page-nav-centered-inline-logo").length&&(r(window).on("resize",r.throttle(500,this._centeredInlineLogo)),this._centeredInlineLogo()),0!=r("body.fl-nav-left").length&&(r(window).on("resize",r.throttle(500,this._navLeft)),this._navLeft()),0!=r("body.fl-shrink").length&&0==r("html.fl-builder-edit").length&&(r(window).on("resize",r.throttle(500,this._shrinkHeaderEnable)),this._shrinkHeaderInit(),this._shrinkHeaderEnable()),0!=r(".fl-page-header-fixed").length&&(r(window).on("resize.fl-page-header-fixed",r.throttle(500,this._enableFixedHeader)),this._enableFixedHeader()),0!=r("body.fl-fixed-header").length&&0==r("html.fl-builder-edit").length&&(r(window).on("resize",r.throttle(500,this._fixedHeader)),this._fixedHeader()),0!=r("body.fl-scroll-header").length&&0==r("html.fl-builder-edit").length&&(r(window).on("resize",r.throttle(500,this._scrollHeader)),this._scrollHeader()),0!=r(".fl-page-header-primary").find("li.mega-menu").length&&(r(window).on("resize",r.throttle(500,this._megaMenu)),this._megaMenu()),0!=r(".fl-page-header-fixed").length&&(r(window).on("scroll.fl-mega-menu-on-scroll",r.throttle(500,this._megaMenuOnScroll)),r(window).on("resize.fl-mega-menu-on-scroll",r.throttle(500,this._megaMenuOnScroll))),0!=r("html.fl-builder-edit").length&&this._fixedHeadersWhenBuilderActive(),0!=r("body.fl-nav-mobile-offcanvas").length&&0!=!r("html.fl-builder-edit").length&&(r(window).on("resize",r.throttle(500,this._setupMobileNavLayout)),this._setupMobileNavLayout(),this._toggleMobileNavLayout()),r("body").on("click",this.closeMenu),r(".fl-theme-menu > li:last-child").on("focusout",function(e){void 0!==r(e.relatedTarget)[0]&&"nav-link"===r(e.relatedTarget)[0].className||a.closeMenu(e)}),0!=r(".fl-full-width.fl-footer-effect").length&&(r(window).on("resize",r.throttle(500,this._footerEffect)),this._footerEffect()),0!=r("body.fl-scroll-to-top").length&&this._toTop(),void 0!==r("body").magnificPopup&&this._enableLightbox(),void 0===r.fn.fitVids||r("body").hasClass("fl-builder")||this._enableFitVids(),FLTheme._navBackiosFix(),this._initSmoothScroll()},_isMobile:function(){return"ontouchstart"in window||0<navigator.maxTouchPoints||0<navigator.msMaxTouchPoints||/Mobile|Android|Silk\/|Kindle|BlackBerry|Opera Mini|Opera Mobi|webOS/i.test(navigator.userAgent)},_initRetinaImages:function(){1<(window.devicePixelRatio||1)&&r("img[data-retina]").each(FLTheme._convertImageToRetina)},_convertImageToRetina:function(){var a=r(this),l=new Image,e=a.attr("src"),n=a.data("retina");if(void 0===(e=void 0===e?a.data("cfsrc"):e))return!1;var t=e.split(".").pop();""!=n&&(l.onload=function(){var e=l.width;l.height;"svg"==t&&(e=a.width(),a.height()),a.width(e),a.attr("src",n)},l.src=e)},_initMobileHeaderLogo:function(){this._enableMobileLogo(),r(window).on("resize",r.proxy(this._enableMobileLogo,this))},_enableMobileLogo:function(){var e,a=r(window),l=r(".fl-page-header-logo").find("img[data-mobile]"),n=null,t=null;0!==l.length&&r(l).each(function(){t=new Image,n=r(this),src=n.attr("src"),width=n.data("width"),height=n.data("height"),e=n.data("mobile"),mobileWidth=n.data("mobile-width"),mobileHeight=n.data("mobile-height"),n.attr("src",""),n.attr("data-src",src),a.width()<window.themeopts.mobile_breakpoint?""!=e&&(t.onload=function(){n.attr("src",e),n.attr("width",mobileWidth),n.attr("height",mobileHeight),n.css("width","")},t.src=src,n.show()):void 0!==n.data("src")&&(n.attr("src",n.data("src")),n.attr("width",width),n.attr("height",height),n.css("width",width))})},navbarToggleClick:function(e){var a,l=r("body").hasClass("fl-nav-mobile-offcanvas")?"flyout":"dropdown";"dropdown"==l?((a=r(e.target).closest(".fl-page-nav").find(".fl-page-nav-collapse")).toggleClass("collapse"),a.toggleClass("in")):"flyout"==l&&r(".fl-page").toggleClass("fl-nav-offcanvas-active"),e.stopPropagation()},closeMenu:function(e){var a=r("body").hasClass("fl-nav-mobile-offcanvas")?"flyout":"dropdown",l=r(".fl-page-nav-collapse").hasClass("in"),n=r(".fl-page").hasClass("fl-nav-offcanvas-active"),t=r(e.target).is(".mega-toggle-animated-inner, .mega-menu-toggle-animated-block, .mega-toggle-animated-box, .mega-toggle-blocks-right");void 0===e||void 0===e.target||t||("dropdown"==a&&l?r(".navbar-collapse.in").closest(".fl-page-nav").find(".navbar-toggle").trigger("click"):"flyout"==a&&n&&r(".fl-offcanvas-close").trigger("click"))},_setupDropDowns:function(){r("ul.sub-menu").each(function(){r(this).closest("li").find("a").first().attr("aria-haspopup","true")})},_enableTopNavDropDowns:function(){var e=r(".fl-page-bar-nav"),a=e.find(" > li"),e=e.find("> li").has("> ul.sub-menu").find(".fl-submenu-toggle-icon");!FLTheme._isMobile()||!1!==/iPhone|iPad/i.test(navigator.userAgent)?a.hover(FLTheme._navItemMouseover,FLTheme._navItemMouseout):(a.hover(function(){},FLTheme._navItemMouseout),e.on("click",FLTheme._navSubMenuToggleClick))},_navBackiosFix:function(){!1!==(ipad=null!==navigator.userAgent.match("iPhone|iPad")&&0<r(".menu-item-has-children").length)&&(window.onpageshow=function(e){e.persisted&&window.location.reload()})},_initSmoothScroll:function(){var e;"undefined"==typeof FLBuilderLayout||void 0!==window.themeopts.smooth&&"disabled"===window.themeopts.smooth||(e=(e=location.hash).replace(/(:|\!|\.|\[|\]|,|=|@|\/)/g,"\\$1"))&&r(e).length&&setTimeout(function(){window.scrollTo(0,0),FLBuilderLayout._scrollToElement(r(e))},1)},_enablePageNavDropDowns:function(){r(".fl-page-header").each(FLTheme._enablePageNavDropDown)},_enablePageNavDropDown:function(){var e=r(this).find(".fl-page-nav .fl-page-nav-collapse"),a=e.find("ul li"),l=e.find("li").has("> ul.sub-menu").find("> a"),n=(e.find("li").has("> ul.sub-menu").find(".fl-submenu-toggle-icon"),e.find("> ul > li").has("ul.sub-menu"));r(".fl-page-nav .navbar-toggle").is(":visible")?(a.off("mouseenter mouseleave"),(n=r("body").hasClass("fl-submenu-toggle")?e.find("> ul li").has("ul.sub-menu"):n).find("> a").off().on("click",FLTheme._navItemClickMobile),n.find(".fl-submenu-toggle-icon").off().on("click",FLTheme._navItemClickMobile),e.find(".menu").on("click",'.menu-item > a[href*="#"]',FLTheme._toggleForMobile),l.off("click",FLTheme._navSubMenuToggleClick)):(e.find("a").off("click",FLTheme._navItemClickMobile),e.find("a").off("click",FLTheme._toggleForMobile),e.find(".fl-submenu-toggle-icon").off("click",FLTheme._navItemClickMobile),e.removeClass("in").addClass("collapse"),a.removeClass("fl-mobile-sub-menu-open"),a.find("a").width(0).width("auto"),FLTheme._isMobile()?(a.hover(function(){},FLTheme._navItemMouseout),l.on("click",FLTheme._navSubMenuToggleClick)):(a.keydown(function(e){9===e.keyCode&&(el=r(this),(focused=el.find(":focus")).parent().is(":last-child")&&(sub=focused.parent().find("ul.sub-menu").first(),mega=focused.parent().parent().parent().parent().parent().hasClass("mega-menu"),mega_last=focused.parent().parent().parent().is(":last-child"),0<sub.length?sub.trigger("mouseenter"):mega&&!mega_last||el.trigger("mouseleave")),(parent=focused.closest("ul.sub-menu").parent()).hasClass("fl-sub-menu-open")||focused.trigger("mouseenter"))}),a.hover(FLTheme._navItemMouseover,FLTheme._navItemMouseout)))},_navItemClickMobile:function(e){var a,l=r(this).closest(".fl-page-nav-collapse"),n=r(this).closest("li"),t=r(this).attr("href"),i=n.find("ul.sub-menu"),o=r(e.target).hasClass("fl-submenu-toggle-icon"),s=null;t&&"#"!==t&&(a=t.split("#")[1],0<r("body").find("#"+a).length)&&n.hasClass("fl-mobile-sub-menu-open")&&((el=r(this).parent().closest("nav").find(".navbar-toggle")).trigger("click"),"undefined"!=typeof FLBuilderLayout)&&void 0===window.themeopts.smooth&&"disabled"!==window.themeopts.smooth&&setTimeout(function(){window.scrollTo(0,0),FLBuilderLayout._scrollToElement(r("#"+a))},1),("#"==t||o)&&n.hasClass("fl-mobile-sub-menu-open")?(e.preventDefault(),n.removeClass("fl-mobile-sub-menu-open"),i.hide()):n.hasClass("fl-mobile-sub-menu-open")||(e.preventDefault(),n.addClass("fl-mobile-sub-menu-open"),o&&0===r(".fl-submenu-toggle").length&&(s=i.find("li.menu-item-has-children")).addClass("fl-mobile-sub-menu-open"),i.fadeIn(200)),0!=r(".fl-nav-collapse-menu").length&&l.find("li.fl-mobile-sub-menu-open").not(r(this).parents(".fl-mobile-sub-menu-open")).not(s).removeClass("fl-mobile-sub-menu-open").find("ul.sub-menu").hide(),e.stopPropagation()},_setupCurrentNavItem:function(e){var a=r(".fl-page-nav .navbar-nav"),e=void 0!==e?r(e.target).prop("hash"):window.location.hash,l=(e=e.replace(/(:|\!|\.|\[|\]|,|=|@|\/)/g,"\\$1")).length?a.find("a[href*=\\"+e+"]:not([href=\\#])"):null,a=a.closest(".fl-page-nav").find(".fl-offcanvas-close");null!=l&&0<r("body").find(e).length&&(r(".current-menu-item").removeClass("current-menu-item"),l.parent().addClass("current-menu-item"),a)&&a.trigger("click")},_navItemMouseover:function(){var e,a,l,n,t,i,o;0===r(this).find("ul.sub-menu").length||(a=(e=r(this)).parent(),n=(l=e.find("ul.sub-menu")).width(),t=r(window).width(),(o=i=0)!==e.closest(".fl-sub-menu-right").length?e.addClass("fl-sub-menu-right"):r("body").hasClass("rtl")?(a.is("ul.sub-menu")?a.offset().left-n:e.offset().left-n)<=0&&e.addClass("fl-sub-menu-right"):t<(a.is("ul.sub-menu")?a.offset().left+2*n:e.offset().left+n)&&e.addClass("fl-sub-menu-right"),e.addClass("fl-sub-menu-open"),e.hasClass("hide-heading")||(l.hide(),l.stop().fadeIn(200)),FLTheme._hideNavSearch(),0===e.closest(".fl-page-nav-collapse").length)||!e.hasClass("mega-menu")||0<e.find(".mega-menu-spacer").length||(l.first().before('<div class="mega-menu-spacer"></div>'),i=e.find(".mega-menu-spacer").offset().top,o=l.first().offset().top,e.find(".mega-menu-spacer").css("padding-top",Math.floor(parseInt(o-i))+"px"))},_navItemMouseout:function(){var e=r(this),a=e.find("ul.sub-menu");e.hasClass("hide-heading")?FLTheme._navItemMouseoutComplete():a.stop().fadeOut({duration:200,done:FLTheme._navItemMouseoutComplete})},_navItemMouseoutComplete:function(){var e=r(this).parent();e.removeClass("fl-sub-menu-open"),e.removeClass("fl-sub-menu-right"),0<e.find(".mega-menu-spacer").length&&e.find(".mega-menu-spacer").remove(),r(this).show()},_navSubMenuToggleClick:function(e){var a=r(this).closest("li").eq(0);a.hasClass("fl-sub-menu-open")||(FLTheme._navItemMouseover.apply(a[0]),e.preventDefault())},_toggleForMobile:function(e){var a=r(".fl-page-nav .fl-page-nav-collapse"),l=r(this).attr("href"),n=r(this).closest("li").hasClass("menu-item-has-children");"#"!==l&&(l=l.split("#")[1],0<r("body").find("#"+l).length)&&!n&&(r.isFunction(a.collapse)?a.collapse("hide"):(el=r(this).parent().closest("nav").find(".navbar-toggle")).trigger("click"))},_toggleNavSearch:function(e){var a=r(".fl-page-nav-search form");e.preventDefault(),a.is(":visible")?a.stop().fadeOut(200):(a.stop().fadeIn(200),r("body").on("click.fl-page-nav-search",FLTheme._hideNavSearch),r(".fl-page-nav-search .fl-search-input").focus())},_hideNavSearch:function(e){var a=r(".fl-page-nav-search form");void 0!==e&&0<r(e.target).closest(".fl-page-nav-search").length||(a.stop().fadeOut(200),r("body").off("click.fl-page-nav-search"))},_navVertical:function(){r(window).width()>=window.themeopts.medium_breakpoint&&r(".fl-page-header-primary").hasClass("fl-page-nav-toggle-visible-always")&&(r("body").toggleClass("fl-nav-vertical"),r("body").hasClass("fl-nav-vertical-left")&&r("body").toggleClass("fl-nav-vertical-left"),r("body").hasClass("fl-nav-vertical-right"))&&r("body").toggleClass("fl-nav-vertical-right")},_updateVerticalRightPos:function(){var e=(r(window).width()-r(".fl-page").width())/2;r(".fl-page-header-vertical").css("right",e)},_navLeft:function(){var e=r(window);(e.width()<window.themeopts.medium_breakpoint||r(".fl-page-header-primary").hasClass("fl-page-nav-toggle-visible-always"))&&r(".fl-page-header-primary .fl-page-logo-wrap").insertBefore(".fl-page-header-primary .fl-page-nav-col"),e.width()>=window.themeopts.medium_breakpoint&&!r(".fl-page-header-primary").hasClass("fl-page-nav-toggle-visible-always")&&r(".fl-page-header-primary .fl-page-nav-col").insertBefore(".fl-page-header-primary .fl-page-logo-wrap"),0==r(".fl-page-header-fixed").length||r(".fl-page-header-fixed").hasClass("fl-page-nav-toggle-visible-always")||r(".fl-page-header-fixed .fl-page-fixed-nav-wrap").insertBefore(".fl-page-header-fixed .fl-page-logo-wrap")},_shrinkHeaderInit:function(){var n=r(window).scrollTop(),t=r(".fl-page-header");r("body").addClass("fl-shrink-header-enabled"),"scrollRestoration"in history&&(history.scrollRestoration="manual"),r(".fl-page-header-logo").imagesLoaded(function(){var e=r(".fl-logo-img"),a=r(".fl-page-header-logo:visible .fl-logo-img").first(),l=(a=a.length?a:e.first()).length?a.height():0;!(l=void 0!==a.data("origHeight")?parseInt(a.data("origHeight")):l)&&e.length&&(l=parseInt(e.first().data("origHeight"))||46),e.css("max-height",l),setTimeout(function(){r(".fl-page-header").addClass("fl-shrink-header-transition"),250<n?t.addClass("fl-shrink-header"):t.removeClass("fl-shrink-header")},100)})},_shrinkHeaderEnable:function(){var e,a,l,n,t,i=r(window);i.width()>=window.themeopts.medium_breakpoint?(a=(e=r(".fl-page-header")).outerHeight(),(t=n=0)!=(l=r(".fl-page-bar")).length?(t=(n+=l.outerHeight())+a,0!=r("body.admin-bar").length&&(n+=32),e.css("top",n)):t=a,0<e.prevAll(".fl-builder-content").length&&(FLTheme._initThemerLayoutFix(),t=l.outerHeight()),0===r(".fl-header-padding-top-custom").length&&r(".fl-page").css("padding-top",t),r(i).on("scroll.fl-shrink-header",FLTheme._shrinkHeader)):(r(".fl-page-header").css("top",0),r(".fl-page").css("padding-top",0),r(i).off("scroll.fl-shrink-header"))},_shrinkHeader:function(){var l=r(this).scrollTop(),n=r(".fl-page-header"),t=null;r(".fl-page-header-logo").imagesLoaded(function(){t=r(".fl-logo-img");var e=r(".fl-page-header-logo:visible .fl-logo-img").first(),a=(e=e.length?e:t.first()).length?e.height():t.first().data("origHeight")||46;void 0===t.data("origHeight")&&(t.data("origHeight",a),e.length)&&!e.is(t.first())&&e.data("origHeight",a),250<l?n.addClass("fl-shrink-header"):n.removeClass("fl-shrink-header"),void 0!==n.data("original-top")&&FLTheme._fixThemerLayoutOnScroll()})},_fixedHeader:function(){var e=r(window),a=r(".fl-page-header"),l=0,n=0,t=r(".fl-page-bar"),i=0;e.width()>=window.themeopts.medium_breakpoint?(l=a.outerHeight(),0!=t.length?(n=(i=t.outerHeight())+l,0!=r("body.admin-bar").length&&(i+=32),r("html.fl-builder-edit").length,a.css("top",i)):n=l,0<a.prevAll(".fl-builder-content").length&&(FLTheme._initThemerLayoutFix(),n=t.outerHeight(),r(e).on("scroll.fl-fixed-header",FLTheme._fixThemerLayoutOnScroll)),0===r("body.fl-scroll-header").length&&0===r(".fl-header-padding-top-custom").length&&r(".fl-page").css("padding-top",n),r(e).trigger("scroll")):(r(".fl-page-header").css("top",0),r(".fl-page").css("padding-top",0),r(e).off("scroll.fl-fixed-header"))},_enableFixedHeader:function(){var e=r(window);e.width()<window.themeopts.medium_breakpoint?(e.off("scroll.fl-page-header-fixed"),r(".fl-page-header-fixed").hide()):e.on("scroll.fl-page-header-fixed",FLTheme._toggleFixedHeader)},_initThemerLayoutFix:function(){var e=r(".fl-page-header"),a=e.prevAll(".fl-builder-content"),l=0;a.length&&(e.css("position","initial"),r.each(a,function(){l+=r(this).outerHeight()}),e.data("original-top",l))},_fixThemerLayoutOnScroll:function(){var e=r(window).scrollTop(),a=r(".fl-page-header"),l=a.data("original-top");void 0!==l&&(l<=e?a.css("position","fixed"):a.css("position","initial"),"undefined"!=typeof Waypoint)&&Waypoint.refreshAll()},_toggleFixedHeader:function(){var e=r(window),a=r(".fl-page-header-fixed"),l=a.is(":visible"),n=r(".fl-page-header-primary"),t=!1;(t=0===n.length?200<e.scrollTop():e.scrollTop()>n.height()+n.offset().top)&&!l?a.stop().fadeIn(200):!t&&l&&a.stop().hide()},_centeredInlineLogo:function(){var e=r(window),a=r(".fl-page-nav-centered-inline-logo .fl-page-header-logo").eq(0),l=r(".fl-logo-centered-inline .fl-page-header-logo"),n=r(".fl-page-nav-centered-inline-logo .fl-page-nav .navbar-nav"),t=n.children("li").length,i=Math.round(t/2)-1,o=r(".fl-page-nav-centered-inline-logo .fl-page-header-row");e.width()>=window.themeopts.medium_breakpoint&&l.length<1&&!r(".fl-page-header-primary").hasClass("fl-page-nav-toggle-visible-always")&&(a.hasClass("fl-inline-logo-left")&&t%2!=0?n.children("li:nth("+i+")").before('<li class="fl-logo-centered-inline"></li>'):n.children("li:nth("+i+")").after('<li class="fl-logo-centered-inline"></li>'),n.children(".fl-logo-centered-inline").append(a)),e.width()<window.themeopts.medium_breakpoint&&(r(".fl-logo-centered-inline").remove(),o.children(".fl-page-header-logo").length<1)&&o.prepend(l)},_scrollHeader:function(){var e=r(window),a=null,l=r(".fl-page-header-primary").data("fl-distance"),n=0,a=0!=r(".fl-page-bar").length?r(".fl-page-header-primary, .fl-page-bar"):r(".fl-page-header-primary");e.width()>=window.themeopts.medium_breakpoint?e.on("scroll.fl-show-header-on-scroll",function(){r(this).scrollTop()>l?a.addClass("fl-show"):(a.removeClass("fl-show"),r(".fl-responsive-nav-enabled").length&&(n=2*r(".fl-page-header-primary").height(),0!=r(".fl-page-bar").length&&(n+=r(".fl-page-bar").height()),void 0!==r(".fl-nav-offcanvas-collapse").css("top"))&&(n+=parseInt(r(".fl-nav-offcanvas-collapse").css("top"))),r(".fl-nav-offcanvas-active").length&&0<n&&r(".fl-nav-offcanvas-collapse").css({transform:"translateY("+n+"px)","-ms-transform":"translateY("+n+"px)","-webkit-transform":"translateY("+n+"px)"}))}):(e.off("scroll.fl-show-header-on-scroll"),r(".fl-nav-offcanvas-collapse").css("transform",""))},_megaMenu:function(){r(window);var e=r(".fl-page-header"),a=e.find(".fl-page-header-container").outerWidth(),l=null,n=0;e.find("li.mega-menu, li.mega-menu-disabled").each(function(){l=r(this),n=l.find("> ul.sub-menu").outerWidth(),void 0!==l.data("megamenu-width")&&(n=l.data("megamenu-width")),l.hasClass("mega-menu")&&a<n||FLTheme._isResponsiveNavEnabled()?(l.data("megamenu-width",n),FLTheme._isResponsiveNavEnabled()&&l.find("> ul.sub-menu").css("display","block"),l.removeClass("mega-menu"),l.hasClass("mega-menu-disabled")||l.addClass("mega-menu-disabled")):l.hasClass("mega-menu-disabled")&&n<=a&&(l.find("> ul.sub-menu").css("display",""),l.removeClass("mega-menu-disabled"),l.hasClass("mega-menu")||l.addClass("mega-menu"),l.addClass("mega-menu-items-"+l.children("ul").children("li").length))})},_megaMenuOnScroll:function(){var e=r(window),a=r(".fl-page-header-fixed"),l=a.find(".fl-page-header-container"),n=a.is(":visible"),t=null,i=null;n&&(a.find("li.mega-menu").each(function(){t=r(this),i=t.find("> ul.sub-menu"),l.outerWidth()<i.outerWidth()?(t.removeClass("mega-menu"),t.hasClass("mega-menu-disabled")||t.addClass("mega-menu-disabled")):(t.removeClass("mega-menu-disabled"),t.hasClass("mega-menu")||t.addClass("mega-menu"),t.addClass("mega-menu-items-"+t.children("ul").children("li").length))}),e.off("scroll.fl-mega-menu-on-scroll"),e.off("resize.fl-mega-menu-on-scroll"))},_fixedHeadersWhenBuilderActive:function(){0!=r("body.fl-shrink").length&&r("body").removeClass("fl-shrink"),0!=r("body.fl-fixed-header").length&&r("body").removeClass("fl-fixed-header"),0!=r("body.fl-scroll-header").length&&r("body").removeClass("fl-scroll-header")},_setupMobileNavLayout:function(){var e=r(window),a=r("button.navbar-toggle"),l=r(".fl-page-header:not(.fl-page-header-fixed)"),n=l.find(".fl-page-nav-collapse"),t=r(".fl-page"),i=0,o=(e.height(),r("body").hasClass("fl-offcanvas-push-opacity-left")||r("body").hasClass("fl-offcanvas-push-opacity-right"));l.find(".fl-page-header-logo").offset();FLTheme._isResponsiveNavEnabled()&&a.is(":visible")?(r("body").addClass("fl-responsive-nav-enabled"),a.attr("data-toggle","offcanvas"),n.addClass("fl-nav-offcanvas-collapse"),0===n.find(".fl-button-close").length&&n.prepend('<div class="fl-button-close"><button class="fl-offcanvas-close" aria-label="Close Menu"><i class="fas fa-times"></i></button></div>'),o&&0===r(".fl-offcanvas-opacity").length&&t.append('<div class="fl-offcanvas-opacity"></div>'),t.height()>e.height()&&(r(document).height(),0!=r("body.fl-shrink").length)&&l.height(),0!=r("body.admin-bar").length&&(i=r("#wpadminbar").height()),0==r(".fl-page-bar").length||r(".fl-page-header").hasClass("fl-page-nav-toggle-button")||(i+=r(".fl-page-bar").height()+1),r(".fl-scroll-header").length&&e.width()>=window.themeopts.medium_breakpoint?n.css("top",t.offset().top-i+"px"):n.css("top","")):(a.attr("data-toggle","collapse"),n.removeClass("fl-nav-offcanvas-collapse"),n.find(".fl-button-close").remove(),n.css("height",""),n.css("top",""),t.removeClass("fl-nav-offcanvas-active"),r("body").find(".fl-offcanvas-opacity").remove(),r("body").removeClass("fl-responsive-nav-enabled"))},_toggleMobileNavLayout:function(){r(".fl-page-nav").on("click",".fl-offcanvas-close",function(e){r(".fl-page").toggleClass("fl-nav-offcanvas-active"),e.stopPropagation()})},_footerEffect:function(){r(window).width()>=window.themeopts.mobile_breakpoint?r(".fl-page").css("margin-bottom",r(".fl-page-footer-wrap").height()):r(".fl-page").css("margin-bottom",0)},_toTop:function(){var e=r("#fl-to-top");e.each(function(){r(this).click(function(){return r("html,body").animate({scrollTop:0},"linear"),!1})}),r(window).scroll(function(){r(this).scrollTop()>window.themeopts.scrollTopPosition?e.fadeIn():e.fadeOut()})},_enableLightbox:function(){var e=r("body");"disabled"!==window.themeopts.lightbox&&(e.hasClass("fl-builder")||e.hasClass("woocommerce")||r(".fl-content a").filter(function(){return/\.(png|jpg|jpeg|gif|webp)(\?.*)?$/i.test(this.href)}).magnificPopup({closeBtnInside:!1,type:"image",gallery:{enabled:!0}}),e.hasClass("fl-builder")||e.hasClass("fl-theme-builder-singular"))&&!e.hasClass("woocommerce")&&r(".fl-rich-text a, .fl-module-fl-post-content a").filter(function(){return/\.(png|jpg|jpeg|gif|webp)(\?.*)?$/i.test(this.href)}).magnificPopup({closeBtnInside:!1,type:"image",gallery:{enabled:!0}})},_enableFitVids:function(){r(".fl-post-content").fitVids()},_isResponsiveNavEnabled:function(){var e=r(window);return enabled=!1,enabled=0<r(".fl-page-nav-toggle-visible-always").length||0<r(".fl-page-nav-toggle-visible-medium-mobile").length&&e.width()<window.themeopts.medium_breakpoint||0<r(".fl-page-nav-toggle-visible-mobile").length&&e.width()<window.themeopts.mobile_breakpoint?!0:enabled}},r(function(){FLTheme.init()}),0===r("html.fl-builder-edit").length&&FLTheme._initMobileHeaderLogo(),FLTheme._initRetinaImages()})(jQuery);