!function(t){t(function(){MPHB.DateRules=can.Construct.extend({},{dates:{},init:function(t){this.dates=t},canCheckIn:function(t){var e=this.formatDate(t);return!this.dates.hasOwnProperty(e)||!this.dates[e].not_check_in&&!this.dates[e].not_stay_in},canCheckOut:function(t){var e=this.formatDate(t);return!this.dates.hasOwnProperty(e)||!this.dates[e].not_check_out},canStayIn:function(t){var e=this.formatDate(t);return!this.dates.hasOwnProperty(e)||!this.dates[e].not_stay_in},getNearestNotStayInDate:function(e,a){var i=MPHB.Utils.cloneDate(a),n=t.datepick.formatDate("yyyy-mm-dd",e),s=t.datepick.formatDate("yyyy-mm-dd",a);return t.each(this.dates,function(e,a){return!(e>s)&&(n>e||(a.not_stay_in?(i=t.datepick.parseDate("yyyy-mm-dd",e),!1):void 0))}),i},formatDate:function(e){return t.datepick.formatDate("yyyy-mm-dd",e)}}),can.Control("MPHB.Datepicker",{},{form:null,hiddenElement:null,roomTypeId:null,init:function(t,e){this.form=e.form,this.roomTypeId=e.hasOwnProperty("roomTypeId")?e.roomTypeId:0,this.setupHiddenElement(),this.initDatepick()},setupHiddenElement:function(){var e=this.element.attr("id")+"-hidden";if(this.hiddenElement=t("#"+e),this.hiddenElement.val()){var a=t.datepick.parseDate(MPHB._data.settings.dateTransferFormat,this.hiddenElement.val()),i=t.datepick.formatDate(MPHB._data.settings.dateFormat,a);this.element.val(i)}else;},initDatepick:function(){var e={dateFormat:MPHB._data.settings.dateFormat,altFormat:MPHB._data.settings.dateTransferFormat,altField:this.hiddenElement,minDate:MPHB.HotelDataManager.myThis.today,monthsToShow:MPHB._data.settings.numberOfMonthDatepicker,firstDay:MPHB._data.settings.firstDay,pickerClass:MPHB._data.settings.datepickerClass},a=t.extend(e,this.getDatepickSettings());this.element.datepick(a)},getDatepickSettings:function(){return{}},getDate:function(){var e=this.element.val(),a=null;try{a=t.datepick.parseDate(MPHB._data.settings.dateFormat,e)}catch(t){a=null}return a},getFormattedDate:function(e){void 0===e&&(e=MPHB._data.settings.dateFormat);var a=this.getDate();return a?t.datepick.formatDate(e,a):""},setDate:function(t){this.element.datepick("setDate",t)},getOption:function(t){return this.element.datepick("option",t)},setOption:function(t,e){this.element.datepick("option",t,e)},getMinDate:function(){var t=this.getOption("minDate");return null!==t&&""!==t?MPHB.Utils.cloneDate(t):null},getMaxDate:function(){var t=this.getOption("maxDate");return null!==t&&""!==t?MPHB.Utils.cloneDate(t):null},clear:function(){this.element.datepick("clear")},formatDate:function(e,a){return a=void 0!==a?a:"yyyy-mm-dd",t.datepick.formatDate(a,e)},refresh:function(){t.datepick._update(this.element[0],!0),t.datepick._updateInput(this.element[0],!1)}}),MPHB.FlexsliderGallery=can.Control.extend({},{sliderEl:null,navSliderEl:null,groupId:null,init:function(e,a){this.sliderEl=e,this.groupId=e.data("group");var i=t('.mphb-gallery-thumbnail-slider[data-group="'+this.groupId+'"]');i.length&&(this.navSliderEl=i);var n=this;t(window).on("load",function(){n.initSliders()})},initSliders:function(){var t=this.sliderEl.data("flexslider-atts");if(this.navSliderEl){var e=this.navSliderEl.data("flexslider-atts");e.asNavFor='.mphb-flexslider-gallery-wrapper[data-group="'+this.groupId+'"]',e.itemWidth=this.navSliderEl.find("ul > li img").width(),t.sync='.mphb-gallery-thumbnail-slider[data-group="'+this.groupId+'"]',this.navSliderEl.addClass("flexslider mphb-flexslider mphb-gallery-thumbnails-slider").flexslider(e)}this.sliderEl.addClass("flexslider mphb-flexslider mphb-gallery-slider").flexslider(t)}}),MPHB.format_price=function(e,a){a=a||{};var i=MPHB._data.settings.currency;a=t.extend({trim_zeros:!1},i,a),e=MPHB.number_format(e,a.decimals,a.decimal_separator,a.thousand_separator);var n=a.price_format.replace("%s",e);if(a.trim_zeros){var s=new RegExp("\\"+a.decimal_separator+"0+$|(\\"+a.decimal_separator+"\\d*[1-9])0+$");n=n.replace(s,"$1")}return''+n+""},MPHB.number_format=function(t,e,a,i){var n,s,r,o,l,c="";return e=e||0,a=a||".",i=i||",",t<0&&(c="-",t*=-1),n=parseInt(t=(+t||0).toFixed(e))+"",(s=n.length)>3?s%=3:s=0,l=s?n.substr(0,s)+i:"",r=n.substr(s).replace(/(\d{3})(?=\d)/g,"$1"+i),o=e?a+Math.abs(t-n).toFixed(e).replace(/-/,0).slice(2):"",c+l+r+o},MPHB.post=function(e,a,i){e="mphb_"+e,a=t.extend({action:e,mphb_nonce:MPHB._data.nonces[e]},a);var n=t.extend({url:MPHB._data.ajaxUrl,type:"POST",dataType:"json",data:a},i);return t.ajax(n)},can.Construct("MPHB.Season",{},{startDate:null,endDate:null,allowedDays:[],init:function(e){var a=MPHB._data.settings.dateTransferFormat;this.startDate=t.datepick.parseDate(a,e.start_date),this.endDate=t.datepick.parseDate(a,e.end_date),this.allowedDays=e.allowed_days},isContainDate:function(t){return t>=this.startDate&&t<=this.endDate&&MPHB.Utils.inArray(t.getDay(),this.allowedDays)}}),MPHB.ReservationRulesChecker=can.Construct.extend({myThis:null},{rules:{checkInDays:{},checkOutDays:{},minStay:{},maxStay:{}},init:function(e){this.rules.checkInDays=t.map(e.check_in_days,function(t){return new MPHB.Rules.CheckInDayRule(t)}),this.rules.checkOutDays=t.map(e.check_out_days,function(t){return new MPHB.Rules.CheckOutDayRule(t)}),this.rules.minStay=t.map(e.min_stay_length,function(t){return new MPHB.Rules.MinDaysRule(t)}),this.rules.maxStay=t.map(e.max_stay_length,function(t){return new MPHB.Rules.MaxDaysRule(t)})},getActualRule:function(e,a,i){var n=null;return t.each(this.rules[e],function(t,e){if(e.isActualRule(a,i))return n=e,!1}),n},getActualCombinedRule:function(e,a){var i=[],n=[];return t.each(this.rules[e],function(t,e){var s=MPHB.Utils.arrayDiff(e.roomTypeIds,i);if(s.length&&e.isActualForDate(a))return n.push(e),i=i.concat(s),!e.isAllRoomTypeRule()&&(!!MPHB.Utils.arrayDiff(MPHB._data.allRoomTypeIds,i).length&&void 0)}),this.combineRules(e,n)},combineRules:function(e,a){var i;switch(e){case"checkInDays":var n=[];t.each(a,function(t,e){n=n.concat(e.days)}),n=MPHB.Utils.arrayUnique(n),i=new MPHB.Rules.CheckInDayRule({season_ids:[0],room_type_ids:[0],check_in_days:n});break;case"checkOutDays":var n=[];t.each(a,function(t,e){n=n.concat(e.days)}),n=MPHB.Utils.arrayUnique(n),i=new MPHB.Rules.CheckOutDayRule({season_ids:[0],room_type_ids:[0],check_out_days:n});break;case"minStay":var s=MPHB.Utils.arrayMin(t.map(a,function(t){return t.min}));i=new MPHB.Rules.MinDaysRule({season_ids:[0],room_type_ids:[0],min_stay_length:s});break;case"maxStay":var s=MPHB.Utils.arrayMax(t.map(a,function(t){return t.max}));i=new MPHB.Rules.MaxDaysRule({season_ids:[0],room_type_ids:[0],max_stay_length:s})}return i},isCheckInSatisfy:function(t,e){return e?this.getActualRule("checkInDays",t,e).verify(t):this.getActualCombinedRule("checkInDays",t).verify(t)},isCheckOutSatisfy:function(t,e,a){return a?this.getActualRule("checkOutDays",t,a).verify(t,e):this.getActualCombinedRule("checkOutDays",t).verify(t,e)},getMinStay:function(t,e){return e?this.getActualRule("minStay",t,e).min:this.getActualCombinedRule("minStay",t).min},getMaxStay:function(t,e){return e?this.getActualRule("maxStay",t,e).max:this.getActualCombinedRule("maxStay",t).max},getMinCheckOutDate:function(e,a){var i=this.getMinStay(e,a);return t.datepick.add(MPHB.Utils.cloneDate(e),i,"d")},getMaxCheckOutDate:function(e,a){var i=this.getMaxStay(e,a);return t.datepick.add(MPHB.Utils.cloneDate(e),i,"d")}}),MPHB.Rules={},MPHB.Rules.BasicRule=can.Construct.extend({},{seasonIds:[],roomTypeIds:[],init:function(t){this.seasonIds=t.season_ids,this.roomTypeIds=t.room_type_ids},isActualRule:function(t,e){return this.isActualForRoomType(e)&&this.isActualForDate(t)},isActualForRoomType:function(t){return MPHB.Utils.inArray(t,this.roomTypeIds)||MPHB.Utils.inArray(0,this.roomTypeIds)},isActualForDate:function(e){if(this.isAllSeasonRule())return!0;var a=!1;return t.each(this.seasonIds,function(t,i){if(MPHB.HotelDataManager.myThis.seasons[i]&&MPHB.HotelDataManager.myThis.seasons[i].isContainDate(e))return a=!0,!1}),a},verify:function(t,e){return!0},isAllSeasonRule:function(){return MPHB.Utils.inArray(0,this.seasonIds)},isAllRoomTypeRule:function(){return MPHB.Utils.inArray(0,this.roomTypeIds)},isGlobalRule:function(){return this.isAllSeasonRule()&&this.isAllRoomTypeRule()}}),MPHB.Rules.BasicRule("MPHB.Rules.CheckInDayRule",{},{days:[],init:function(t){this._super(t),this.days=t.check_in_days},verify:function(t,e){return MPHB.Utils.inArray(t.getDay(),this.days)}}),MPHB.Rules.BasicRule("MPHB.Rules.CheckOutDayRule",{},{days:[],init:function(t){this._super(t),this.days=t.check_out_days},verify:function(t,e){return MPHB.Utils.inArray(e.getDay(),this.days)}}),MPHB.Rules.BasicRule("MPHB.Rules.MinDaysRule",{},{min:null,init:function(t){this._super(t),this.min=t.min_stay_length},verify:function(e,a){var i=t.datepick.add(MPHB.Utils.cloneDate(e),this.min,"d");return MPHB.Utils.formatDateToCompare(a)>=MPHB.Utils.formatDateToCompare(i)}}),MPHB.Rules.BasicRule("MPHB.Rules.MaxDaysRule",{},{max:null,init:function(t){this._super(t),this.max=0!=t.max_stay_length?t.max_stay_length:3652},verify:function(e,a){var i=t.datepick.add(MPHB.Utils.cloneDate(e),this.max,"d");return MPHB.Utils.formatDateToCompare(a)<=MPHB.Utils.formatDateToCompare(i)}}),can.Construct("MPHB.HotelDataManager",{myThis:null,ROOM_STATUS_AVAILABLE:"available",ROOM_STATUS_NOT_AVAILABLE:"not-available",ROOM_STATUS_BOOKED:"booked",ROOM_STATUS_PAST:"past"},{today:null,roomTypesData:{},translationIds:{},dateRules:null,typeRules:{},seasons:{},init:function(e){MPHB.HotelDataManager.myThis=this,this.setToday(t.datepick.parseDate(MPHB._data.settings.dateTransferFormat,e.today)),this.initSeasons(e.seasons),this.initRoomTypesData(e.roomTypesData,e.rules),this.initRules(e.rules)},initRoomTypesData:function(e,a){var i=this;t.each(e,function(e,n){e=parseInt(e);var s=parseInt(n.originalId);s!=e&&(i.translationIds.hasOwnProperty(s)||(i.translationIds[s]=[]),i.translationIds[s].push(e));var r=new MPHB.RoomTypeData(e,n);t.each(a.dates,function(t,e){e.not_stay_in&&r.blockAllRoomsOnDate(t)}),a.blockedTypes.hasOwnProperty(s)&&t.each(a.blockedTypes[s],function(t,e){e.not_stay_in&&r.blockAllRoomsOnDate(t)}),i.roomTypesData[e]=r})},initRules:function(e){this.dateRules=new MPHB.DateRules(e.dates);var a=this;t.each(e.blockedTypes,function(e,i){a.typeRules[e]=new MPHB.DateRules(i),a.translationIds.hasOwnProperty(e)&&t.each(a.translationIds[e],function(t,e){a.typeRules[e]=new MPHB.DateRules(i)})}),this.reservationRules=new MPHB.ReservationRulesChecker(e.reservationRules)},initSeasons:function(e){t.each(e,this.proxy(function(t,e){this.seasons[t]=new MPHB.Season(e)}))},setToday:function(t){this.today=t},getRoomTypeData:function(t){return!!this.roomTypesData.hasOwnProperty(t)&&this.roomTypesData[t]},fillDateCellData:function(t,e,a,i){i||(i=e);var n=[],s=[],r=t.roomTypeId;return this.notStayIn(e,r)&&(n.push(MPHB._data.translations.notStayIn),s.push("mphb-not-stay-in-date")),"checkIn"==a&&this.notCheckIn(e,r,i)&&(n.push(MPHB._data.translations.notCheckIn),s.push("mphb-not-check-in-date")),"checkOut"==a&&this.notCheckOut(e,r,i)&&(n.push(MPHB._data.translations.notCheckOut),s.push("mphb-not-check-out-date")),n.length&&(t.title+=" "+MPHB._data.translations.rules+" "+n.join(", ")),s.length&&(t.dateClass+=(t.dateClass.length?" ":"")+s.join(" ")),t},notStayIn:function(t,e){var a=this.dateRules.canStayIn(t);return this.typeRules[e]&&(a=a&&this.typeRules[e].canStayIn(t)),!a},notCheckIn:function(t,e,a){a||(a=t);var i=this.dateRules.canCheckIn(t);return i=i&&this.reservationRules.isCheckInSatisfy(t,e),this.typeRules[e]&&(i=i&&this.typeRules[e].canCheckIn(t)),!i},notCheckOut:function(t,e,a){var i=this.dateRules.canCheckOut(t);return i=i&&this.reservationRules.isCheckOutSatisfy(a,t,e),this.typeRules[e]&&(i=i&&this.typeRules[e].canCheckOut(t)),!i}}),MPHB.TermsSwitcher=can.Construct.extend({},{init:function(t,e){var a=t.children(".mphb-terms-and-conditions");t.find(".mphb-terms-and-conditions-link").on("click",function(t){t.preventDefault(),a.toggleClass("mphb-active")})}}),MPHB.Utils=can.Construct.extend({formatDateToCompare:function(e){return t.datepick.formatDate("yyyymmdd",e)},cloneDate:function(t){return new Date(t.getTime())},arrayUnique:function(t){return t.filter(function(t,e,a){return a.indexOf(t)===e})},arrayMin:function(t){return Math.min.apply(null,t)},arrayMax:function(t){return Math.max.apply(null,t)},arrayDiff:function(t,e){return t.filter(function(t){return e.indexOf(t)<0})},inArray:function(t,e){return-1!==e.indexOf(t)}},{}),MPHB.Gateway=can.Construct.extend({},{amount:0,paymentDescription:"",init:function(t){this.billingSection=t.billingSection,this.initSettings(t.settings)},initSettings:function(t){this.amount=t.amount,this.paymentDescription=t.paymentDescription},canSubmit:function(t,e){return Promise.resolve(!0)},updateData:function(t){this.amount=t.amount,this.paymentDescription=t.paymentDescription},afterSelection:function(t){},cancelSelection:function(){},onInput:function(t,e){}}),MPHB.BeanstreamGateway=MPHB.Gateway.extend({},{scriptUrl:"",isCanSubmit:!1,loadHandler:null,validityHandler:null,tokenRequestHandler:null,tokenUpdatedHandler:null,initSettings:function(t){this._super(t),this.scriptUrl=t.scriptUrl||"https://payform.beanstream.com/v1.1.0/payfields/beanstream_payfields.js",this.validityHandler=this.validityChanged.bind(this),this.tokenRequestHandler=this.tokenRequested.bind(this),this.tokenUpdatedHandler=this.tokenUpdated.bind(this)},canSubmit:function(t,e){return Promise.relosve(this.isCanSubmit)},afterSelection:function(e){if(this._super(e),e.length>0){var a=document.createElement("script");a.id="payfields-script",a.src=this.scriptUrl,a.dataset.submitform="true",a.dataset.async="true",null!=this.loadHandler&&t(document).off("beanstream_payfields_loaded",this.loadHandler),this.loadHandler=function(a){t("[data-beanstream-id]").appendTo(e)},t(document).on("beanstream_payfields_loaded",this.loadHandler),e.append(a),e.removeClass("mphb-billing-fields-hidden")}t(document).on("beanstream_payfields_inputValidityChanged",this.validityHandler).on("beanstream_payfields_tokenRequested",this.tokenRequestHandler).on("beanstream_payfields_tokenUpdated",this.tokenUpdatedHandler)},cancelSelection:function(){t(document).off("beanstream_payfields_inputValidityChanged",this.validityHandler).off("beanstream_payfields_tokenRequested",this.tokenRequestHandler).off("beanstream_payfields_tokenUpdated",this.tokenUpdatedHandler)},validityChanged:function(t){(t.eventDetail||t.originalEvent.eventDetail).isValid||(this.isCanSubmit=!1)},tokenRequested:function(t){this.billingSection.showPreloader()},tokenUpdated:function(t){var e=t.eventDetail||t.originalEvent.eventDetail;e.success?this.isCanSubmit=!0:(this.isCanSubmit=!1,this.billingSection.showError(MPHB._data.translations.tokenizationFailure.replace("(%s)",e.message))),this.billingSection.hidePreloader()}}),MPHB.BillingSection=can.Control.extend({},{updateBillingFieldsTimeout:null,parentForm:null,billingFieldsWrapperEl:null,gateways:{},amounts:{},lastGatewayId:null,init:function(t,e){this.parentForm=e.form,this.billingFieldsWrapperEl=this.element.find(".mphb-billing-fields"),this.initGateways(e.gateways)},initGateways:function(e){var a=this;t.each(e,function(t,e){var i={billingSection:a,settings:e},n=null;switch(t){case"braintree":n=new MPHB.BraintreeGateway(i);break;case"beanstream":n=new MPHB.BeanstreamGateway(i);break;case"stripe":n=new MPHB.StripeGateway(i);break;default:n=new MPHB.Gateway(i)}null!=n&&(a.gateways[t]=n,a.amounts[t]=e.amount)}),this.notifySelectedGateway()},'[name="mphb_gateway_id"] change':function(e,a){var i=this,n=e.val();this.showPreloader(),this.billingFieldsWrapperEl.empty().addClass("mphb-billing-fields-hidden"),clearTimeout(this.updateBillingFieldsTimeout),this.updateBillingFieldsTimeout=setTimeout(function(){var e=i.parentForm.parseFormToJSON();t.ajax({url:MPHB._data.ajaxUrl,type:"GET",dataType:"json",data:{action:"mphb_get_billing_fields",mphb_nonce:MPHB._data.nonces.mphb_get_billing_fields,mphb_gateway_id:n,formValues:e},success:function(t){t.hasOwnProperty("success")?t.success?(i.lastGatewayId&&i.gateways[i.lastGatewayId].cancelSelection(),i.billingFieldsWrapperEl.html(t.data.fields),t.data.hasVisibleFields?i.billingFieldsWrapperEl.removeClass("mphb-billing-fields-hidden"):i.billingFieldsWrapperEl.addClass("mphb-billing-fields-hidden"),i.notifySelectedGateway(n)):i.showError(t.data.message):i.showError(MPHB._data.translations.errorHasOccured)},error:function(t){i.showError(MPHB._data.translations.errorHasOccured)},complete:function(t){i.hidePreloader()}})},500)},hideErrors:function(){this.parentForm.hideErrors()},showError:function(t){this.parentForm.showError(t)},showPreloader:function(){this.parentForm.showPreloader()},hidePreloader:function(){this.parentForm.hidePreloader()},onInput:function(t,e){var a=this.gateways[this.getSelectedGateway()];a&&a.onInput(t,e)},canSubmit:function(t,e){var a=this.gateways[this.getSelectedGateway()];return a?a.canSubmit(t,e):Promise.resolve(!0)},getSelectedGateway:function(){var t=this.element.find('[name="mphb_gateway_id"]');return 1==t.length?t.val():t.filter(":checked").val()},getSelectedGatewayAmount:function(){var t=this.getSelectedGateway();return this.amounts.hasOwnProperty(t)?this.amounts[t]:0},notifySelectedGateway:function(t){if((t=t||this.getSelectedGateway())&&this.gateways.hasOwnProperty(t)){this.gateways[t].afterSelection(this.billingFieldsWrapperEl);var e=this.parentForm.getCountry();!1!==e&&this.gateways[t].onInput("country",e)}this.lastGatewayId=t},updateGatewaysData:function(e){var a=this;t.each(e,function(t,e){a.gateways.hasOwnProperty(t)&&a.gateways[t].updateData(e)})}}),MPHB.BraintreeGateway=MPHB.Gateway.extend({},{clientToken:"",checkout:null,initSettings:function(t){this._super(t),this.clientToken=t.clientToken},canSubmit:function(t,e){return Promise.resolve(this.isNonceStored())},storeNonce:function(t){this.billingSection.billingFieldsWrapperEl.find('[name="mphb_braintree_payment_nonce"]').val(t)},isNonceStored:function(){var t=this.billingSection.billingFieldsWrapperEl.find('[name="mphb_braintree_payment_nonce"]');return t.length&&""!=t.val()},afterSelection:function(t){if(this._super(t),void 0!=braintree){var e="mphb-braintree-container-"+this.clientToken.substr(0,8);t.append('
');var a=this;braintree.setup(this.clientToken,"dropin",{container:e,onReady:function(t){a.checkout=t},onPaymentMethodReceived:function(t){a.storeNonce(t.nonce),a.billingSection.parentForm.element.submit(),a.billingSection.showPreloader()}}),t.removeClass("mphb-billing-fields-hidden")}},cancelSelection:function(){if(this._super(),null!=this.checkout){var t=this;this.checkout.teardown(function(){t.checkout=null})}}}),MPHB.CouponSection=can.Control.extend({},{applyCouponTimeout:null,parentForm:null,appliedCouponEl:null,couponEl:null,messageHolderEl:null,init:function(t,e){this.parentForm=e.form,this.couponEl=t.find('[name="mphb_coupon_code"]'),this.appliedCouponEl=t.find('[name="mphb_applied_coupon_code"]'),this.messageHolderEl=t.find(".mphb-coupon-message")},".mphb-apply-coupon-code-button click":function(e,a){a.preventDefault(),a.stopPropagation(),this.clearMessage();var i=this.couponEl.val();if(!i.length)return void this.showMessage(MPHB._data.translations.emptyCouponCode);this.appliedCouponEl.val("");var n=this;this.showPreloader(),clearTimeout(this.applyCouponTimeout),this.applyCouponTimeout=setTimeout(function(){var e=n.parentForm.parseFormToJSON();t.ajax({url:MPHB._data.ajaxUrl,type:"POST",dataType:"json",data:{action:"mphb_apply_coupon",mphb_nonce:MPHB._data.nonces.mphb_apply_coupon,mphb_coupon_code:i,formValues:e},success:function(t){t.hasOwnProperty("success")?t.success?(n.parentForm.setCheckoutData(t.data),n.couponEl.val(""),n.appliedCouponEl.val(t.data.coupon.applied_code),n.showMessage(t.data.coupon.message)):n.showMessage(t.data.message):n.showMessage(MPHB._data.translations.errorHasOccured)},error:function(t){n.showMessage(MPHB._data.translations.errorHasOccured)},complete:function(t){n.hidePreloader()}})},500)},removeCoupon:function(){this.appliedCouponEl.val(""),this.clearMessage()},showPreloader:function(){this.parentForm.showPreloader()},hidePreloader:function(){this.parentForm.hidePreloader()},clearMessage:function(){this.messageHolderEl.html("").addClass("mphb-hide")},showMessage:function(t){this.messageHolderEl.html(t).removeClass("mphb-hide")}}),MPHB.CheckoutForm=can.Control.extend({myThis:null},{priceBreakdownTableEl:null,bookBtnEl:null,errorsWrapperEl:null,preloaderEl:null,billingSection:null,couponSection:null,waitResponse:!1,updateInfoTimeout:null,updateRatesTimeout:null,freeBooking:!1,currentInfoAjax:null,toPay:0,init:function(t,e){MPHB.CheckoutForm.myThis=this,this.bookBtnEl=this.element.find("input[type=submit]"),this.errorsWrapperEl=this.element.find(".mphb-errors-wrapper"),this.preloaderEl=this.element.find(".mphb-preloader"),this.priceBreakdownTableEl=this.element.find("table.mphb-price-breakdown"),MPHB._data.settings.useBilling&&(this.billingSection=new MPHB.BillingSection(this.element.find("#mphb-billing-details"),{form:this,gateways:MPHB._data.gateways})),MPHB._data.settings.useCoupons&&(this.couponSection=new MPHB.CouponSection(this.element.find("#mphb-coupon-details"),{form:this}))},setTotal:function(t,e){this.toPay=t,this.element.find(".mphb-total-price-field").html(e)},setDeposit:function(t,e){this.toPay=t,this.element.find(".mphb-deposit-amount-field").html(e)},setupPriceBreakdown:function(t){this.priceBreakdownTableEl.replaceWith(t),this.priceBreakdownTableEl=this.element.find("table.mphb-price-breakdown")},updateCheckoutInfo:function(){var e=this;e.hideErrors(),e.showPreloader(),clearTimeout(this.updateInfoTimeout),this.updateInfoTimeout=setTimeout(function(){var a=e.parseFormToJSON();e.currentInfoAjax=t.ajax({url:MPHB._data.ajaxUrl,type:"GET",dataType:"json",data:{action:"mphb_update_checkout_info",mphb_nonce:MPHB._data.nonces.mphb_update_checkout_info,formValues:a},beforeSend:function(){null!=e.currentInfoAjax&&(e.currentInfoAjax.abort(),e.hideErrors())},success:function(t){t.hasOwnProperty("success")?t.success?e.setCheckoutData(t.data):e.showError(t.data.message):e.showError(MPHB._data.translations.errorHasOccured)},error:function(t){e.showError(MPHB._data.translations.errorHasOccured)},complete:function(t){e.hidePreloader(),e.currentInfoAjax=null}})},500)},setCheckoutData:function(t){this.setTotal(t.newAmount,t.priceHtml),this.setupPriceBreakdown(t.priceBreakdown),MPHB._data.settings.useBilling&&(this.setDeposit(t.depositAmount,t.depositPrice),this.billingSection.updateGatewaysData(t.gateways),t.isFree?this.setFreeMode():this.unsetFreeMode())},setFreeMode:function(){this.freeBooking=!0,this.billingSection.element.addClass("mphb-hide"),this.element.append(t("",{type:"hidden",name:"mphb_gateway_id",value:"manual",id:"mphb-manual-payment-input"}))},unsetFreeMode:function(){this.freeBooking=!1,this.billingSection.element.removeClass("mphb-hide"),this.element.find("#mphb-manual-payment-input").remove()},updateRatePrices:function(e){if(e&&e.length){var a=parseInt(e.attr("data-index")),i=e.find(".mphb_sc_checkout-rate"),n=t.map(i,function(t){return parseInt(t.value)});if(!(n.length<=1)){var s=this.parseFormToJSON(),r=s.mphb_room_details[a],o=r.adults||"",l=r.children||"";clearTimeout(this.updateRatesTimeout),this.updateRatesTimeout=setTimeout(function(){t.ajax({url:MPHB._data.ajaxUrl,type:"GET",dataType:"json",data:{action:"mphb_update_rate_prices",mphb_nonce:MPHB._data.nonces.mphb_update_rate_prices,rates:n,adults:o,children:l,check_in_date:s.mphb_check_in_date,check_out_date:s.mphb_check_out_date},success:function(e){if(e.hasOwnProperty("success")){var a=e.data;t.each(i,function(e,i){var n=i.value;if(void 0!=a[n]){var s=t(i).parent().children("strong");s.children(".mphb-price").remove(),s.append(a[n])}})}}})},500)}}},".mphb_checkout-guests-chooser change":function(t,e){this.updateRatePrices(t.closest(".mphb-room-details")),this.updateCheckoutInfo()},".mphb_checkout-rate change":function(t,e){this.updateCheckoutInfo()},".mphb_checkout-service, .mphb_checkout-service-adults change":function(t,e){this.updateCheckoutInfo()},".mphb_checkout-service-quantity input":function(t,e){this.updateCheckoutInfo()},'select[name="mphb_country"] change':function(e,a){if(null!=this.billingSection){var i=t(e).val();this.billingSection.onInput("country",i)}},getCountry:function(){return this.getCustomerDetailsOf(["country"]).country||!1},".mphb-price-breakdown-expand click":function(e,a){a.preventDefault(),t(e).blur();var i=t(e).parents("tr.mphb-price-breakdown-group");i.find(".mphb-price-breakdown-rate").toggleClass("mphb-hide"),i.nextUntil("tr.mphb-price-breakdown-group").toggleClass("mphb-hide"),t(e).children(".mphb-inner-icon").toggleClass("mphb-hide")},hideErrors:function(){this.errorsWrapperEl.empty().addClass("mphb-hide")},showError:function(t){this.errorsWrapperEl.html(t).removeClass("mphb-hide")},showPreloader:function(){this.waitResponse=!0,this.bookBtnEl.attr("disabled","disabled"),this.preloaderEl.removeClass("mphb-hide")},hidePreloader:function(){this.waitResponse=!1,this.bookBtnEl.removeAttr("disabled"),this.preloaderEl.addClass("mphb-hide")},parseFormToJSON:function(){return this.element.serializeJSON()},getCustomerDetailsOf:function(t){var e={},a=this.element;return t.forEach(function(t){var i=a.find("#mphb_"+t);i.length>0&&(e[t]=i.val())}),e},getCustomerDetails:function(){var e={};return t.extend(e,this.getCustomerDetailsOf(["first_name","last_name","email","phone"])),MPHB._data.settings.countryRequired&&t.extend(e,this.getCustomerDetailsOf(["country"])),MPHB._data.settings.fullAddressRequired&&t.extend(e,this.getCustomerDetailsOf(["country","address1","state","zip"])),e},getToPayAmount:function(){var t=this.toPay;return 0==t&&(t=this.billingSection.getSelectedGatewayAmount()),t},submit:function(t,e){if(this.waitResponse)return!1;if(MPHB._data.settings.useBilling&&!this.freeBooking){var a=this.getToPayAmount(),i=this.getCustomerDetails(),n=this;return this.showPreloader(),this.billingSection.canSubmit(a,i).then(function(t){t?n.element[0].submit():n.hidePreloader()}).catch(function(t){n.hidePreloader(),console.error("Billing error. "+t.message)}),!1}},"#mphb-price-details .mphb-remove-coupon click":function(t,e){e.preventDefault(),e.stopPropagation(),MPHB._data.settings.useCoupons&&(this.couponSection.removeCoupon(),this.updateCheckoutInfo())}}),MPHB.StripeGateway=MPHB.Gateway.extend({},{publicKey:"",locale:"auto",currency:"EUR",successUrl:window.location.href,defaultCountry:"",paymentDescription:"Accommodation(s) reservation",statementDescriptor:"Hotel Booking",fullAddressRequired:!1,i18n:{},style:{},api:null,elements:null,cardControl:null,idealControl:null,ibanControl:null,payments:null,customer:null,mountWrapper:null,errorsWrapper:null,hasErrors:!1,undefinedError:MPHB._data.translations.errorHasOccured,init:function(t){this._super(t),this.api=Stripe(this.publicKey),this.elements=this.api.elements({locale:this.locale}),this.cardControl=this.elements.create("card",{style:this.style,hidePostalCode:this.fullAddressRequired}),this.idealControl=this.elements.create("idealBank",{style:this.style}),this.ibanControl=this.elements.create("iban",{style:this.style,supportedCountries:["SEPA"]}),this.payments=new MPHB.StripeGateway.PaymentMethods(t.settings.paymentMethods,this.defaultCountry),this.addListeners()},initSettings:function(t){this._super(t),this.publicKey=t.publicKey,this.locale=t.locale,this.currency=t.currency,this.successUrl=t.successUrl,this.defaultCountry=t.defaultCountry,this.paymentDescription=t.paymentDescription,this.statementDescriptor=t.statementDescriptor,this.fullAddressRequired=MPHB._data.settings.fullAddressRequired,this.i18n=t.i18n,this.style=t.style},addListeners:function(){var t=this.onChange.bind(this);this.cardControl.on("change",t),this.ibanControl.on("change",t)},onChange:function(t){t.error?(this.showError(t.error.message),this.hasErrors=!0):(this.hideErrors(),this.hasErrors=!1)},onInput:function(t,e){"country"==t&&this.payments.selectCountry(e)},afterSelection:function(t){this._super(t),t.append(this.mountHtml()),this.mountWrapper=t,this.errorsWrapper=t.find("#mphb-stripe-errors"),this.cardControl.mount("#mphb-stripe-card-element"),this.payments.isEnabled("ideal")&&this.idealControl.mount("#mphb-stripe-ideal-element"),this.payments.isEnabled("sepa_debit")&&this.ibanControl.mount("#mphb-stripe-iban-element"),this.payments.mount(t);var e=this;this.payments.inputs.on("change",function(){switch(e.payments.currentPayment){case"card":e.cardControl.clear();break;case"ideal":e.idealControl.clear();break;case"sepa_debit":e.ibanControl.clear()}e.payments.selectPayment(this.value)}),t.removeClass("mphb-billing-fields-hidden")},cancelSelection:function(){this._super(),this.mountWrapper=null,this.errorsWrapper=null,this.cardControl.unmount(),this.payments.isEnabled("ideal")&&this.idealControl.unmount(),this.payments.isEnabled("sepa_debit")&&this.ibanControl.unmount(),this.payments.unmount()},canSubmit:function(t,e){return this.hasErrors?Promise.resolve(!1):(this.setCustomer(e),"card"==this.payments.currentPayment?this.createPaymentIntent(t).then(this.createCardPayment.bind(this)).then(this.handleStripeErrors.bind(this)).then(this.completeCardPayment.bind(this)):this.createSource(t).then(this.handleStripeErrors.bind(this)).then(this.completeSourcePayment.bind(this)))},setCustomer:function(e){var a=t.extend({},e);a.name=a.first_name+" "+a.last_name,a.hasOwnProperty("country")||(a.country=this.payments.currentCountry),this.customer=a},createPaymentIntent:function(t){var e=this;return new Promise(function(a,i){MPHB.post("create_stripe_payment_intent",{amount:t,description:e.paymentDescription},{success:function(t){if(t.hasOwnProperty("success"))if(t.success){var n={id:t.data.id,client_secret:t.data.client_secret,object:"payment_intent"};a(n)}else e.showError(t.data.message),i(new Error(t.data.message));else e.showError(e.undefinedError),i(new Error(e.undefinedError))},error:function(t){e.showError(e.undefinedError),i(new Error(e.undefinedError))}})})},createCardPayment:function(t){return this.api.handleCardPayment(t.client_secret,this.cardControl,{payment_method_data:{billing_details:{name:this.customer.name}}})},createSource:function(t){var e=this.payments.currentPayment,a=this.customer,i={type:e,amount:this.convertToSmallestUnit(t),currency:this.currency.toLowerCase(),owner:{name:a.name,email:a.email},mandate:{notification_method:"none"},redirect:{return_url:this.successUrl},statement_descriptor:this.statementDescriptor},n=null;switch(e){case"bancontact":["en","de","fr","nl"].indexOf(this.locale)>=0&&(i.bancontact={preferred_language:this.locale});break;case"ideal":n=this.idealControl;break;case"giropay":break;case"sepa_debit":n=this.ibanControl;break;case"sofort":i.sofort={country:a.country},["de","en","es","it","fr","nl","pl"].indexOf(this.locale)>=0&&(i.sofort.preferred_language=this.locale)}return null!=n?this.api.createSource(n,i):this.api.createSource(i)},handleStripeErrors:function(t){if(t.error)throw this.showError(t.error.message),new Error(t.error.message);return null!=t.paymentIntent?t.paymentIntent:t.source},completeCardPayment:function(t){if("succeeded"==t.status||"processing"==t.status)return this.saveToCheckout("payment_method",this.payments.currentPayment),this.saveToCheckout("payment_intent_id",t.id),!0;throw this.showError(this.undefinedError),new Error(this.undefinedError)},completeSourcePayment:function(t){return this.saveToCheckout("payment_method",this.payments.currentPayment),this.saveToCheckout("source_id",t.id),this.saveToCheckout("redirect_url",t.redirect.url),!0},saveToCheckout:function(t,e){this.mountWrapper.find("#mphb_stripe_"+t).val(e)},convertToSmallestUnit:function(t){switch(this.currency){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":t=Math.floor(t);break ;default:t=Math.round(100*t)}return t},mountHtml:function(){var t=''+this.i18n.iban_policy+"
"),e+="'+this.i18n.redirect_notice+"
"},showError:function(t){this.errorsWrapper.html(t).removeClass("mphb-hide")},hideErrors:function(){this.errorsWrapper.addClass("mphb-hide").text("")}}),MPHB.SearchCheckInDatepicker=MPHB.Datepicker.extend({},{getDatepickSettings:function(){return{onSelect:this.proxy(function(t){this.form.updateCheckOutLimitations()}),onDate:this.proxy(function(t,e){var a={dateClass:"mphb-date-cell",selectable:!1,title:""};if(e){MPHB.HotelDataManager.myThis.reservationRules.isCheckInSatisfy(t,this.roomTypeId)&&MPHB.HotelDataManager.myThis.dateRules.canCheckIn(t)&&(a.selectable=!0),a=MPHB.HotelDataManager.myThis.fillDateCellData(a,t,"checkIn")}else a.dateClass+=" mphb-extra-date";return a.selectable?a.dateClass+=" mphb-selectable-date":a.dateClass+=" mphb-unselectable-date",a}),pickerClass:"mphb-datepick-popup mphb-check-in-datepick "+MPHB._data.settings.datepickerClass}}}),MPHB.SearchCheckOutDatepicker=MPHB.Datepicker.extend({},{getDatepickSettings:function(){return{onDate:this.proxy(function(t,e){var a={dateClass:"mphb-date-cell",selectable:!1,title:""};if(e){var i=this.form.checkInDatepicker.getDate(),n=null!==this.getMinDate()&&MPHB.Utils.formatDateToCompare(t)",{class:"mphb-error",html:e});this.errorsWrapper.append(a).removeClass("mphb-hide")},clearErrors:function(){this.errorsWrapper.empty().addClass("mphb-hide")},lock:function(){this.element.find("[name]").attr("disabled","disabled"),this.reserveBtn.attr("disabled","disabled").addClass("mphb-disabled"),this.reserveBtnPreloader.removeClass("mphb-hide")},unlock:function(){this.element.find("[name]").removeAttr("disabled"),this.reserveBtn.removeAttr("disabled").removeClass("mphb-disabled"),this.reserveBtnPreloader.addClass("mphb-hide")},setFormWaitingMode:function(){this.mode=MPHB.ReservationForm.MODE_WAITING,this.lock()},setFormNormalMode:function(){this.mode=MPHB.ReservationForm.MODE_NORMAL,this.unlock()},initCheckInDatepicker:function(){var t=this.formEl.find('input[type="text"][id^=mphb_check_in_date]');this.checkInDatepicker=new MPHB.RoomTypeCheckInDatepicker(t,{form:this,roomTypeId:this.searchRoomTypeId})},initCheckOutDatepicker:function(){var t=this.formEl.find('input[type="text"][id^=mphb_check_out_date]');this.checkOutDatepicker=new MPHB.RoomTypeCheckOutDatepicker(t,{form:this,roomTypeId:this.searchRoomTypeId})},initReserveBtn:function(){this.reserveBtn=this.formEl.find(".mphb-reserve-btn"),this.reserveBtnPreloader=this.formEl.find(".mphb-preloader"),this.setFormNormalMode()},updateCheckOutLimitations:function(t){void 0===t&&(t=!0);var e=this.retrieveCheckOutLimitations(this.checkInDatepicker.getDate(),this.checkOutDatepicker.getDate());this.checkOutDatepicker.setOption("minDate",e.minDate),this.checkOutDatepicker.setOption("maxDate",e.maxDate),this.checkOutDatepicker.setDate(t?e.date:null)},retrieveCheckOutLimitations:function(t,e){var a=MPHB.HotelDataManager.myThis.today,i=null,n=null;return null!==t&&(a=MPHB.HotelDataManager.myThis.reservationRules.getMinCheckOutDate(t,this.searchRoomTypeId),i=MPHB.HotelDataManager.myThis.reservationRules.getMaxCheckOutDate(t,this.searchRoomTypeId),this.isDirectBooking&&(i=this.roomTypeData.getNearestLockedCheckOutDate(t,i),i=this.roomTypeData.getNearestHaveNotPriceDate(t,i)),i=MPHB.HotelDataManager.myThis.dateRules.getNearestNotStayInDate(t,i),n=this.isCheckOutDateNotValid(t,e,a,i)?this.retrieveRecommendedCheckOutDate(t,a,i):e),{minDate:a,maxDate:i,date:n}},retrieveRecommendedCheckOutDate:function(e,a,i){for(var n=null,s=MPHB.Utils.cloneDate(a);MPHB.Utils.formatDateToCompare(s)<=MPHB.Utils.formatDateToCompare(i);){var r=t.datepick.add(MPHB.Utils.cloneDate(s),-1,"d");if(!this.isCheckOutDateNotValid(e,s,a,i)&&(!this.isDirectBooking||this.roomTypeData.hasPriceForDate(r))){n=s;break}s=t.datepick.add(s,1,"d")}return n},isCheckOutDateNotValid:function(t,e,a,i){return null===e||MPHB.Utils.formatDateToCompare(e)