jQuery(function($){"use strict";window.mooGlobalParams={allowScOrders:false,isDeliveryOrder:false,doNotVerifyPhone:false,isGuestPhoneVerified:false,isOtpCodeSent:false,selectedAddress:null,deliveryFees:null,deliveryError:false,isGuest:false,selectedOrderType:null,selectedPaymentMethod:null,selectedTime:null,tipAmount:0,timer:null,couponCode:null,couponAmount:null,couponName:null,points:null,pointsAmount:null,pointsLabel:"Points",grandTotal:0,cartTopPos:null};window.mooCheckout={init:function(){if(!(typeof sooCheckout!=="undefined"&&typeof sooCheckout.options!=="undefined"&&typeof sooCheckout.delivery!=="undefined")){console.log("Checkout Option not loaded correctly, the store is closed or there is an error");this.hideLoadingCheckout();return}this.initSettings();if($("form#soo-add-address-form").length){mooCheckout.addAddressForm=$("form#soo-add-address-form");mooCheckout.addAddressForm.on("submit",this.addNewAddress)}return},initSettings:function(){if(this.canAcceptPoints()){mooGlobalParams.pointsLabel=sooCheckout.options.loyaltySetting.label}else{this.changeElemVisibility("#moo-checkout-form-loyalty","hide")}},startSubmitingAform:function(form){form.data("submitted",true);form.find("button[type=submit]").html('<div class="dot-flashing"></div>');setTimeout(()=>{this.finishSubmitingAform(form)},3e4)},finishSubmitingAform:function(form){form.data("submitted",false);var button=form.find("button[type=submit]");button.html(button.attr("aria-label"))},onInputChange:function(elem){if(elem.value){$(elem).removeClass("moo-has-error");$(elem).parent().removeClass("moo-has-error");$(elem).next().hide()}},editCustomerInfo:function(elm){const customer=this.getLoggedInCustomer();const form=document.createElement("div");form.innerHTML=`
<div class="moo_CheckoutContainer"><div class="moo-edit-profile-form">
    <div class="moo-row">
        <div class="moo-form-group moo-col-md-6">
            <label for="sooContactFirstName" class="moo-checkoutText-fullName">
                First Name:*
            </label>
            <input type="text" class="moo-form-control sooCheckoutTextInput" name="name" id="sooContactFirstName" autocomplete="first_name" value="${customer.first_name}">
        </div>
        <div class="moo-form-group moo-col-md-6">
            <label for="sooContactLastName" class="moo-checkoutText-fullName">
                Last Name:*
            </label>
            <input type="text" class="moo-form-control sooCheckoutTextInput" name="name" id="sooContactLastName" autocomplete="last_name" value="${customer.last_name}">
        </div>
    </div>
    <div class="moo-row">
        <div class="moo-form-group moo-col-md-12">
            <label for="sooContactEmail" class="moo-checkoutText-email">Email:*</label>
            <input type="email" class="moo-form-control sooCheckoutTextInput" id="sooContactEmail" autocomplete="email" value="${customer.email}">
        </div>
    </div>
    <div class="moo-row">
        <div class="moo-form-group moo-col-md-12">
            <label for="sooContactPhone" class="moo-checkoutText-phoneNumber">Phone number:*</label>
            <input type="text" class="moo-form-control sooCheckoutTextInput" name="phone" id="sooContactPhone" autocomplete="phone" value="${customer.phone}">
        </div>
    </div>
</div></div>`;Swal.fire({title:"Edit Your Profile",html:form,showCancelButton:true,cancelButtonText:mooObjectL10n.cancel,confirmButtonText:mooObjectL10n.edit,showLoaderOnConfirm:true,preConfirm:()=>{const firstName=Swal.getPopup().querySelector("#sooContactFirstName").value;const lastName=Swal.getPopup().querySelector("#sooContactLastName").value;const email=Swal.getPopup().querySelector("#sooContactEmail").value;const phone=Swal.getPopup().querySelector("#sooContactPhone").value;if(firstName===""){Swal.showValidationMessage("Your name is required");return}if(email===""){Swal.showValidationMessage("Your email is required");return}if(phone===""){Swal.showValidationMessage("Your phone is required");return}const token=localStorage.getItem("customerJwtToken");return fetch(sooCheckout.options.restApiUrl+"moo-clover/v2/customers/me",{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify({email:email,first_name:firstName,last_name:lastName,phone:phone})}).then(response=>{return response.json()}).then(data=>{if(data.message){throw new Error(data.message)}else{if(data===false){throw new Error(mooObjectL10n.anErrorOccurred)}return data}}).catch(error=>{Swal.showValidationMessage(error)})},allowOutsideClick:false}).then(function(data){if(data.value){localStorage.setItem("loggedInCustomer",JSON.stringify(data.value));mooCheckout.loggedInCustomer=data.value;mooCheckout.fillCustomerInfo()}},function(data){if(data.dismiss==="cancel"){Swal.close()}})},logout:function(e){e.preventDefault();mooCheckout.loggedInCustomer=null;mooCheckout.loggedInCustomer=null;localStorage.removeItem("customerJwtToken");localStorage.removeItem("loggedInCustomer");this.uncheckSelectedOrderingMethod();this.uncheckSelectedPaymentMethod();this.updateTotals();this.showLoginSection();return false},continueAsGuest:function(e){e.preventDefault();mooGlobalParams.isGuest=true;history.pushState({},"Checkout");this.showCheckoutDetails();return false},hideLoadingCheckout(){$("#moo-checkout>#moo-login-section > div.sooOverlayLoader").hide()},showOrHideASection(section,show){$("div.moo-section").hide();const elem=$("#moo-"+section);if(show){elem.show()}else{elem.hide()}},showLoginSection(section,show){$("#sooAuthSection").show();$("div.moo-section").hide();$("#moo-login-section").show()},isCustomerLoggedIn(){return localStorage.getItem("customerJwtToken")!==null},getLoggedInCustomer(){if(localStorage.getItem("loggedInCustomer")){let customer=JSON.parse(localStorage.getItem("loggedInCustomer"));mooCheckout.loggedInCustomer=customer;return customer}return null},getGuestInfo(){const firstName=$("#MooContactFirstName").val();const lastName=$("#MooContactLastName").val();const email=$("#MooContactEmail").val();const phone=$("#MooContactPhone").val();return{first_name:firstName.trim(),last_name:lastName.trim(),email:email.trim(),phone:phone.trim(),isPhoneVerified:mooGlobalParams.isGuestPhoneVerified,address:this.getSelectedAddress(),full_address:this.getSelectedAddressAsString()}},syncLoggedInCustomerProfile(){this.getCustomerProfile().then(async function(response){if(!response.ok){const message=`An error has occured: ${response.status}`;throw new Error(message)}return await response.json()}).then(data=>{localStorage.setItem("loggedInCustomer",JSON.stringify(data));mooCheckout.loggedInCustomer=data}).catch(error=>{console.log(error)})},getCustomerProfile(){let token=localStorage.getItem("customerJwtToken");return fetch(sooCheckout.options.restApiUrl+"moo-clover/v2/customers/me",{method:"GET",mode:"cors",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},redirect:"follow",referrerPolicy:"no-referrer"})},fillCustomerInfo(){if(mooGlobalParams.isGuest){$("#moo-checkout-contact-form").show();$("#moo-checkout-contact-content").hide()}else{let customer=this.getLoggedInCustomer();if(customer){let name=null;if(customer.first_name){name=customer.first_name}if(customer.last_name){name+=" "+customer.last_name}if(!name){name=" "+customer.full_name}$("#moo-checkout-contact-content .soo-contact-info-name").text(name);if(customer.is_email_verified){$("#moo-checkout-contact-content .soo-contact-info-email").text(customer.email+" ✓ ")}else{$("#moo-checkout-contact-content .soo-contact-info-email").text(customer.email)}if(customer.is_phone_verified){$("#moo-checkout-contact-content .soo-contact-info-phone").text(customer.phone+" ✓ ")}else{if(customer.phone===""){$("#moo-checkout-contact-content .soo-contact-info-phone").text("Phone not provided")}else{$("#moo-checkout-contact-content .soo-contact-info-phone").text(customer.phone)}}$("#moo-checkout-contact-form").hide();$("#moo-checkout-contact-content").show()}else{console.log("Can't get the customer, he must login again");this.showLoginSection()}}},fillCustomerPointsBalance(){let customer=this.getLoggedInCustomer();if(customer){let balance=0;let balanceUsdValue=0;if(customer.point_count){balance=customer.point_count;balanceUsdValue=this.getValueOfPoints(balance)}$("#moo-checkout-form-loyalty .loyaltyBalance > div.balance > span.balancePoints").text(balance+" "+mooGlobalParams.pointsLabel);$("#moo-checkout-form-loyalty .loyaltyBalance > div.balance > span.balanceAmount").text(this.formatPrice(balanceUsdValue));if(balance<=0){$("#moo-checkout-form-loyalty .loyaltyButtons > button.sooUsePointsButton").html("Loyalty Conditions").attr("onclick","mooCheckout.openLoyaltyDetails()").css("padding","2px");$("#moo-checkout-form-loyalty .loyaltyButtons").removeClass("moo-col-xs-4").addClass("moo-col-xs-6");$("#moo-checkout-form-loyalty .loyaltyBalance").removeClass("moo-col-xs-6").addClass("moo-col-xs-4")}}else{console.log("Can't get the customer, he must login again")}},shouldVerifyPhone:function(){if(!sooCheckout.options.useSmsVerification){return false}else{if(mooGlobalParams.isGuest){return mooGlobalParams.isGuestPhoneVerified===false}else{const customer=this.getLoggedInCustomer();if(customer){return customer.is_phone_verified===false}else{this.syncLoggedInCustomerProfile();return true}}}},loggedInCustomerPhoneIsVerified:function(){const customer=this.getLoggedInCustomer();if(customer){return customer.is_phone_verified}else{this.syncLoggedInCustomerProfile();return false}},isMobile:function(){if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){return true}return false},getSelectedPaymentMethod:function(){var elm=$('#moo-checkout-form-payments input[name="paymentMethod"]:checked');if(elm.length>0&&elm.val()!==""){return elm.val()}return null},getSelectedOrderingMethod:function(){var elm=$('#moo-checkout-form-ordertypes input[name="ordertype"]:checked');if(elm.length){return elm.val()}return null},countAvailableOrderingMethods:function(){const elmOrderingMethods=$('#moo-checkout-form-ordertypes input[name="ordertype"]');const elmDisabledOrderingMethods=$('#moo-checkout-form-ordertypes input[name="ordertype"]:disabled');if(elmOrderingMethods.length){if(elmDisabledOrderingMethods.length){return elmOrderingMethods.length-elmDisabledOrderingMethods.length}else{return elmOrderingMethods.length}}else{return 0}},countAvailablePaymentMethods:function(){const elmPaymentMethods=$('#moo-checkout-form-payments input[name="paymentMethod"]');if(elmPaymentMethods.length){return elmPaymentMethods.length}else{return 0}},uncheckSelectedOrderingMethod:function(){const elm=$('#moo-checkout-form-ordertypes input[name="ordertype"]:checked');if(elm.length){elm.removeAttr("checked")}mooGlobalParams.selectedOrderType=null;mooGlobalParams.selectedAddress=null;mooGlobalParams.deliveryFees=null;mooGlobalParams.isDeliveryOrder=false;this.hideAddressSection();this.hideDeliveryAmount()},uncheckSelectedPaymentMethod:function(){const elm=$('#moo-checkout-form-payments input[name="paymentMethod"]:checked');if(elm.length){elm.removeAttr("checked")}this.hidePhoneVerificationSection();$("#moo-cloverCreditCardPanel").hide()},getCustomer:function(){if(mooGlobalParams.isGuest){return this.getGuestInfo()}else{const customer=this.getLoggedInCustomer();return{first_name:customer.first_name,last_name:customer.last_name,email:customer.email,phone:customer.phone,isPhoneVerified:customer.is_phone_verified,address:this.getSelectedAddress(),full_address:this.getSelectedAddressAsString()}}},getTipAmount:function(){if(isNaN(mooGlobalParams.tipAmount)||mooCheckout.getSelectedPaymentMethod()==="cash"){return 0}return mooGlobalParams.tipAmount},getSelectedAddress:function(){return mooGlobalParams.selectedAddress},getSelectedAddressAsString:function(){var address=this.getSelectedAddress();var address_string="";if(address){if(address.address)address_string+=address.address+" ";if(address.line2)address_string+=address.line2+" ";if(address.city)address_string+=address.city+", ";if(address.state)address_string+=address.state+" ";if(address.zipcode)address_string+=address.zipcode}return address_string},addNewAddress:function(e){e.preventDefault();if(mooCheckout.addAddressForm.data("submitted")===true){return false}else{mooCheckout.startSubmitingAform(mooCheckout.addAddressForm)}const formElements={fullNameInput:mooCheckout.addAddressForm.find("#sooAddAddressName"),addressInput:mooCheckout.addAddressForm.find("#sooAddAddressLine1"),line2Input:mooCheckout.addAddressForm.find("#sooAddAddressLine2"),cityInput:mooCheckout.addAddressForm.find("#sooAddAddressCity"),stateInput:mooCheckout.addAddressForm.find("#sooAddAddressState"),zipCodeInput:mooCheckout.addAddressForm.find("#sooAddAddressZipCode")};const requiredField=["addressInput","cityInput","stateInput","zipCodeInput"];for(const el in formElements){if(requiredField.includes(el)&&!formElements[el].val()){formElements[el].parent().addClass("moo-has-error");formElements[el].next().show();formElements[el].focus();mooCheckout.finishSubmitingAform(mooCheckout.addAddressForm);return}}mooGlobalParams.selectedAddress={full_name:formElements.fullNameInput.val().trim(),address:formElements.addressInput.val().trim(),line2:formElements.line2Input.val().trim(),city:formElements.cityInput.val().trim(),state:formElements.stateInput.val().trim(),zipcode:formElements.zipCodeInput.val().trim()};if(mooGlobalParams.isGuest){if(mooGlobalParams.selectedOrderType){if(mooGlobalParams.selectedOrderType.ot_uuid==="onDemandDelivery"){mooCheckout.finishSubmitingAform(mooCheckout.addAddressForm);mooCheckout.showListOfAddresses()}else{$.ajax({type:"POST",cache:false,url:sooCheckout.options.restApiUrl+"moo-clover/v3/geocode-address",headers:{"Content-Type":"application/json"},data:JSON.stringify(mooGlobalParams.selectedAddress)}).done(function(response){mooGlobalParams.selectedAddress.lat=response.lat;mooGlobalParams.selectedAddress.lng=response.lng;mooCheckout.finishSubmitingAform(mooCheckout.addAddressForm);const res=mooCheckout.calculateDeliveryFees(mooGlobalParams.selectedAddress.lat,mooGlobalParams.selectedAddress.lng);if(res.result==="zone_error"){mooCheckout.showErrorAlert(res.message,"")}else{mooCheckout.showListOfAddresses()}}).fail(function(response){mooCheckout.finishSubmitingAform(mooCheckout.addAddressForm);let errorMsg="";if(response.responseJSON&&response.responseJSON.message){errorMsg=response.responseJSON.message}else{errorMsg=mooObjectL10n.anErrorOccurred}mooCheckout.showErrorAlert(errorMsg,mooObjectL10n.tryAgain);mooGlobalParams.selectedAddress=null})}}else{mooCheckout.showErrorAlert(mooObjectL10n.error,"Select an Ordering Method")}}else{let token=localStorage.getItem("customerJwtToken");if(!token){console.log("token not found")}$.ajax({type:"POST",cache:false,url:sooCheckout.options.restApiUrl+"moo-clover/v3/customers/addresses",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},data:JSON.stringify(mooGlobalParams.selectedAddress)}).done(function(address){if(address.id){mooCheckout.finishSubmitingAform(mooCheckout.addAddressForm);if(mooCheckout.loggedInCustomer.addresses.length>0){mooCheckout.loggedInCustomer.addresses.push(address)}else{mooCheckout.loggedInCustomer.addresses=[address]}mooCheckout.showListOfAddresses()}else{mooCheckout.showErrorAlert(mooObjectL10n.anErrorOccurred,"")}}).fail(function(data){mooCheckout.finishSubmitingAform(mooCheckout.addAddressForm);let errorMsg="";if(data.responseJSON&&data.responseJSON.message){errorMsg=data.responseJSON.message}else{errorMsg=mooObjectL10n.anErrorOccurred}mooCheckout.showErrorAlert(errorMsg,mooObjectL10n.tryAgain)})}},fillAddressToEdit:function(){if(mooGlobalParams.selectedAddress){const formElements={fullNameInput:mooCheckout.addAddressForm.find("#sooAddAddressName"),addressInput:mooCheckout.addAddressForm.find("#sooAddAddressLine1"),line2Input:mooCheckout.addAddressForm.find("#sooAddAddressLine2"),cityInput:mooCheckout.addAddressForm.find("#sooAddAddressCity"),stateInput:mooCheckout.addAddressForm.find("#sooAddAddressState"),zipCodeInput:mooCheckout.addAddressForm.find("#sooAddAddressZipCode")};if(mooGlobalParams.selectedAddress.full_name){formElements.fullNameInput.val(mooGlobalParams.selectedAddress.full_name)}if(mooGlobalParams.selectedAddress.address){formElements.addressInput.val(mooGlobalParams.selectedAddress.address)}if(mooGlobalParams.selectedAddress.line2){formElements.line2Input.val(mooGlobalParams.selectedAddress.line2)}if(mooGlobalParams.selectedAddress.city){formElements.cityInput.val(mooGlobalParams.selectedAddress.city)}if(mooGlobalParams.selectedAddress.state){formElements.stateInput.val(mooGlobalParams.selectedAddress.state)}if(mooGlobalParams.selectedAddress.zipcode){formElements.zipCodeInput.val(mooGlobalParams.selectedAddress.zipcode)}}},setAddress:function(address){localStorage.setItem("selectedAddress",JSON.stringify(address))},isPhoneVerificationActivated:function(){return sooCheckout.options.useSmsVerification},orderTypeChanged:function(){if(mooGlobalParams.selectedOrderType&&mooCheckout.getSelectedOrderingMethod()===mooGlobalParams.selectedOrderType.ot_uuid){console.log("order type not changed");return}mooGlobalParams.selectedOrderType=mooCheckout.getOneOrderType(mooCheckout.getSelectedOrderingMethod());if(mooGlobalParams.selectedOrderType){const orderType=mooGlobalParams.selectedOrderType;mooGlobalParams.deliveryFees=0;if(this.isTrue(mooGlobalParams.selectedOrderType.allow_sc_order)&&sooCheckout.options.allowScOrder){mooGlobalParams.allowScOrders=true;this.showOrderingTime()}else{mooGlobalParams.allowScOrders=false;this.hideOrderingTime()}if(this.isTrue(mooGlobalParams.selectedOrderType.show_sa)){mooGlobalParams.isDeliveryOrder=true;this.showListOfAddresses();this.showDeliveryAmount();if(mooGlobalParams.allowScOrders){this.changeOrderingTimes("delivery")}if(sooCheckout.options.cashUponDelivery&&orderType.ot_uuid!=="onDemandDelivery"){$("#moo-checkout-form-payincash-label").text(mooObjectL10n.payUponDelivery);this.showCashPayment()}else{this.hideCashPayment()}}else{mooGlobalParams.isDeliveryOrder=false;mooGlobalParams.deliveryFees=0;mooGlobalParams.selectedAddress=null;this.hideAddressSection();this.hideDeliveryAmount();if(mooGlobalParams.allowScOrders){this.changeOrderingTimes("pickup")}if(sooCheckout.options.cashInStore){$("#moo-checkout-form-payincash-label").text(mooObjectL10n.payAtlocation);this.showCashPayment()}else{this.hideCashPayment()}}if(this.isTrue(mooGlobalParams.selectedOrderType.use_coupons)){this.showCouponsSection()}else{this.hideCouponsSection()}this.updateTotals()}else{console.log("No OrderType found")}},paymentMethodChanged:function(){const selectedPaymentMethod=mooCheckout.getSelectedPaymentMethod();if(selectedPaymentMethod==="cash"){this.hideTipSection();$("#moo-cloverCreditCardPanel").hide();$("#moo-cloverGiftCardPanel").hide();if(this.shouldVerifyPhone()){this.showPhoneVerificationSection()}$("#moo_btn_submit_order").show();$("#moo-cloverGooglePay").hide();$("#mooGooglePaySection").hide()}if(selectedPaymentMethod==="clover"){this.showTipSection();this.hidePhoneVerificationSection();$("#moo-cloverGiftCardPanel").hide();$("#moo_btn_submit_order").show();$("#moo-cloverGooglePay").hide();$("#mooGooglePaySection").hide();$("#moo-cloverCreditCardPanel").show()}if(selectedPaymentMethod==="giftcard"){this.showTipSection();$("#moo-cloverCreditCardPanel").hide();this.hidePhoneVerificationSection();$("#moo-cloverGiftCardPanel").show();$("#moo_btn_submit_order").show();$("#moo-cloverGooglePay").hide();$("#mooGooglePaySection").hide()}if(selectedPaymentMethod==="googlepay"){this.showTipSection();$("#moo-cloverCreditCardPanel").hide();this.hidePhoneVerificationSection();$("#moo-cloverGiftCardPanel").hide();$("#moo_btn_submit_order").hide();$("#moo-cloverGooglePay").show();$("#mooGooglePaySection").show()}this.updateTotalsSection(sooCheckout.options.totals)},orderingTimeChanged:function(element){this.updateSelectedTime()},orderingDayChanged:function(element){let html="";const theDay=$(element).val();const times=mooGlobalParams.isDeliveryOrder?sooCheckout.options.deliveryTimes[theDay]:sooCheckout.options.pickupTimes[theDay];if(!(typeof times==="undefined")){html+='<option value="Select a time">Select a time</option>';for(let i in times){html+='<option value="'+times[i]+'">'+times[i]+"</option>"}}else{html=""}$("#moo_pickup_hour").html(html);this.updateSelectedTime()},tipPercentageChanged:function(){const selectedPercentAmount=$("#moo_tips_select").val();if(selectedPercentAmount&&selectedPercentAmount!=="cash"&&selectedPercentAmount!=="other"){const calculatedAmount=sooCheckout.options.totals.sub_total*selectedPercentAmount/100;mooGlobalParams.tipAmount=Math.round(parseInt(calculatedAmount))}else{mooGlobalParams.tipAmount=0;if(selectedPercentAmount==="other"){$("#moo_tips").select()}}$("#moo_tips").val(this.formatPrice(mooGlobalParams.tipAmount));this.updateTotalsSection(sooCheckout.options.totals)},tipAmountChanged:function(){const calculatedAmount=parseInt(Math.ceil(parseFloat($("#moo_tips").val())*100));const amount=Math.round(calculatedAmount);if(!isNaN(amount)&&amount>0){mooGlobalParams.tipAmount=amount;$("#moo_tips").val(this.formatPrice(mooGlobalParams.tipAmount))}else{mooGlobalParams.tipAmount=0;$("#moo_tips").val("0.00")}this.updateTotalsSection(sooCheckout.options.totals)},showListOfAddresses:function(){$("#moo-checkout-form-ordertypes .soo-address-section .soo-add-delivery-address-form").hide();var listAddrElm=$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses");listAddrElm.show();listAddrElm.html("<div  class='soo-addresses-wrapper'><div class='soo-addresses-title'>Loading your addresses...</div></div>");let html="<div  class='soo-addresses-wrapper'>";html+="<div class='soo-estimate-loader'></div>";let addressesProcessed=0;let nbOfAddresses=0;let addresses=[];let cssClasses="";if(mooGlobalParams.isGuest){if(mooGlobalParams.selectedAddress){nbOfAddresses=1;addresses=[mooGlobalParams.selectedAddress]}else{mooCheckout.showAddAddressForm();$("#soo-add-address-form > div > div > button.sooCheckoutSecondaryButtonInput").hide();return}}else{if(mooCheckout.loggedInCustomer){addresses=mooCheckout.loggedInCustomer.addresses;nbOfAddresses=addresses?addresses.length:0}}if(nbOfAddresses===1){mooGlobalParams.selectedAddress=addresses[0];cssClasses="soo-selected";html+="<div class='soo-addresses-title'>Delivery to :</div>"}else{html+="<div class='soo-addresses-title'>Choose a delivery address</div>"}if(nbOfAddresses>0){addresses.forEach(element=>{if(mooGlobalParams.selectedAddress&&mooGlobalParams.selectedAddress.id===element.id){cssClasses="soo-selected"}else{cssClasses=""}html+="<div class='soo-one-address "+cssClasses+"' id='soo-address-"+element.id+"' onclick='mooCheckout.selectAnAddress("+element.id+")'>";if(typeof element.full_name!=="undefined"&&element.full_name!==null){html+="<div class='soo-one-address-name'>"+element.full_name+"</div>"}html+="<div class='soo-one-address-line1'>"+element.address+"</div>";if(element.line2){html+="<div class='soo-one-address-line2'>"+element.line2+"</div>"}html+="<div class='soo-one-address-line2'>"+element.city+" "+element.state+", "+element.zipcode+"</div>";html+="<div class='soo-address-error'></div>";html+="<div class='soo-delivery-amount'></div>";html+="</div>";addressesProcessed++;if(addressesProcessed>=nbOfAddresses){if(mooGlobalParams.isGuest){html+="</div><div class='soo-add-new-address-button'><span onclick='mooCheckout.showEditAddressForm()'>Edit Address</span></div>"}else{html+="</div><div class='soo-add-new-address-button'><span onclick='mooCheckout.showAddAddressForm()'>Add New Address</span></div>"}listAddrElm.html(html);mooCheckout.syncDeliveryFee()}})}else{mooCheckout.showAddAddressForm()}},showAddAddressForm:function(){$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses").hide();$("#moo-checkout-form-ordertypes .soo-address-section .soo-add-delivery-address-form").show();$("#soo-add-address-form > div > div > button.sooCheckoutSecondaryButtonInput").show()},showEditAddressForm:function(){this.showAddAddressForm();if(mooGlobalParams.selectedAddress){this.fillAddressToEdit()}},hideAddressSection:function(){$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses").hide();$("#moo-checkout-form-ordertypes .soo-address-section .soo-add-delivery-address-form").hide()},hideCouponsSection:function(){$("#moo-checkout-form-coupon").hide()},showCouponsSection:function(){$("#moo-checkout-form-coupon").show()},showDeliveryAmount:function(){$("#sooDeliveryFeeTotalSection").show()},hideDeliveryAmount:function(){$("#sooDeliveryFeeTotalSection").hide()},showServiceFeeAmount:function(){$("#sooServiceFeeTotalSection").show()},hideServiceFeeAmount:function(){$("#sooServiceFeeTotalSection").hide()},showTipSection:function(){$("#sooTipsTotalSection").show();$("#moo-checkout-form-tips").show()},hideTipSection:function(){$("#sooTipsTotalSection").hide();$("#moo-checkout-form-tips").hide()},showCashPayment:function(){$(".moo-checkout-form-payments-cash-container").show();$("#moo-checkout-form-payments-cash").val("cash")},hideCashPayment:function(){$(".moo-checkout-form-payments-cash-container").hide();$("#moo_cashPanel").hide();$("#moo-checkout-form-payments-cash").val("");if(this.getSelectedPaymentMethod()==="cash"){this.uncheckSelectedPaymentMethod()}},hidePhoneVerificationSection:function(){$("#moo_cashPanel").hide()},showPhoneVerificationSection:function(){clearInterval(mooGlobalParams.timer);$("#moo_cashPanel").show();const seconds=120;if(mooGlobalParams.isOtpCodeSent){this.changeElemVisibility("#moo_cashPanel > div.soo-phone-button","hide");this.changeElemVisibility("#moo_cashPanel > div.soo-phone-input","show");$("#moo_cashPanel > div.soo-phone-verif-title").text("Sent sms verification to: "+this.getPhoneNumber());$("#moo_cashPanel > div.soo-phone-verif-footer").html("Resend code in <span class='timer'>"+seconds+"</span> seconds");mooGlobalParams.timer=setInterval(this.countDown,1e3)}else{this.changeElemVisibility("#moo_cashPanel > div.soo-phone-button","show");this.changeElemVisibility("#moo_cashPanel > div.soo-phone-input","hide");$("#moo_cashPanel > div.soo-phone-verif-title").text("We will send a verification code via SMS to your number");$("#moo_cashPanel > div.soo-phone-verif-footer").html("")}},selectAnAddress:function(id){if(!mooGlobalParams.isGuest){$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address").removeClass("soo-selected soo-selected-error soo-selected-warning");$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address .soo-address-error").text("");$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address .soo-delivery-amount").text("");$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses #soo-address-"+id).addClass("soo-selected");mooGlobalParams.selectedAddress=this.getAddressById(id);this.syncDeliveryFee()}},unSelectAddress:function(id){$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address").removeClass("soo-selected soo-selected-error soo-selected-warning");$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address .soo-address-error").text("");$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address .soo-delivery-amount").text("")},syncDeliveryFee:function(){if(mooGlobalParams.selectedAddress){const addrElm=$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses #soo-address-"+mooGlobalParams.selectedAddress.id);const amountPos=-1/2*parseFloat(addrElm.css("height"))+6;if(mooGlobalParams.selectedOrderType&&mooGlobalParams.selectedOrderType.ot_uuid==="onDemandDelivery"){$(".soo-delivery-amount",addrElm).css("top",amountPos+"px");this.createOnDemandDeliveryEstimate()}else{const res=this.calculateDeliveryFees(mooGlobalParams.selectedAddress.lat,mooGlobalParams.selectedAddress.lng);if(res.result==="success"){mooGlobalParams.selectedAddress.isValid=true;let deliveryAmount;if(!isNaN(res.amount)&&res.amount>0){mooGlobalParams.deliveryFees=res.amount;deliveryAmount=parseFloat(res.amount/100).toFixed(2);deliveryAmount="+ $"+deliveryAmount}else{mooGlobalParams.deliveryFees=0;deliveryAmount="Free"}$(".soo-delivery-amount",addrElm).text(deliveryAmount).css("top",amountPos+"px")}else{mooGlobalParams.selectedAddress.isValid=false}if(res.result==="zone_error"){addrElm.addClass("soo-selected-error");$(".soo-address-error",addrElm).text(res.message);mooGlobalParams.deliveryFees=null}if(res.result==="min_error"){addrElm.addClass("soo-selected-warning");$(".soo-address-error",addrElm).text(res.message);mooGlobalParams.deliveryFees=null}mooCheckout.updateTotals()}}},getAddressById:function(id){if(mooCheckout.loggedInCustomer){for(var i=0;i<mooCheckout.loggedInCustomer.addresses.length;i++){if(mooCheckout.loggedInCustomer.addresses[i].id===id)return mooCheckout.loggedInCustomer.addresses[i]}}return null},getOneOrderType:function(orderTypeUuid){if(typeof sooCheckout.options.orderTypes!=="undefined"){for(var i in sooCheckout.options.orderTypes){if(orderTypeUuid===sooCheckout.options.orderTypes[i].ot_uuid){return sooCheckout.options.orderTypes[i]}}}return null},changeElemVisibility:function(selector,showOrHide){if(showOrHide==="show"){$(selector).show()}if(showOrHide==="hide"){$(selector).hide()}},hideOrderingTime:function(){this.changeElemVisibility("#moo-checkout-form-orderdate","hide")},showOrderingTime:function(){this.changeElemVisibility("#moo-checkout-form-orderdate","show")},getPhoneNumber:function(){if(mooGlobalParams.isGuest){const customer=this.getGuestInfo();return customer.phone}else{const customer=this.getLoggedInCustomer();return customer.phone}},sendCodeToVerifyPhone:function(){const btnSend=$("#moo_cashPanel > div.soo-phone-button > button");const btnSendTxt=btnSend.html();const phone=this.getPhoneNumber();const seconds=120;if(phone===""){mooCheckout.showErrorAlert(mooObjectL10n.enterYourPhone,"");return}btnSend.html('<div class="dot-flashing"></div>');let token=localStorage.getItem("customerJwtToken");if(!token&&!mooGlobalParams.isGuest){return}const url=mooGlobalParams.isGuest?"moo-clover/v2/guests/send-code":"moo-clover/v2/customers/send-code";fetch(sooCheckout.options.restApiUrl+url,{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify({phone:phone})}).then(response=>{if(!response.ok){return response.json()}else{mooGlobalParams.isOtpCodeSent=true;this.showPhoneVerificationSection();btnSend.html(btnSendTxt);return response.json()}}).then(data=>{btnSend.html(btnSendTxt);if(typeof data!=="undefined"&&data.message){if(data.message==="You just sent the verification code please try later"){mooGlobalParams.isOtpCodeSent=true;this.showPhoneVerificationSection()}else{Swal.fire({icon:"success",title:data.message})}}else{if(data===false){throw mooObjectL10n.anErrorOccurred}}}).catch(error=>{btnSend.html(btnSendTxt);mooCheckout.showErrorAlert(error,"")})},verifyCodeSentToPhone:function(){const btn=$("#moo_cashPanel > div.soo-phone-input > button");const btnTxt=btn.html();const numReg=/^\d+\.?\d*$/;const phone=this.getPhoneNumber();const code=$("#moo_cashPanel > div.soo-phone-input > input").val();const seconds=120;if(code.length!==6||!numReg.test(code)){mooCheckout.showErrorAlert(mooObjectL10n.codeInvalid,mooObjectL10n.codeInvalidDetails);return}btn.html('<div class="dot-flashing"></div>');let token=localStorage.getItem("customerJwtToken");if(!token&&!mooGlobalParams.isGuest){return}const url=mooGlobalParams.isGuest?"moo-clover/v2/guests/check-code":"moo-clover/v2/customers/check-code";fetch(sooCheckout.options.restApiUrl+url,{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify({code:code,phone:phone})}).then(response=>{if(!response.ok){return response.json()}else{btn.html(btnTxt);clearInterval(mooGlobalParams.timer);mooCheckout.showSuccessAlert(mooObjectL10n.phoneVerified,mooObjectL10n.phoneVerifiedDetails);mooGlobalParams.isOtpCodeSent=false;this.hidePhoneVerificationSection();if(mooGlobalParams.isGuest){mooGlobalParams.isGuestPhoneVerified=true}else{this.getCustomerProfile().then(async function(response){if(!response.ok){const message=`An error has occured: ${response.status}`;throw new Error(message)}return await response.json()}).then(data=>{localStorage.setItem("loggedInCustomer",JSON.stringify(data));mooCheckout.loggedInCustomer=data;mooCheckout.fillCustomerInfo()}).catch(error=>{console.log(error)})}}}).then(data=>{btn.html(btnTxt);if(typeof data!=="undefined"&&data.message){throw data.message}else{if(data===false){throw mooObjectL10n.anErrorOccurred}}}).catch(error=>{btn.html(btnTxt);mooCheckout.showErrorAlert(error,"")})},countDown:function(){let sec=parseInt($("#moo_cashPanel > div.soo-phone-verif-footer>.timer").text());$("#moo_cashPanel > div.soo-phone-verif-footer>.timer").text(--sec);if(sec<=0){$("#moo_cashPanel > div.soo-phone-verif-footer").html("<div onclick='mooCheckout.sendCodeToVerifyPhone()'>Resend code</div>");clearInterval(mooGlobalParams.timer)}},finalizeOrder:function(e){e.preventDefault();$("#moo_btn_submit_order").hide();$("#moo_checkout_loading").show();$("#moo-checkout .errors-section").html("");try{window.mooCheckout.getCheckoutForm()}catch(e){console.log(e);window.mooCheckout.stopLoading();window.mooCheckout.showErrorAlert(mooObjectL10n.anErrorOccurred)}},verifyCheckoutForm:function(form){var regex_exp={email:/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/};var message_errors={};const selectedOrderType=mooGlobalParams.selectedOrderType;if(form.customer.first_name===""&&form.customer.last_name===""){mooCheckout.showErrorAlert(mooObjectL10n.enterYourName,"","#MooContactFirstName");return false}if(form.customer.email===""||!regex_exp.email.test(form.customer.email)){mooCheckout.showErrorAlert(mooObjectL10n.enterYourEmail,mooObjectL10n.enterYourEmailReason,"#MooContactEmail");return false}if(form.customer.phone===""){mooCheckout.showErrorAlert(mooObjectL10n.enterYourPhone,mooObjectL10n.enterYourPhoneReason,"#MooContactPhone");return false}if(document.getElementById("moo-checkout-form-ordertypes")){if(typeof form.order_type==="undefined"||form.order_type===""){mooCheckout.showErrorAlert(mooObjectL10n.chooseOrderingMethod,mooObjectL10n.chooseOrderingMethodReason,"#moo-checkout-form-ordertypes");return false}}if(selectedOrderType){var minAmount=parseFloat(selectedOrderType.minAmount);var maxAmount=parseFloat(selectedOrderType.maxAmount);if(!isNaN(minAmount)){minAmount=minAmount*100;minAmount=Math.round(minAmount*100)/100;if(minAmount>0&&minAmount>sooCheckout.options.totals.sub_total){this.stopLoading();Swal.fire({title:mooObjectL10n.YouDidNotMeetMinimum,text:mooObjectL10n.orderingMethodSubtotalGreaterThan+mooformatCentPrice(minAmount),icon:"warning",showCancelButton:true,confirmButtonColor:"#DD6B55",confirmButtonClass:"fontSizeLg",confirmButtonText:mooObjectL10n.continueToCheckout,cancelButtonText:mooObjectL10n.continueShopping}).then(data=>{if(data.dismiss&&data.dismiss==="cancel"){if(sooCheckout.options.storeLink){window.location.href=sooCheckout.options.storeLink}}});return false}}if(!isNaN(maxAmount)){maxAmount=maxAmount*100;maxAmount=Math.round(maxAmount*100)/100;if(maxAmount&&maxAmount<sooCheckout.options.totals.sub_total){this.stopLoading();Swal.fire({title:mooObjectL10n.reachedMaximumPurchaseAmount,text:mooObjectL10n.orderingMethodSubtotalLessThan+mooformatCentPrice(maxAmount),icon:"warning",showCancelButton:true,confirmButtonColor:"#DD6B55",confirmButtonText:mooObjectL10n.updateCart,cancelButtonText:mooObjectL10n.checkout,closeOnConfirm:false}).then(function(data){if(data.value){Swal.close();window.location.href=moo_params.cartPage}});return false}}if(mooCheckout.isTrue(selectedOrderType.show_sa)){if(mooGlobalParams.selectedAddress){if(!mooGlobalParams.selectedAddress.isValid){mooCheckout.showErrorAlert(mooObjectL10n.verifyYourAddress,"Sorry, we are unable to deliver to this address. Please provide a different address or kindly get in touch with us if you feel are within the delivery range.","#moo-checkout-form-ordertypes>.moo-checkout-bloc-message");return false}}else{mooCheckout.showErrorAlert(mooObjectL10n.addDeliveryAddress,mooObjectL10n.addDeliveryAddressReason,"#moo-checkout-form-ordertypes>.moo-checkout-bloc-message .MooSimplButon");return false}}}if(mooGlobalParams.allowScOrders){if(sooCheckout.options.orderingTimeRequired){if(form.pickup_hour===""||form.pickup_hour==="Select a time"){mooCheckout.showErrorAlert(mooObjectL10n.chooseTime,"","#moo-checkout-form-orderdate");return false}}}if(sooCheckout.options.specialInstructionsRequired){if(typeof form.special_instructions==="undefined"||form.special_instructions===""){mooCheckout.showErrorAlert(mooObjectL10n.SpecialInstructionsRequired,"","#moo-checkout-form-instruction");return false}}if(form.tip_amount>0&&this.getOrderTotal()===0){mooCheckout.showErrorAlert("Unable to Include Tips for $0 Orders","To enhance your experience, kindly note that we are unable to include tips when the Order Total is $0. However, you have the option to show your appreciation by providing a tip upon order pickup or delivery. We appreciate your understanding.","#moo-checkout-form-tips");return false}if(typeof form.payment_method==="undefined"||form.payment_method===""){mooCheckout.showErrorAlert(mooObjectL10n.choosePaymentMethod,"","#moo-checkout-form-payments");return false}else{if(form.payment_method==="cash"){if(mooCheckout.shouldVerifyPhone()){if(mooGlobalParams.isGuest&&!mooGlobalParams.isGuestPhoneVerified||!mooGlobalParams.isGuest&&!mooCheckout.loggedInCustomerPhoneIsVerified()){mooCheckout.showPhoneVerificationSection();mooCheckout.showErrorAlert(mooObjectL10n.verifyYourPhone,mooObjectL10n.verifyYourPhoneReason,"#moo-checkout-form-payments");return false}}this.submitForm(form)}if(form.payment_method==="clover"){if(window.cloverCardIsValid){window.clover.createToken().then(function(response){if(response.token){form.token=response.token;form.card=response.card;window.mooCheckout.submitForm(form)}else{mooCheckout.showErrorAlert(mooObjectL10n.verifyYourCreditCard,"","#moo-checkout-form-payments");return false}})}else{mooCheckout.showErrorAlert(mooObjectL10n.verifyYourCreditCard,window.cloverCardErrorMsg,"#moo-checkout-form-payments");return false}}if(form.payment_method==="giftcard"){if(window.cloverGiftCardIsValid){try{const timeoutId=setTimeout(()=>{mooCheckout.showErrorAlert("Please verify the gift card information","","#moo-checkout-form-payments")},1e4);window.clover.createGiftCardToken().then(function(response){clearTimeout(timeoutId);if(response.token){form.payment_method="clover";form.selected_payment_method="giftcard";form.token=response.token;window.mooCheckout.submitForm(form)}else{mooCheckout.showErrorAlert("Please verify the gift card information","","#moo-checkout-form-payments");return false}})}catch(err){console.log(err)}}else{mooCheckout.showErrorAlert("Please verify the gift card information","","#moo-checkout-form-payments");return false}}if(form.payment_method==="googlepay"){if(window.googlePayToken){try{form.payment_method="clover";form.token=window.googlePayToken.token;form.selected_payment_method="googlepay";form.googledata=window.googlePayToken;window.mooCheckout.submitForm(form)}catch(err){console.log(err)}}else{mooCheckout.showErrorAlert("Please Try Again","","#moo-checkout-form-payments");return false}}}},getCheckoutForm:function(){var form={channel:"website",customer:null,metainfo:[{name:"source_url",value:window.location.href},{name:"checkout_version",value:"new"}]};form.customer=mooCheckout.getCustomer();form.tip_amount=mooCheckout.getTipAmount();form.special_instructions=$("#Mooinstructions").val();form.pickup_day=$("#moo_pickup_day").val();form.pickup_hour=$("#moo_pickup_hour").val();form.orderingTime=mooGlobalParams.selectedTime;if(document.getElementById("moo-checkout-form-ordertypes")){form.order_type=$('input[name="ordertype"]:checked').val()}form.payment_method=$('#moo-checkout-form-payments input[name="paymentMethod"]:checked').val();form.delivery_amount=mooCheckout.getDeliveryFees();form.service_fee=mooCheckout.getServiceFees();if(this.canAcceptCoupons()){form.coupon={code:mooGlobalParams.couponCode}}if(this.canAcceptPoints()){form.use_points=parseInt(mooGlobalParams.points)}form.totals=mooCheckout.getTotals();this.verifyCheckoutForm(form)},submitForm:function(form){if(form.order_type==="onDemandDelivery"){let deliveryTime=(new Date).toISOString();if(mooGlobalParams.selectedTime){deliveryTime=mooGlobalParams.selectedTime}this.createDeliveryEstimate().then(response=>{if(!response.ok){throw new Error(mooObjectL10n.anErrorOccurred)}else{return response.json()}}).then(res=>{if(res.status==="success"){form.delivery_estimate=res;form.delivery_time=deliveryTime;this.createOrder(form)}else{throw new Error(res.message)}}).catch(err=>{this.showErrorAlert(err.message,"")})}else{this.createOrder(form)}},createOrder:function(form){if(sooCheckout.options.reCAPTCHA_site_key){grecaptcha.ready(function(){grecaptcha.execute(sooCheckout.options.reCAPTCHA_site_key,{action:"createOrder"}).then(token=>{console.log(token);form.reCAPTCHA_token=token;mooCheckout.sendCreateOrder(form)})})}else{mooCheckout.sendCreateOrder(form)}return;let headers={"Content-Type":"application/json"};if(this.isCustomerLoggedIn()){form.customer_token=localStorage.getItem("customerJwtToken")}$.ajax({type:"POST",cache:false,url:sooCheckout.options.restApiUrl+"moo-clover/v2/checkout",headers:headers,data:JSON.stringify(form)}).done(function(data){if(typeof data=="object"){if(data.status==="success"){mooCheckout.trackConversion(true,form);mooCheckout.successfulOrder(data.id)}else{mooCheckout.trackConversion(false,form);mooCheckout.failedOrder(data.message)}}else{if(data.indexOf('"status":"success"')!==-1){mooCheckout.trackConversion(true,form);mooCheckout.successfulOrder("")}else{mooCheckout.trackConversion(false,form);mooCheckout.failedOrder("")}}}).fail(function(data){console.log("FAIL");console.log(data.responseText);if(data.responseText.indexOf('"status":"success"')!==-1){mooCheckout.trackConversion(true,form);mooCheckout.successfulOrder("")}else{mooCheckout.trackConversion(false,form);mooCheckout.failedOrder("")}})},sendCreateOrder:function(form){let headers={"Content-Type":"application/json"};if(this.isCustomerLoggedIn()){form.customer_token=localStorage.getItem("customerJwtToken")}$.ajax({type:"POST",cache:false,url:sooCheckout.options.restApiUrl+"moo-clover/v2/checkout",headers:headers,data:JSON.stringify(form)}).done(function(data){if(typeof data=="object"){if(data.status==="success"){mooCheckout.trackConversion(true,form);mooCheckout.successfulOrder(data.id)}else{mooCheckout.trackConversion(false,form);mooCheckout.failedOrder(data.message)}}else{if(data.indexOf('"status":"success"')!==-1){mooCheckout.trackConversion(true,form);mooCheckout.successfulOrder("")}else{mooCheckout.trackConversion(false,form);mooCheckout.failedOrder("")}}}).fail(function(data){console.log("FAIL");console.log(data.responseText);if(data.responseText.indexOf('"status":"success"')!==-1){mooCheckout.trackConversion(true,form);mooCheckout.successfulOrder("")}else{mooCheckout.trackConversion(false,form);mooCheckout.failedOrder("")}})},successfulOrder:function(orderId){if(sooCheckout.options.thanksPage&&sooCheckout.options.thanksPage!==""){window.location.href=sooCheckout.options.thanksPage+"?order_id="+orderId}else{let html='<div class="moo-alert moo-alert-success" role="alert" style="font-size: 20px;text-align: center">';html+=mooObjectL10n.thanksForOrder;html+="<br/>";html+=mooObjectL10n.orderBeingPrepared;if(orderId!==""){html+="<br>";html+=mooObjectL10n.seeReceipt;html+=sooCheckout.options.isSandbox?' <a href="https://sandbox.dev.clover.com/r/'+orderId+'" target="_blank">':' <a href="https://www.clover.com/r/'+orderId+'" target="_blank">';html+=mooObjectL10n.here;html+="</a>"}html+="</div>";$("#moo_checkout_msg").remove();$("#moo-checkout").html("");if(sooCheckout.delivery.moo_merchantAddress!==""){$("#moo-checkout").parent().prepend("<div style='text-align: center'><p style='font-size: 21px;'>"+mooObjectL10n.ourAddress+" : </p>"+sooCheckout.delivery.moo_merchantAddress+"</div>")}$("#moo-checkout").parent().prepend(html);$("html, body").animate({scrollTop:0},600)}},failedOrder:function(failureMessage){let html="";this.stopLoading();if(failureMessage&&failureMessage!==""&&failureMessage!==undefined){html='<div class="moo-alert moo-alert-danger" role="alert" id="moo_checkout_msg">'+failureMessage+"</div>"}else{html='<div class="moo-alert moo-alert-warning" role="alert" id="moo_checkout_msg"><strong>';html+=mooObjectL10n.cannotSendEntireOrder;html+="</strong></div>"}$("#moo-checkout .errors-section").html(html);$("html, body").animate({scrollTop:0},600)},getCustomerSelectedAddress:function(){return{}},getDeliveryFees:function(){return mooGlobalParams.deliveryFees},getServiceFees:function(){let fee=sooCheckout.options.feeAmount;if(fee){if(mooGlobalParams.selectedOrderType){if(mooCheckout.isTrue(mooGlobalParams.selectedOrderType.allow_service_fee)){if(sooCheckout.options.feeType==="amount"){return fee}else{return Math.round(fee*sooCheckout.options.totals.sub_total/100)}}}else{if($("#sooServiceFeeTotalSection").css("display")==="block"){if(sooCheckout.options.feeType==="amount"){return fee}else{return Math.round(fee*sooCheckout.options.totals.sub_total/100)}}}}return 0},createOnDemandDeliveryEstimate:function(){if(mooGlobalParams.selectedAddress){const addrElm=$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses #soo-address-"+mooGlobalParams.selectedAddress.id);const loader=$("#moo-checkout-form-ordertypes div.soo-address-section > div.soo-list-of-addresses > div.soo-addresses-wrapper>.soo-estimate-loader");$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address").removeClass("soo-selected-error soo-selected-warning");$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address .soo-address-error").text("");$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses .soo-one-address .soo-delivery-amount").text("");$(".soo-delivery-amount",addrElm).html('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" class="BpkSpinner_bpk-spinner__NjNlZ BpkSpinner_bpk-spinner--primary__YTQxN"><rect width="4" height="2" y="7" opacity=".45" rx="1"></rect><rect width="4" height="2" x="12" y="7" rx="1"></rect><rect width="4" height="2" x="7" y="16" opacity=".3" rx="1" transform="rotate(-90 7 16)"></rect><rect width="4" height="2" x="7" y="4" opacity=".65" rx="1" transform="rotate(-90 7 4)"></rect><rect width="4" height="2" x="11.134" y="15.428" opacity=".25" rx="1" transform="rotate(-120 11.134 15.428)"></rect><rect width="4" height="2" x="5.134" y="5.036" opacity=".55" rx="1" transform="rotate(-120 5.134 5.036)"></rect><rect width="4" height="2" x="14.428" y="12.866" opacity=".2" rx="1" transform="rotate(-150 14.428 12.866)"></rect><rect width="4" height="2" x="4.036" y="6.866" opacity=".5" rx="1" transform="rotate(-150 4.036 6.866)"></rect><rect width="4" height="2" x="15.428" y="4.866" opacity=".85" rx="1" transform="rotate(150 15.428 4.866)"></rect><rect width="4" height="2" x="5.036" y="10.866" opacity=".4" rx="1" transform="rotate(150 5.036 10.866)"></rect><rect width="4" height="2" x="12.866" y="1.572" opacity=".75" rx="1" transform="rotate(120 12.866 1.572)"></rect><rect width="4" height="2" x="6.866" y="11.964" opacity=".35" rx="1" transform="rotate(120 6.866 11.964)"></rect></svg>');loader.show();let deliveryTime=(new Date).toISOString();if(mooGlobalParams.selectedTime){deliveryTime=mooGlobalParams.selectedTime}this.createDeliveryEstimate().then(response=>{if(!response.ok){$(".soo-delivery-amount",addrElm).text("");loader.hide();mooCheckout.unSelectAddress();if(mooGlobalParams.selectedAddress){mooGlobalParams.selectedAddress.isValid=false}throw new Error(mooObjectL10n.anErrorOccurred)}else{return response.json()}}).then(res=>this.displayDeliveryAmountForAddress(res)).catch(err=>{mooCheckout.showErrorAlert(err.message,"")})}},calculateDeliveryFees:function(lat,lng){var order_total=parseFloat(sooCheckout.options.totals.sub_total);const delivery_free_after=Math.round(parseFloat(sooCheckout.delivery.free_amount)*100);const delivery_fixed_amount=Math.round(parseFloat(sooCheckout.delivery.fixed_amount)*100);const delivery_for_other_zone=Math.round(parseFloat(sooCheckout.delivery.other_zone_fee)*100);let moo_delivery_areas=null;try{moo_delivery_areas=JSON.parse(sooCheckout.delivery.zones)}catch(e){console.log("Parsing error: moo_delivery_areas")}if(!isNaN(delivery_fixed_amount)){return{result:"success",amount:delivery_fixed_amount,message:null}}if(!(lat!==""&&lng!=="")){return{result:"zone_error",amount:null,message:mooObjectL10n.deliveryZoneNotSupported}}else{var zones_contain_point=[];for(const i in moo_delivery_areas){var zone=moo_delivery_areas[i];if(zone.feeType==="percent"){zone.fee=parseFloat(zone.fee)}else{zone.fee=Math.round(parseFloat(zone.fee)*100)}zone.minAmount=Math.round(parseFloat(zone.minAmount)*100);if(zone.type==="polygon"){if(google.maps.geometry.poly.containsLocation(new google.maps.LatLng(parseFloat(lat),parseFloat(lng)),new google.maps.Polygon({paths:zone.path}))){zones_contain_point.push({zone_id:zone.id,zone_fee:zone.fee,feeType:zone.feeType,minAmount:zone.minAmount})}}if(zone.type==="circle"){var point=new google.maps.LatLng(parseFloat(lat),parseFloat(lng));var center=new google.maps.LatLng(parseFloat(zone.center.lat),parseFloat(zone.center.lng));if(google.maps.geometry.spherical.computeDistanceBetween(point,center)<=zone.radius){zones_contain_point.push({zone_id:zone.id,zone_fee:zone.fee,feeType:zone.feeType,minAmount:zone.minAmount})}}}if(zones_contain_point.length>=1){var delivery_final_amount=zones_contain_point[0].feeType==="percent"?zones_contain_point[0].zone_fee*order_total/100:zones_contain_point[0].zone_fee;var delivery_zone_id=zones_contain_point[0].zone_id;var delivery_zone_minAmount=zones_contain_point[0].minAmount;for(const i in zones_contain_point){if(zones_contain_point[i].feeType==="percent"){const amount=parseFloat(zones_contain_point[i].zone_fee)*order_total/100;if(delivery_final_amount>=amount){delivery_final_amount=amount;delivery_zone_id=zones_contain_point[i].zone_id;delivery_zone_minAmount=zones_contain_point[i].minAmount}}else{if(delivery_final_amount>=zones_contain_point[i].zone_fee){delivery_final_amount=zones_contain_point[i].zone_fee;delivery_zone_id=zones_contain_point[i].zone_id;delivery_zone_minAmount=zones_contain_point[i].minAmount}}}if(!isNaN(delivery_zone_minAmount)){if(delivery_zone_minAmount>sooCheckout.options.totals.sub_total){return{result:"min_error",amount:null,message:mooObjectL10n.minimumForDeliveryZone+parseFloat(delivery_zone_minAmount/100).toFixed(2)}}}if(isNaN(delivery_free_after)){return{result:"success",amount:delivery_final_amount,message:null}}else{var amountToAdd=delivery_free_after-order_total;if(amountToAdd<=0){return{result:"success",amount:0,message:null}}else{Swal.fire({title:mooObjectL10n.spend+parseFloat(delivery_free_after/100).toFixed(2)+" "+mooObjectL10n.toGetFreeDelivery,text:"Add $"+parseFloat(amountToAdd/100).toFixed(2)+" to your order to enjoy free delivery",icon:"warning",showCancelButton:true,confirmButtonColor:"#6e7881",confirmButtonClass:"fontSizeLg",cancelButtonColor:"#DD6B55",confirmButtonText:mooObjectL10n.continueToCheckout,cancelButtonText:mooObjectL10n.continueShopping}).then(data=>{if(data.dismiss&&data.dismiss==="cancel"){if(sooCheckout.options.storeLink){window.location.href=sooCheckout.options.storeLink}else{window.history.back()}}});if(amountToAdd>0&&amountToAdd<delivery_final_amount){delivery_final_amount=amountToAdd}return{result:"success",amount:delivery_final_amount,message:null}}}}else{if(isNaN(delivery_for_other_zone)){return{result:"zone_error",amount:null,message:mooObjectL10n.deliveryZoneNotSupported}}else{return{result:"success",amount:delivery_for_other_zone,message:null}}}}},formatPrice:function(priceInCentes){var p=priceInCentes/100;p=p.toFixed(2);return p.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")},updateTotals:function(){const totals=sooCheckout.options.totals;if(totals===false){return}const deliveryAmount=this.getDeliveryFees();const serviceFee=this.getServiceFees();const discounts=this.getDiscountedAmount();this.startLoadingDeliveryFee();this.getOrderTotals(deliveryAmount+serviceFee,discounts,this.updateTotalsSection)},getTotals:function(){return{tipAmount:mooCheckout.getTipAmount(),deliveryAmount:mooCheckout.getDeliveryFees(),serviceFee:this.getServiceFees(),discounts:this.getDiscountedAmount(),couponAmount:mooGlobalParams.couponAmount,pointsAmount:mooGlobalParams.pointsAmount,grandTotal:mooGlobalParams.grandTotal,orderTaxable:mooCheckout.isOrderTaxable()}},updateTotalsSection:function(totals){mooGlobalParams.grandTotal=0;const tips_amount=mooCheckout.getTipAmount();const delivery_amount=mooCheckout.getDeliveryFees();const service_fee=mooCheckout.getServiceFees();const discounts=mooCheckout.getDiscountedAmount();const orderTaxable=mooCheckout.isOrderTaxable();if(service_fee===0){mooCheckout.hideServiceFeeAmount()}else{mooCheckout.showServiceFeeAmount();$("#sooServiceFeeTotalSection > .moo-totals-value").text(" $"+mooCheckout.formatPrice(service_fee))}mooCheckout.stopLoadingDeliveryFee();if(discounts===0){$("#sooCouponTotalSection").hide();$("#sooPointsTotalSection").hide()}else{if(mooCheckout.canAcceptCoupons()&&mooGlobalParams.couponAmount){$("#sooCouponTotalSection").show();$("#sooCouponName").text(mooGlobalParams.couponName);$("#sooCouponValue").text(" -$"+mooCheckout.formatPrice(mooGlobalParams.couponAmount))}else{$("#sooCouponTotalSection").hide()}if(mooCheckout.canAcceptPoints()&&mooGlobalParams.pointsAmount){$("#sooPointsTotalSection").show();$("#sooPointslabel").text(mooGlobalParams.points+" "+mooGlobalParams.pointsLabel);$("#sooPointsValue").text(" -$"+mooCheckout.formatPrice(mooGlobalParams.pointsAmount))}else{$("#sooPointsTotalSection").hide()}}$(".moo-totals-value").fadeOut(300,function(){$("#moo-cart-subtotal").html("$"+mooCheckout.formatPrice(totals.sub_total));$("#moo-cart-tip").html("$"+mooCheckout.formatPrice(tips_amount));$("#moo-cart-delivery-fee").html("$"+mooCheckout.formatPrice(delivery_amount));if(orderTaxable){if(discounts===0){mooGlobalParams.grandTotal=totals.sub_total+totals.taxes+tips_amount+delivery_amount+service_fee;$("#moo-cart-tax").html("$"+mooCheckout.formatPrice(totals.taxes));$("#moo-cart-total").html("$"+mooCheckout.formatPrice(mooGlobalParams.grandTotal))}else{mooGlobalParams.grandTotal=totals.sub_total+totals.taxes_after_discount+tips_amount+delivery_amount+service_fee-discounts;$("#moo-cart-tax").html("$"+mooCheckout.formatPrice(totals.taxes_after_discount));$("#moo-cart-total").html("$"+mooCheckout.formatPrice(mooGlobalParams.grandTotal))}}else{mooGlobalParams.grandTotal=totals.sub_total+tips_amount+delivery_amount+service_fee-discounts;$("#moo-cart-tax").html("0.00");$("#moo-cart-total").html("$"+mooCheckout.formatPrice(mooGlobalParams.grandTotal))}$(".moo-totals-value").fadeIn(300)})},getOrderTotals:function(charges,discounts,callback){$.ajax({type:"POST",cache:false,url:sooCheckout.options.restApiUrl+"moo-clover/v3/checkout/order_totals",contentType:"application/json; charset=UTF-8",data:JSON.stringify({charges:charges,discounts:discounts})}).done(function(data){sooCheckout.options.totals=data;callback(data)}).fail(function(data){console.log("FAIL");console.log(data.responseText)})},showErrorAlert:function(title,message,focusOnElem=null){this.stopLoading();if(focusOnElem){Swal.fire({title:title,text:message,icon:"error"}).then(function(){setTimeout(function(){$(focusOnElem).focus()},500)})}else{Swal.fire({title:title,text:message,icon:"error"})}},showSuccessAlert:function(title,message,focusOnElem=null){this.stopLoading();if(focusOnElem){Swal.fire(title,message,"success").then(function(){setTimeout(function(){$(focusOnElem).focus()},500)})}else{Swal.fire(title,message,"success")}},stopLoading:function(){if(this.getSelectedPaymentMethod()==="googlepay"){$("#moo_checkout_loading").hide();$("#moo-cloverGooglePay").show()}else{$("#moo_checkout_loading").hide();$("#moo_btn_submit_order").show()}},startLoadingDeliveryFee:function(){$("#sooDeliveryFeeTotalSection").addClass("moo-fade-in");$(".moo-totals-item-total").addClass("moo-fade-in")},stopLoadingDeliveryFee:function(){$("#sooDeliveryFeeTotalSection").removeClass("moo-fade-in");$(".moo-totals-item-total").removeClass("moo-fade-in")},trackConversion:function(status,form){if(typeof dataLayer!=="undefined"){try{if(status){dataLayer.push({event:"OrderCreated",amount:sooCheckout.options.totals.total/100,taxes:sooCheckout.options.totals.total_of_taxes/100,tips:form.tip_amount/100,nbOfItems:sooCheckout.options.totals.nb_items})}else{dataLayer.push({event:"OrderNotCreated",amount:sooCheckout.options.totals.total/100,taxes:sooCheckout.options.totals.total_of_taxes/100,tips:form.tip_amount/100,nbOfItems:sooCheckout.options.totals.nb_items})}}catch(e){console.log(e)}}},isTrue:function(param){return param===true||param===1||param==="1"||param==="true"},changeOrderingTimes:function(type){var dayInput=$("#moo_pickup_day");var hoursInput=$("#moo_pickup_hour");var html_days="";var html_hours="";let times=null;if(type==="pickup"){if(sooCheckout.options.pickupTimes===null){$("#moo-checkout-form-orderdate .extra-info").html("There are no time slots available. Please try again later. Thank you for your understanding and patience.");return}for(let i in sooCheckout.options.pickupTimes){html_days+='<option value="'+i+'">'+i+"</option>"}times=sooCheckout.options.pickupTimes[Object.keys(sooCheckout.options.pickupTimes)[0]]}if(type==="delivery"){if(sooCheckout.options.deliveryTimes===null){$("#moo-checkout-form-orderdate .extra-info").html("There are no time slots available. Please try again later. Thank you for your understanding and patience.");return}for(var i in sooCheckout.options.deliveryTimes){html_days+='<option value="'+i+'">'+i+"</option>"}times=sooCheckout.options.deliveryTimes[Object.keys(sooCheckout.options.deliveryTimes)[0]]}if(times){html_hours+='<option value="Select a time">Select a time</option>';for(let i in times){html_hours+='<option value="'+times[i]+'">'+times[i]+"</option>"}}else{html_hours=""}hoursInput.html(html_hours);dayInput.html(html_days)},updateSelectedTime:function(){const day=$("#moo_pickup_day").val();let time=$("#moo_pickup_hour").val();if(day!==""){if(time==="ASAP"){}if(time!==""&&time!=="Select a time"){const today=new Date;let str="";if(day==="Today"){str=today.toDateString()}else{str=day+" "+today.getFullYear()}if(time==="ASAP"){time=today.toTimeString()}str+=" "+time.substring(0,time.length-2)+":00 "+time.substring(time.length-2,time.length);let selectedDay=new Date(str);mooGlobalParams.selectedTime=selectedDay;if(mooGlobalParams.selectedOrderType&&mooGlobalParams.selectedOrderType.ot_uuid==="onDemandDelivery"){this.createOnDemandDeliveryEstimate()}return}}mooGlobalParams.selectedTime=null},getDiscountedAmount:function(){let discounts=0;if(this.canAcceptCoupons()&&mooGlobalParams.couponAmount){discounts+=mooGlobalParams.couponAmount}if(this.canAcceptPoints()&&mooGlobalParams.pointsAmount){discounts+=mooGlobalParams.pointsAmount}return discounts},createDeliveryEstimate:function(){let deliveryTime=(new Date).toISOString();if(mooGlobalParams.selectedTime){deliveryTime=mooGlobalParams.selectedTime}const url=sooCheckout.options.restApiUrl+"moo-clover/v3/delivery-estimate";return fetch(url,{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json"},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify({dropoff_address:{street:mooGlobalParams.selectedAddress.address,unit:mooGlobalParams.selectedAddress.line2,city:mooGlobalParams.selectedAddress.city,state:mooGlobalParams.selectedAddress.state,zip_code:mooGlobalParams.selectedAddress.zipcode},order_value:sooCheckout.options.totals.sub_total,delivery_time:deliveryTime})})},displayDeliveryAmountForAddress:function(res){if(!mooGlobalParams.selectedAddress){return}$("#moo-checkout-form-ordertypes div.soo-address-section > div.soo-list-of-addresses > div.soo-addresses-wrapper>.soo-estimate-loader").hide();const addrElm=$("#moo-checkout-form-ordertypes .soo-address-section .soo-list-of-addresses #soo-address-"+mooGlobalParams.selectedAddress.id);$(".soo-delivery-amount",addrElm).text("");if(res.status==="success"){$(addrElm).addClass("soo-selected");let deliveryAmount;mooGlobalParams.selectedAddress.isValid=true;if(res.minAmount&&res.minAmount>0&&res.minAmount>sooCheckout.options.totals.sub_total){const message=mooObjectL10n.minimumForDeliveryZone+parseFloat(res.minAmount/100).toFixed(2);mooCheckout.unSelectAddress();addrElm.addClass("soo-selected-warning");$(".soo-address-error",addrElm).text(message);mooGlobalParams.deliveryFees=null}if(res.freeAfter&&res.freeAfter>0&&res.freeAfter<=sooCheckout.options.totals.sub_total){mooGlobalParams.deliveryFees=0;deliveryAmount="Free"}else{if(res.fee>0){mooGlobalParams.deliveryFees=res.fee;deliveryAmount=parseFloat(res.fee/100).toFixed(2);deliveryAmount="+ $"+deliveryAmount}else{mooGlobalParams.deliveryFees=0;deliveryAmount="Free"}}$(".soo-delivery-amount",addrElm).text(deliveryAmount)}else{mooGlobalParams.selectedAddress.isValid=false;mooCheckout.unSelectAddress()}if(res.status==="failed"){if(res.code==="zone_not_supported"){addrElm.addClass("soo-selected-error");$(".soo-address-error",addrElm).text(res.message);mooGlobalParams.deliveryFees=null}if(["min_amount_not_valid","delivery_time_not_valid"].includes(res.code)){addrElm.addClass("soo-selected-warning");$(".soo-address-error",addrElm).text(res.message);mooGlobalParams.deliveryFees=null}}mooCheckout.updateTotals()},applyCoupon:function(showError=true){const btnRemove=$("#moo-checkout-form-coupon div > button.sooDeleteCouponButton.sooCheckoutPrimaryButtonInput");const btn=$("#moo-checkout-form-coupon div > button.sooApplyCouponButton.sooCheckoutPrimaryButtonInput");const btnTxt=btn.html();btn.html('<div class="dot-flashing"></div>');mooGlobalParams.couponCode=$("#moo_coupon").val();if(mooGlobalParams.couponCode){mooGlobalParams.couponCode=mooGlobalParams.couponCode.trim();this.getCouponByCode(mooGlobalParams.couponCode).then(res=>{if(res.ok){return res.json()}throw new Error(mooObjectL10n.anErrorOccurred)}).then(res=>{if(res.status==="success"&&res.coupon){let discountAmount=0;const minValue=Math.round(parseFloat(res.coupon.minAmount)*100);const maxValue=Math.round(parseFloat(res.coupon.maxValue)*100);if(sooCheckout.options.totals.sub_total<=0||typeof sooCheckout.options.totals.sub_total===undefined){throw new Error(mooObjectL10n.cartEmpty)}else{if(!isNaN(minValue)){if(sooCheckout.options.totals.sub_total<minValue){throw new Error("Minimum order amount to use this coupon is $"+this.formatPrice(minValue))}}}if(res.coupon.type.toUpperCase()==="AMOUNT"){discountAmount=Math.round(parseFloat(res.coupon.value)*100);mooGlobalParams.couponName=res.coupon.name}else{discountAmount=Math.round(parseFloat(res.coupon.value)*sooCheckout.options.totals.sub_total/100);mooGlobalParams.couponName=res.coupon.name}mooGlobalParams.couponAmount=Math.min(sooCheckout.options.totals.sub_total,discountAmount);if(!isNaN(maxValue)){if(mooGlobalParams.couponAmount>maxValue){mooGlobalParams.couponAmount=maxValue}}this.updateTotals();if(this.canAcceptPoints()&&mooGlobalParams.points>0){if(this.getOrderTotal()<0){this.clickOnRemovePoints();const additionalMsg=` and your previously used loyalty ${mooGlobalParams.pointsLabel} have been reset. Please take a moment to use review them again`;const txt=mooObjectL10n.receivedDiscountUSD+this.formatPrice(mooGlobalParams.couponAmount)+additionalMsg;this.showSuccessAlert(mooObjectL10n.couponApplied,txt)}}else{const txt=mooObjectL10n.receivedDiscountUSD+this.formatPrice(mooGlobalParams.couponAmount);this.showSuccessAlert(mooObjectL10n.couponApplied,txt)}btn.html(btnTxt).hide();$("#moo_coupon").attr("readonly",true).attr("disabled",true);btnRemove.show()}else{if(showError){throw new Error(res.message)}else{$("#moo_coupon").val("");btn.html(btnTxt)}}}).catch(err=>{this.showErrorAlert(mooObjectL10n.error,err.message);btn.html(btnTxt)})}else{this.showErrorAlert(mooObjectL10n.error,mooObjectL10n.enterCouponCode,"#moo_coupon");btn.html(btnTxt)}},removeCoupon:function(){const btnApply=$("#moo-checkout-form-coupon div > button.sooApplyCouponButton.sooCheckoutPrimaryButtonInput");const btn=$("#moo-checkout-form-coupon div > button.sooDeleteCouponButton.sooCheckoutPrimaryButtonInput");const btnTxt=btn.html();btn.html('<div class="dot-flashing"></div>');mooGlobalParams.couponCode=null;mooGlobalParams.couponAmount=null;mooGlobalParams.couponName=null;this.updateTotals();btn.html(btnTxt);btn.hide();btnApply.show();$("#moo_coupon").val("").attr("readonly",false).attr("disabled",false)},clickOnUsePoints:function(){$("#moo-checkout-form-loyalty .loyaltyButtons > .sooUsePointsButton").hide();$("#moo-checkout-form-loyalty .loyaltyButtons > .sooRemovePointsButton").show();$("#moo-checkout-form-loyalty .usePointsInput").show();this.setLoyaltyError("");$("#moo-checkout-form-loyalty .usePointsInput .sooValidatePoints .sooValidatePointsButton").show();$("#moo-checkout-form-loyalty .usePointsInput .sooValidatePoints .sooEditPointsButton").hide();$("#sooSelectedPointsValue").attr("disabled",false).attr("readonly",false)},clickOnRemovePoints:function(){this.removePoints();$("#moo-checkout-form-loyalty .loyaltyButtons > .sooUsePointsButton").show();$("#moo-checkout-form-loyalty .loyaltyButtons > .sooRemovePointsButton").hide();$("#moo-checkout-form-loyalty .usePointsInput").hide();this.updateTotalsSection(sooCheckout.options.totals)},changePointsValue:function(){this.setLoyaltyError("");const points=$("#sooSelectedPointsValue").val();if(points.match(/^[0-9]+$/)&&points>0){const maxAllowed=this.getMaxPointsAllowed();const amount=this.getValueOfPoints(points);if(amount>0){const elm=$("#moo-checkout-form-loyalty > div.moo-checkout-bloc-content > div.moo-row.usePointsInput  .sooToPayInfo > .sooToPayAmount");elm.html("$"+this.formatPrice(amount))}if(maxAllowed<points){if(maxAllowed===0){this.setLoyaltyError(`${mooGlobalParams.pointsLabel} can't be used for this order.`)}else{this.setLoyaltyError("The maximum number of "+mooGlobalParams.pointsLabel+" that can be used is "+maxAllowed)}}}else{this.setLoyaltyError("Not a valid number")}},usePoints:function(){this.setLoyaltyError("");const points=$("#sooSelectedPointsValue").val();if(points.match(/^[0-9]+$/)&&points>0){const customer=this.getLoggedInCustomer();const settings=this.getLoyaltySettings();const maxAllowed=this.getMaxPointsAllowed();if(!customer||!settings){this.setLoyaltyError("Your session has been expired, please refresh the page");return}if(customer.point_count<points){this.setLoyaltyError("Insufficient balance");return}if(settings.min_points_to_order&&settings.min_points_to_order>points){this.setLoyaltyError("The store owner has set a minimum requirement of "+settings.min_points_to_order+" "+mooGlobalParams.pointsLabel+" per order.");return}if(settings.min_amount_to_up&&settings.min_amount_to_up>sooCheckout.options.totals.sub_total){this.setLoyaltyError("Minimum order amount to use points is $"+this.formatPrice(settings.min_amount_to_up));return}if(maxAllowed<points){if(maxAllowed===0){this.setLoyaltyError(`${mooGlobalParams.pointsLabel} can't be used for this order.`)}else{this.setLoyaltyError("The maximum number of "+mooGlobalParams.pointsLabel+" that can be used is "+maxAllowed)}return}mooGlobalParams.points=points;mooGlobalParams.pointsAmount=Math.min(this.getValueOfPoints(points),this.getSubTotalWithoutCoupons());this.updateTotals();$("#moo-checkout-form-loyalty .usePointsInput .sooValidatePoints .sooValidatePointsButton").hide();$("#moo-checkout-form-loyalty .usePointsInput .sooValidatePoints .sooEditPointsButton").show();$("#sooSelectedPointsValue").attr("disabled",true).attr("readonly",true)}else{this.setLoyaltyError("Not a valid number")}},editPoints:function(){mooGlobalParams.points=null;mooGlobalParams.pointsAmount=null;this.setLoyaltyError("");$("#moo-checkout-form-loyalty .usePointsInput .sooValidatePoints .sooValidatePointsButton").show();$("#moo-checkout-form-loyalty .usePointsInput .sooValidatePoints .sooEditPointsButton").hide();$("#sooSelectedPointsValue").attr("disabled",false).attr("readonly",false);this.updateTotalsSection(sooCheckout.options.totals)},setLoyaltyError:function(err){$("#moo-checkout-form-loyalty > div.moo-checkout-bloc-content > div.moo-row.usePointsInput .moo-error-section").html(err).show()},openLoyaltyDetails:function(){const settings=this.getLoyaltySettings();const maxPointsAllowed=this.getMaxPointsAllowed();const earningMsg=this.getEarningMessage();if(!settings){this.showErrorAlert(mooObjectL10n.error,mooObjectL10n.anErrorOccurred);return}let htmlDiv='<div class="soo-loyalty-conditions"><div class="moo-row"><div class="moo-col-md-12"><ul>';htmlDiv+=`<li>- Get $${this.formatPrice(settings.per_x_usd)} discount when redeeming ${settings.nb_points} ${mooGlobalParams.pointsLabel}</li>`;if(settings.purchase_usd_value){if(settings.calc_method==="subtotal"){htmlDiv+=`<li>- Earn ${settings.purchase_usd_value} ${mooGlobalParams.pointsLabel} for every dollar spent (based on Subtotal).</li>`}else{htmlDiv+=`<li>- Earn ${settings.purchase_usd_value} ${mooGlobalParams.pointsLabel} for every dollar spent.</li>`}}else{htmlDiv+=`<li>- Earn ${settings.purchase_fixed_points} ${mooGlobalParams.pointsLabel} on each order placed.</li>`}if(settings.order_source.website===false){htmlDiv+=`<li>- ${mooGlobalParams.pointsLabel} not earned for purchases made through our website, try our Mobile App.</li>`}if(settings.max_points_per_order){htmlDiv+=`<li>- Maximum of ${settings.max_points_per_order} ${mooGlobalParams.pointsLabel} can be earned per order.</li>`}if(settings.min_points_to_order){htmlDiv+=`<li>- Minimum requirement of ${settings.min_points_to_order} ${mooGlobalParams.pointsLabel} should be used per order.</li>`}if(settings.min_amount_to_up){htmlDiv+=`<li>- Minimum order amount required to use ${mooGlobalParams.pointsLabel} is $${this.formatPrice(settings.min_amount_to_up)}</li>`}const subTotalWithoutCoupons=this.getSubTotalWithoutCoupons();const maxPercent=settings.percent_to_cover?settings.percent_to_cover:100;htmlDiv+=`<li>- ${mooGlobalParams.pointsLabel} can cover up to ${maxPercent}% of $${this.formatPrice(subTotalWithoutCoupons)} (Subtotal - Coupon)</li>`;if(maxPointsAllowed>0){htmlDiv+=`<li>- Maximum of ${maxPointsAllowed} ${mooGlobalParams.pointsLabel} can be used for this order.</li>`}else{htmlDiv+=`<li>- ${mooGlobalParams.pointsLabel} can't be used for this order.</li>`}htmlDiv+=`<li>- <b>${earningMsg}</b></li>`;htmlDiv+="</ul></div></div></div>";Swal.fire({imageUrl:null,title:"Loyalty Conditions",html:htmlDiv,showCancelButton:false,allowOutsideClick:true}).then(function(){setTimeout(p=>$(".sooLoyaltyDetailsButton").focus(),500)})},removePoints:function(){mooGlobalParams.points=null;mooGlobalParams.pointsAmount=null;this.setLoyaltyError("");$("#sooSelectedPointsValue").val(0);$("#moo-checkout-form-loyalty > div.moo-checkout-bloc-content > div.moo-row.usePointsInput .sooToPayInfo > .sooToPayAmount").html("$0.00");this.updateTotalsSection(sooCheckout.options.totals)},getCouponByCode:function(code){const url=sooCheckout.options.restApiUrl+"moo-clover/v2/checkout/check_coupon";return fetch(url,{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json"},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify({code:code})})},canAcceptCoupons:function(){if(mooGlobalParams.selectedOrderType){return this.isTrue(mooGlobalParams.selectedOrderType.use_coupons)}return true},canAcceptPoints:function(){if(mooGlobalParams.isGuest){return false}return sooCheckout.options.loyaltySetting!==null},isOrderTaxable:function(){if(mooGlobalParams.selectedOrderType&&!mooCheckout.isTrue(mooGlobalParams.selectedOrderType.taxable)){return false}return true},showCheckoutDetails:function(){this.changeElemVisibility("#sooAuthSection","hide");this.showOrHideASection("checkout-form",true);this.fillCustomerInfo();if(this.canAcceptPoints()){this.changeElemVisibility("#moo-checkout-form-loyalty","show");this.fillCustomerPointsBalance()}else{this.changeElemVisibility("#moo-checkout-form-loyalty","hide")}if(this.countAvailableOrderingMethods()===1){$('#moo-checkout-form-ordertypes input[name="ordertype"]:not(:disabled)').prop("checked",true);this.orderTypeChanged()}if(this.countAvailablePaymentMethods()===1){$('#moo-checkout-form-payments input[name="paymentMethod"]:not(:disabled)').prop("checked",true);this.paymentMethodChanged()}this.tipPercentageChanged();if(localStorage.getItem("soo-coupon")){$("#moo_coupon").val(localStorage.getItem("soo-coupon"));mooCheckout.applyCoupon(false)}},getValueOfPoints:function(points){const settings=this.getLoyaltySettings();if(settings){return Math.round(points*settings.per_x_usd/settings.nb_points)}return 0},getLoyaltySettings:function(){return sooCheckout.options.loyaltySetting},getMaxPointsAllowed:function(){let customer=this.getLoggedInCustomer();if(customer){let percentAmount=100;const subTotalWithoutCoupons=this.getSubTotalWithoutCoupons();const settings=this.getLoyaltySettings();if(settings){if(!isNaN(parseInt(settings.percent_to_cover))){percentAmount=parseInt(settings.percent_to_cover)}}else{return 0}const amountToCover=subTotalWithoutCoupons*percentAmount/100;const requiredPoints=Math.ceil(amountToCover*settings.nb_points/settings.per_x_usd);return Math.min(requiredPoints,customer.point_count)}return 0},getEarningMessage:function(){let willBeEarned=0;const orderAmount=this.getOrderTotal();const settings=this.getLoyaltySettings();if(settings){if(settings.order_source.website!==false){if(settings.purchase_usd_value){if(settings.calc_method==="subtotal"){willBeEarned=Math.round(settings.purchase_usd_value*sooCheckout.options.totals.sub_total/100)}else{willBeEarned=Math.round(settings.purchase_usd_value*orderAmount/100)}}else{willBeEarned=settings.purchase_fixed_points}if(!settings.earn_on_all_order){if(mooGlobalParams.points>0){willBeEarned=0}}}if(willBeEarned>0){return`By placing this order you will earn ${willBeEarned} ${mooGlobalParams.pointsLabel}.`}else{return`No ${mooGlobalParams.pointsLabel} will be earned for this order.`}}else{return`<li>${mooGlobalParams.pointsLabel} can't be earned for this order.</li>`}},getSubTotalWithoutCoupons:function(){if(this.canAcceptCoupons()&&mooGlobalParams.couponAmount){return sooCheckout.options.totals.sub_total-mooGlobalParams.couponAmount}else{return sooCheckout.options.totals.sub_total}},getOrderTotal:function(){const cartTotals=sooCheckout.options.totals;const totals=mooCheckout.getTotals();let taxAmount=0;if(totals.orderTaxable){if(totals.discounts===0){taxAmount=cartTotals.taxes}else{taxAmount=cartTotals.taxes_after_discount}}return cartTotals.sub_total+taxAmount+totals.deliveryAmount+totals.serviceFee-totals.discounts}};window.moo_clover_gateway={mountElements:function(){if(sooCheckout.options.creditCard){if($("#moo_CloverCardNumber").length){window.clover_card.mount("#moo_CloverCardNumber");window.clover_exp.mount("#moo_CloverCardDate");window.clover_cvc.mount("#moo_CloverCardCvv");window.clover_zip.mount("#moo_CloverCardZip");if(window.clover_streetAddress){window.clover_streetAddress.mount("#moo_CloverStreetAddress")}}}if(sooCheckout.options.giftCards){if($("#moo_CloverGiftCard").length){window.clover_giftCard.mount("#moo_CloverGiftCard")}}if(sooCheckout.options.googlePay){if($("#moo-cloverGooglePay").length){window.clover_googlepay.mount("#moo-cloverGooglePay")}}},createElements:function(){const elementStyles={input:{color:"#31325F",height:"30px","::placeholder":{color:"#CFD7E0"}}};if(sooCheckout.options.creditCard){window.clover_card=window.elements.create("CARD_NUMBER",elementStyles);window.clover_exp=window.elements.create("CARD_DATE",elementStyles);window.clover_cvc=window.elements.create("CARD_CVV",elementStyles);window.clover_zip=window.elements.create("CARD_POSTAL_CODE",elementStyles);window.clover_card.addEventListener("change",function(event){moo_clover_gateway.onCCFormChange();$(document.body).trigger("cloverError",event)});window.clover_exp.addEventListener("change",function(event){moo_clover_gateway.onCCFormChange();$(document.body).trigger("cloverError",event)});window.clover_cvc.addEventListener("change",function(event){moo_clover_gateway.onCCFormChange();$(document.body).trigger("cloverError",event)});window.clover_zip.addEventListener("change",function(event){moo_clover_gateway.onCCFormChange();$(document.body).trigger("cloverError",event)});if(sooCheckout.options.showStreetAddressField){window.clover_streetAddress=window.elements.create("CARD_STREET_ADDRESS",elementStyles);window.clover_streetAddress.addEventListener("change",function(event){moo_clover_gateway.onCCFormChange();$(document.body).trigger("cloverError",event)})}}if(sooCheckout.options.giftCards){const giftCardStyles={input:{"border-radius":"5px",height:"45px",padding:"10px",color:"#31325F",border:"1px solid #ccc","::placeholder":{color:"#CFD7E0"}},body:{margin:"0;",border:"0.7px solid #B8B8B8FF;","border-radius":"10px;",padding:"10px;",width:"96%;","overflow-x":" hidden;"},".fieldError input":{"border-color":"red",color:"red"},".errorMessage":{color:"red","min-height":"10px;"},".sectionHeader":{display:"none"}};window.clover_giftCard=window.elements.create("GIFT_CARD_ELEMENTS",giftCardStyles);window.clover_giftCard.addEventListener("change",function(event){moo_clover_gateway.onGiftCardChange(event);$(document.body).trigger("cloverGiftCardError",event)})}if(sooCheckout.options.googlePay){const paymentReqData={total:{label:"Online Order",amount:sooCheckout.options.totals.sub_total},options:{button:{buttonType:"long"}}};window.clover_googlepay=window.elements.create("PAYMENT_REQUEST_BUTTON",{paymentReqData:paymentReqData});window.clover_googlepay.addEventListener("paymentMethod",function(tokenData){window.googlePayToken=tokenData;try{$("#moo-cloverGooglePay").hide();$("#moo_checkout_loading").show();$("#moo-checkout .errors-section").html("");window.mooCheckout.getCheckoutForm()}catch(e){console.log(e);window.mooCheckout.showErrorAlert(mooObjectL10n.anErrorOccurred)}})}window.moo_clover_gateway.mountElements()},init:function(){$(document).on("cloverError",this.onError).on("cloverGiftCardError",this.onGiftCardError).on("checkout_error",this.reset);moo_clover_gateway.createElements()},isMobile:function(){if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){return true}return false},getSelectedPaymentElement:function(){return $('.payment_methods input[name="payment_method"]:checked')},createSource:function(){return clover.createToken().then(moo_clover_gateway.sourceResponse)},sourceResponse:function(response){if(response.error){return $(document.body).trigger("cloverError",response)}moo_clover_gateway.reset();$("#moo-CloverToken").val(response.token)},onCCFormChange:function(){},onGiftCardChange:function(e){console.log("onGiftCardChange");console.log(e)},reset:function(){if(!$("#moo-checkout-form-payments #moo-cloverCreditCardPanel .clover-error").length){}},onError:function(e,result){var hasError=false;var errorMessage="";if(result.CARD_NUMBER.error){errorMessage=result.CARD_NUMBER.error;hasError=true}else{if(result.CARD_DATE.error){errorMessage=result.CARD_DATE.error;hasError=true}else{if(result.CARD_CVV.error){errorMessage=result.CARD_CVV.error;hasError=true}else{if(result.CARD_STREET_ADDRESS&&result.CARD_STREET_ADDRESS.error){errorMessage=result.CARD_STREET_ADDRESS.error;hasError=true}else{if(result.CARD_POSTAL_CODE.error){errorMessage=result.CARD_POSTAL_CODE.error;hasError=true}}}}}window.cloverCardIsValid=!hasError;window.cloverCardErrorMsg=errorMessage;try{if(errorMessage===""){errorMessage=!result.CARD_NUMBER.touched?mooObjectL10n.CardNumberRequired:!result.CARD_DATE.touched?mooObjectL10n.CardDateRequired:!result.CARD_CVV.touched?"Card Cvv is required":result.CARD_STREET_ADDRESS&&!result.CARD_STREET_ADDRESS.touched?mooObjectL10n.CardStreetAddressRequired:!result.CARD_POSTAL_CODE.touched?mooObjectL10n.CardZipRequired:window.cloverCardErrorMsg}if(errorMessage!==window.cloverCardErrorMsg){window.cloverCardIsValid=false;window.cloverCardErrorMsg=errorMessage}}catch(e){console.log(e)}},onGiftCardError:function(e,result){console.log(result);window.cloverGiftCardIsValid=result?.GIFT_CARD_ELEMENTS?.isFormValid;console.log(window.cloverGiftCardIsValid)},submitError:function(error_message){}};$(document).ready(function(){window.mooCheckout.init();if(sooCheckout.options.pakmsKey){try{window.clover=new Clover(sooCheckout.options.pakmsKey,{locale:sooCheckout.options.locale});window.elements=window.clover.elements();window.cloverCardIsValid=false;window.cloverGiftCardIsValid=false;window.cloverCardErrorMsg=mooObjectL10n.CardNumberRequired;window.moo_clover_gateway.init()}catch(error){console.log(error)}}})});