!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;at*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:"€",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<>>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;t0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],s=0,i=0;s>>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>>4).toString(16)),t.push((15&e[s]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],s=0;s>>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>>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>>24)|4278255360&(o[m]<<24|o[m]>>>8);o[l>>>5]|=128<>>9<<4)]=l;var u=a._ff,g=a._gg,y=a._hh,f=a._ii;for(m=0;m>>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<>>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<>>32-r)+t},a._hh=function(e,t,s,i,a,r,n){var o=e+(t^s^i)+(a>>>0)+n;return(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<>>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=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.datethis.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.startTimee.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.startTime0&&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+='',r+=s.getQuantityLabel()+": "+e.getCapacity(),r+=""),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")+' '),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""+e+""}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+='',t+="";for(let s of e.products)t+='',t+='",t+='",t+="";return t+='',t+='",t+='",t+="",t+="",t+="",e.coupon&&(t+='',t+='",t+='",t+=""),t+='',t+='",t+='",t+="",t+="",t+="
',t+=''+s.name+"",s.capacity>1&&(t+='',t+=s.quantity_label+": "+s.capacity,t+=""),t+="'+fe(s.price)+"
'+u("Subtotal","motopress-appointment")+"'+fe(e.subtotal)+"
',t+=u("Coupon: %s","motopress-appointment").replace("%s",e.coupon.code),t+="',t+=fe(-e.coupon.amount),t+=" ",t+=''+u("Remove","motopress-appointment")+"",t+="
'+u("Total","motopress-appointment")+"'+fe(e.total)+"
",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=''+t.currency_symbol+"";switch(t.currency_position){case"before":i=s+i;break;case"after":i+=s;break;case"before_with_space":i=s+" "+i;break;case"after_with_space":i=i+" "+s}e<0&&(i="-"+i)}return''+i+""}function fe(e,t={}){return t.literal_free=!1,ye(e,t)}function be(e,t,s={}){let i="";return i+=Se(e,t),i+="",i}function ve(e,t,s=!1){let i="";return i='",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""}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("",{id:e.attr("id")+"_error",class:"mpa-phone-field-error mpa-hide",text:u("Phone number is invalid.","motopress-appointment")});e.after("
",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+='
',this.paymentMethods.length>1&&(e+=this.renderNavigation());for(let t of this.paymentMethods.keys)e+=this.renderFields(t);return e+='
',e+="
",e}renderNavigation(){let e="";e+='",e}renderFields(e){let t="";switch(t+='
',t+="
",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+="
","sepa_debit"===e&&(t+='

',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+="

"),t+="
",t}renderPaymentFields(){let e="";return e+='
',e}renderCardFields(){let e="";return e+='",this.methods.card.isEnabledWallets()&&(e+='
',e+='
'+u("or","motopress-appointment")+"
"),e+='
',e}renderIdealFields(){let e="";return e+='",e+='
',e}renderSepaDebitFields(){let e="";return e+='",e+='
',e}renderRedirectNotice(){let e="";return e+='

',e+=u("You will be redirected to a secure page to complete the payment.","motopress-appointment"),e+="

",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.methods=[],0(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+='',s+="",s+='',s+='",s+="",s+='',s+='",s+='",s+="",s+='',s+='",s+='",s+="",s+="",s+="
',s+=u("Deposit","motopress-appointment"),s+="
',s+=u("Paying now","motopress-appointment"),s+="',s+=fe(e.deposit),s+="
',s+=u("Left to pay","motopress-appointment"),s+="',s+=fe(t),s+="
"),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",' - ')+"",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+='',i+=''+a.getQuantityLabel()+":",i+=" ",i+=''+s+"",i+=""}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)}();