function($ = recurpayScript) { if ((window.location.href.indexOf("/products/") > -1) && (window.location.href.indexOf("recurpay_preview=true") > -1)) { recurpay.pdpAPI = recurpay.generalURL + '/storefront/api/2024-07/widgets/products/plans?shop=' + recurpay.shopDomainURL + '&fetch=force'; } var accountTemplate = '', accountSelector = "#recurpay-account-widget", pdpSelector = ".recurpay-pdp-widget", subscriptionSelector = "#recurpay-manage-subscriptions", checkoutSelector = '[href="/checkout"], form[action="/cart"] button[type="submit"][name="checkout"], form[action="/cart"] input[type="submit"][name="checkout"], form[action="/checkout"] input[type="submit"][name="checkout"], form[action="/checkout"] button[type="submit"][name="checkout"], button[type="submit"][name="checkout"],button[name="checkout"], button[name="checkout"].cart__checkout, button.ucd-checkout-btn, #checkout2.flo-checkout-btn', atcFormSelector = 'form[action*="/cart/add"], form[action*="/cart/add.js"], form[id^="product_form_"], form[data-productid], form[action*="/cart/add"][data-js-product-form], form#AddToCartForm, #addToCartFormId1, form.product-form, #AddToCartForm_id, form[data-cart-submit="data-cart-submit"][data-productid], form.lh-product-form, form.shg-product-atc-btn-wrapper, form.shopify-product-form, product-form.product-form, form#product-form-template--*', atcSelector = '.buy-buttons [type="submit"], [name="add"], [type="submit"], button#AddToCart, button.gf_add-to-cart, add-to-cart-button, button.gp-button-atc, #button-cart, .new-form-atc[data-add-to-cart], button[data-type="addToCart"], .product-buy-buttons--primary[data-text="Add to cart"], product-variant-render button[type="submit"], .x-buy-now-button, .add-to-cart-component, add-to-cart-component button, button.product-form__submit, .product-form__submit, .button--add-to-cart, button[id*="add-to-cart"]'; buynowSelector=[".shopify-payment-button__button","shopify-buy-it-now-button button",".accelerated-checkout-block",".shopify-payment-button","shopify-accelerated-checkout",'[data-shopify="payment-button"]'].join(","); priceQuantitySelector = '[name=quantity]', footerManageSubcriptionSelector = ".recurpay-manage-subscription-link-footer", footerLinkSelector = 'footer, .footer', appBlockSelector = '[id*="recurpay_app_block_widget"], .shopify-app-block[data-block-handle="recurpay-app-block-widget"]', appBlockParentSelector = ".product-info, .shop-product-info, .product-single__meta [data-product-blocks], .shopify-block, .product__info-container, .group-block-content, .group-block"; productContainerSelector = '.group-block, .product__info-container, .product-info, .shop-product-info, [data-product-id], product-form-component'; recurpay.pdpAPI = recurpay.generalURL + '/storefront/api/2024-07/widgets/products/plans?shop=' + recurpay.shopDomainURL; recurpay.manualPaymentSubscription = false; // ACCOUNT PAGE if(recurpay.pageTemplate == "customers/account" && $(accountSelector).length <= 0) { if($('.card__linklist').length >0) { $('.card__linklist').before('
'); } else if($('.flits-account-page-title').length >0) { $('.flits-account-page-title').append('
'); } else if($('a[href*="/account/addresses"]').length >0) { $('a[href*="/account/addresses"]').before('
'); } else if ($('.order-history').length >0) { $('.order-history').before('
'); } else if ($('a[href*="/account/logout"]').length >0) { $('a[href*="/account/logout"]').before('
'); } else { recurpay.logEvent("account_widget","Failed to show account snippet", "critical"); } } //LOGIN PAGE function loginPageSubscriptionLink() { var accountLoginHTML = "", footerLinkHTML = "", managesubscriptionSelector = ".recurpay-manage-subscription-link", signUpFormSelector = 'form[action*="/account"]'; if ($(managesubscriptionSelector).length <= 0 && $(signUpFormSelector).length > 0) { $(signUpFormSelector).append(""); } if ($(footerManageSubcriptionSelector).length <= 0 && $(footerLinkSelector).length > 0) { $(footerLinkSelector).find('.footer__content-bottom .footer__content-bottom-wrapper .footer__copyright').append(''); } var account_url = ""; account_url = recurpay.customer ? recurpay.accountAPI + "&settings=true" : recurpay.generalURL + "/api/storefront/v3/customers/subscriptions/count?" + recurpay.urlParam + "&settings=true"; $.ajax( { url: account_url, type: 'POST', data: { customer_id: recurpay.customer || '', customer_hash: recurpay.secret_potion || '' }, async: true, success: function (response) { if (response != "ERROR") { if (response.settings !== null && !$.isEmptyObject(response.settings) && response.translations.breadcrumb_manage_subscription_link != undefined) { if ($(managesubscriptionSelector).length >= 0) { accountLoginHTML += "" + response.translations.breadcrumb_manage_subscription_link + ""; } if ($(footerManageSubcriptionSelector).length >= 0) { footerLinkHTML += "" + response.translations.breadcrumb_manage_subscription_link + ""; } } } $(managesubscriptionSelector).html(accountLoginHTML); $(footerManageSubcriptionSelector).html(footerLinkHTML); } }); } loginPageSubscriptionLink(); if($(accountSelector).length && recurpay.customer !== "guest") { function recurAccount(count) { accountTemplate += '
' accountTemplate += '
' accountTemplate += '' if(count !== 0) { accountTemplate += '' accountTemplate += '' } else { accountTemplate += '' accountTemplate += '' } accountTemplate += '
' return accountTemplate; } $.ajax( { url: recurpay.accountAPI+"&settings=true", type: 'POST', data: { customer_id: recurpay.customer || '', customer_hash: recurpay.secret_potion || '' }, async:true, success: function(response) { var accountHTML = ''; if(response != "ERROR") { if(response.settings !== null && !$.isEmptyObject(response.settings)) { recurpay.accountSettings = response.settings; document.documentElement.style.setProperty('--recurpay_primary_color', recurpay.accountSettings.snippet_color_codes.account_brand_color); document.documentElement.style.setProperty('--recurpay_button_text_color', recurpay.accountSettings.snippet_color_codes.account_button_text_color); document.documentElement.style.setProperty('--recurpay_button_bg_color', recurpay.accountSettings.snippet_color_codes.account_button_color); } accountHTML = recurAccount(response.count); } else { accountHTML = recurAccount(0); } if($(accountSelector).length) { $(accountSelector).html(accountHTML); } }, error: function(jqXhr, textStatus, errorThrown) { console.log( errorThrown ); } }); $(document).on('click', subscriptionSelector, function(e) { e.preventDefault(); $.ajax( { url: recurpay.manageAccountAPI, type: 'POST', data: { customer_id: recurpay.customer, customer_hash: recurpay.secret_potion || '' }, success: function(response) { var redirect_url = response.account.url; if(redirect_url !== "" && redirect_url !== null && redirect_url !== undefined) { setTimeout(() => { window.location.href = redirect_url; }, 100); } else { console.log('redirect url error'); } }, error: function(response) { console.log('redirect url error'); } }) }); } recurpay.isLocalizedCurrency = false; function formatPriceMoney(r){var e=100*(parseFloat(r)||0);return recurpay.recurMoney.formatPrice(e,!recurpay.isLocalizedCurrency)} $(atcFormSelector).closest(".product__meta").find("button.product__chip").on("click",function(){var r=$(this);setTimeout(function(){recurpay.product.selectedVariant=r.parents(atcFormSelector).find('select[name="id"]').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(atcFormSelector).find(".combobox, .wetheme-dropdown__wrapper ul[id^='SingleOptionSelector-'] li, .option-values-radio .popover-list-item .form-element-radio, .single-option-selector .bcpo-image-parent, .regular-select-item, .bcpo-dd.single-option-selector ul.inner li, #clickyboxes-SingleOptionSelector-0 a, button.product__chip, .form-swatch-item, .product-variant__container .product-variant__label, .options-selection__option-value, .popout-list__option--product, .option-swatch .custom-swatch, ul.select-dropdown li, .swatch-element, .swatch_pr_item, .basel-swatch, .swatchBox label, .swatchBox span").on("click",function(){var e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(atcFormSelector).find('select[name="id"], input[name="id"][type="radio"]:checked').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(atcFormSelector).closest(".product-selection").find("select.single-option-selector").on("change",function(){var e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(atcFormSelector).find('select[name="id"]').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(atcFormSelector).find(".product-single__swatch__input").on("change",function(){var e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(atcFormSelector).find('select[name="id"]').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(atcFormSelector).find('input#SelectedId, select.js-variant-select, input[name="id"], select[name="id"], select.single-option-selector, .zpa-single-option-selector, .select.options-selection__input-select, .form-options input.option-value-input, .variant-input input[type="radio"], .product-form__option-select, .option-selectors .selector-wrapper select, select.single-option-list-type, .product-options .option-input, select.input-reset, select.js-product-variant, select[data-single-option-selector], input[data-single-option-selector], select.single-option-selector-product-template, .single-option-selector[type="radio"], .single-option-selector-product-template[type="radio"], .variant-option').on("change",function(){var e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(atcFormSelector).find('input[name="id"], select[name="id"], input#SelectedId').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(document).find(".quantity-breaks input[name='quantity']").on("change",function(){let e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(".product__info-container").find(atcFormSelector).find('input.product-variant-id,input[name="id"],select[name="id"],input#SelectedId').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(document).find("form.variant-picker__form .variant-option input[type='radio']").on("change",function(){let r=$(this);setTimeout(function(){recurpay.product.selectedVariant=r.attr("data-variant-id"),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(document).on("change click",'variant-selects input[type="radio"], variant-selects select, .product-form__input input[type="radio"], .product-form__input select, fieldset.product-form__input input[type="radio"]',function(){var t=$(this).closest(".product__info-container, [data-section], .shopify-app-block, .product-grid__item, form"),e=t.find(atcFormSelector).first().length?t.find(atcFormSelector).first():$(this).closest(atcFormSelector).length?$(this).closest(atcFormSelector):$(atcFormSelector).filter(function(){return $(this).find(".recurpay-pdp-widget").length||$(this).closest(".product__info-container").find(".recurpay-pdp-widget").length}).first(),i=e.find('input[name="id"], input.product-variant-id, select[name="id"], input#SelectedId').val()||$(this).attr("data-variant-id")||null;i&&setTimeout(function(){(i=e.find('input[name="id"], input.product-variant-id, select[name="id"], input#SelectedId').val()||i)&&(recurpay.product.selectedVariant=i,recurDiscountedPrice(i),recurpay.handlePlanOnVariant(i))},50)}); $(document).on("change",'input[name="id"], input.product-variant-id',function(){var t=this.value;if(t){var e=$(this).closest(atcFormSelector);(e.find(".recurpay-pdp-widget").length||e.closest(".product__info-container, [data-section]").find(".recurpay-pdp-widget").length)&&setTimeout(function(){recurpay.product.selectedVariant=t,recurDiscountedPrice(t),recurpay.handlePlanOnVariant(t)},30)}}); var getLastUrl=location.href;new MutationObserver(()=>{var e=location.href;e!==getLastUrl&&(getLastUrl=e,onUrlChange())}).observe(document,{subtree:!0,childList:!0}); function onUrlChange(){var a=new URLSearchParams(window.location.search);a.has("variant")&&(recurpay.product.selectedVariant=a.get("variant"),recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))} function fetchVariants(){if(recurpay.getProductHandle()===false)return;$.ajax({url:"/products/"+recurpay.getProductHandle()+".json",type:"GET",success:function(r){if(recurpay.productDatas&&recurpay.productDatas[0]&&recurpay.productDatas[0].product)recurpay.productDatas[0].product.variants=r.product.variants;recurpay.isLocalizedCurrency=true;recurDiscountedPrice(recurpay.product.selectedVariant);recurpay.handlePlanOnVariant(recurpay.product.selectedVariant)},error:function(r,a,c){console.log(c)}})} recurpay.handlePlanOnVariant=function(e){let r=[];var a=recurpay.calculatePrice(e),t=parseInt(a.product_id);let n=e;(recurpay.globalPlanObjectMap[String(t)]||[]).forEach(e=>{(Array.isArray(e.products)?e.products:[e.products]).forEach(a=>{a&&a.excluded_variants&&a.excluded_variants.length>0&&a.excluded_variants.forEach(a=>{a.id==n&&r.push(e.id)})})});let c=$('.recurpay-pdp-widget[data-product-id="'+t+'"]'),l=r.length>0,i=0,o=c.find(".recurpay__frequency_select").find("option:selected").attr("data-plan")||null,d=c.find(".recurpay__frequency_select").attr("data-original-options");d&&c.find(".recurpay__frequency_select").html(decodeURIComponent(d));c.find(".recurpay__frequency_select option").each(function(){let e=$(this);var a=e.attr("data-plan");l&&r.includes(parseInt(a))?e.remove():i++});if(0===i){c.hide();var p=c.closest(appBlockSelector).length?c.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).first():c.parents(atcFormSelector).first();p.length||(p=c.closest(productContainerSelector).find(atcFormSelector).first());p.length||(p=$(atcFormSelector).filter(function(){return $(this).find(atcSelector+", "+buynowSelector).length}).first());p.find(atcSelector).filter(function(){return 0===$(this).closest(".recurpay-pdp-widget, .recurpay__widget").length}).removeClass("recurpay-hide");p.find(buynowSelector).filter(function(){return 0===$(this).closest(".recurpay-pdp-widget, .recurpay__widget").length}).removeClass("recurpay-hide");$(document).find(atcSelector+".recurpay-hide, "+buynowSelector+".recurpay-hide").filter(function(){return(($(this).closest('[data-product-id="'+t+'"], '+productContainerSelector).length||$(this).closest(atcFormSelector).find('[name="id"]').val()==n)&&0===$(this).closest(".recurpay-pdp-widget, .recurpay__widget").length)}).removeClass("recurpay-hide");c.find(".recurpay_plan_name, .recurpay_plan_id, .recurpay_purchase_data, .recurpay_selling_plan_id, .recurpay_manual_plan_id, .recurpay_manual_payment").attr("name","").val("");p.find(".recurpay_plan_name, .recurpay_plan_id, .recurpay_purchase_data, .recurpay_selling_plan_id, .recurpay_manual_plan_id, .recurpay_manual_payment").attr("name","").val("");c.find('[name="recurpay__group_main"][value="one-time"]').prop("checked",!0).trigger("change")}else{c.show();if("subscription"===$(document).find("[name='recurpay__group_main']:checked").val()){var $form=c.parents(atcFormSelector);c.find('.recurpay__widget_container[data-type="subscription-purchase"]').find('button[name="recurpay-subscribe"], button[data-recurpay-action]').length>0?($form.find(atcSelector).filter(function(){return 0===$(this).closest(".recurpay-pdp-widget, .recurpay__widget").length}).addClass("recurpay-hide"),$form.find(buynowSelector).filter(function(){return 0===$(this).closest(".recurpay-pdp-widget, .recurpay__widget").length}).addClass("recurpay-hide")):($form.find(atcSelector).filter(function(){return 0===$(this).closest(".recurpay-pdp-widget, .recurpay__widget").length}).removeClass("recurpay-hide"),$form.find(buynowSelector).filter(function(){return 0===$(this).closest(".recurpay-pdp-widget, .recurpay__widget").length}).removeClass("recurpay-hide"));$(document).find(".recurpay_plan_name").attr("name","properties[Plan]");$(document).find(".recurpay_plan_id").attr("name","properties[_PlanId]");$(document).find(".recurpay_purchase_data").attr("name","properties[_PurchaseData]");$(document).find(".recurpay_selling_plan_id").attr("name","selling_plan")}let e=c.find(".recurpay__frequency_select"),r=o?e.find(`option[data-plan="${o}"]`):null;r&&r.length||(r=e.find('option[data-recommended-frequency="true"]'));r.length||(r=e.find("option").first());r&&r.length&&(r.prop("selected",!0),e[0].dispatchEvent(new Event("change",{bubbles:!0})))}}; function getOneTimeSavingValue(e,a,t,n=1){e=parseFloat(e)||0,t=parseFloat(t)||0;const r=e*(n=parseInt(n,10)||1);let i=0;return"percentage"===(a=(a||"percentage").toLowerCase())?t>0&&(i=r*(t/100)):"fixed"===a?t>0&&(i=Math.min(t,r)):"price"===a&&(i=0===t?r:t>0&&t"; } else { dropdownOptionHtml = "" + getPlanName + "" + " (" + formatPriceMoney(discountedTotalPrice) + ")"; } $this.html(dropdownOptionHtml); if ($this.is(':selected')) { var $pdpWidget = $('.recurpay-pdp-widget[data-product-id="' + getProductId + '"]'); var $subscriptionContainer = $pdpWidget.find(".recurpay__widget_container[data-type='subscription-purchase']"); var $oneTimeBanner = $pdpWidget.find(".recurpay__offer_onetime"); if (discountedTotalPrice < totalPlanPrice) { $subscriptionContainer .find(".recurpay__group_compare_price") .html("" + formatPriceMoney(totalPlanPrice) + ""); } else { $subscriptionContainer .find(".recurpay__group_compare_price") .html(""); } $subscriptionContainer .find(".recurpay__group_selling_price") .html("" + formatPriceMoney(discountedTotalPrice) + ""); const subscriptionDiscountLabel = getSubscriptionDiscountLabel( getDiscountType, getDiscount, getSavings ); $subscriptionContainer .find(".recurpay__saving_amount") .html(subscriptionDiscountLabel); const oneTimeSaving = getOneTimeSavingValue(basePrice, getDiscountType, getDiscount, getPlanShipment); if (oneTimeSaving > 0) { if (getDiscountType === "percentage") { const oneTimeDiscountLabel = getOneTimeDiscountLabel(getDiscountType, getDiscount, oneTimeSaving); $oneTimeBanner .find(".recurpay__offer_saving_message_amount_text") .html(oneTimeDiscountLabel); $oneTimeBanner.find(".recurpay__saving_amount").html(formatPriceMoney(oneTimeSaving)); $oneTimeBanner.find(".recurpay__offer_saving_message_text").show(); } else { const oneTimeDiscountLabel = getOneTimeDiscountLabel(getDiscountType, getDiscount, oneTimeSaving); $oneTimeBanner.find(".recurpay__offer_saving_message_amount_text").html(""); $oneTimeBanner.find(".recurpay__saving_amount").html(""); $oneTimeBanner.find(".recurpay__offer_saving_message_text") .html(oneTimeDiscountLabel) .show(); } $oneTimeBanner.show(); } else { $oneTimeBanner.hide(); $oneTimeBanner.find(".recurpay__offer_saving_message_amount_text").html(""); $oneTimeBanner.find(".recurpay__saving_amount").html(""); } let recommendedCheck = $this.attr("data-recommended-frequency"); if ( recommendedCheck == "true" && $pdpWidget.find(".recurpay__frequency_select option").length > 1 ) { $this.parents(".recurpay__group_frequency").addClass("recommended_frequency"); } else { $this.parents(".recurpay__group_frequency").removeClass("recommended_frequency"); } if ( (recurpay.settings.sell_only_as_subscription == true || recurpay.product.onlySubscription == "true") && $pdpWidget.parents(".product__info-container").length ) { const $container = $pdpWidget.parents(".product__info-container"); if ($container.find(".price__container .price__sale .price-item.price-item--sale").length) { $container .find(".price__container .price__sale .price-item.price-item--sale") .html("" + formatPriceMoney(discountedTotalPrice) + ""); } if ($container.find(".price__container .price__regular .price-item").length) { $container .find(".price__container .price__regular .price-item") .html("" + formatPriceMoney(discountedTotalPrice) + ""); } } } $('.recurpay-pdp-widget[data-product-id="' + getProductId + '"]') .find(".recurpay__widget_container[data-type='onetime-purchase']") .find(".recurpay__group_selling_price") .html("" + formatPriceMoney(getVariantPrice) + ""); }); } function offerSavings(e){const a=$(e),t=a.find('[name="recurpay__group_main"]:checked').val(),i=a.find(".recurpay__frequency_select option:selected"),n=parseFloat(i.attr("data-plan-discount")||0),r=(i.attr("data-plan-discount-type")||"percentage").toLowerCase(),c=a.parents(atcFormSelector).find('input[name="id"], select[name="id"], input#SelectedId').val()||recurpay.product.availableVariant;let p=0;if(c){const e=recurpay.calculatePrice(c);p=parseFloat(e.variant_price)||0}const s=parseInt(i.attr("data-plan-shipment")||1,10)||1,l=getOneTimeSavingValue(p,r,n,s),o=a.find(".recurpay__offer_onetime"),d=a.find(".recurpay__offer_subscription");o.hide(),d.hide(),"one-time"===t?l>0&&o.css("display","flex"):"subscription"===t&&("price"===r?(0===n||n0&&d.css("display","flex"))} function replaceTranslationPlaceholders(n,c){return n=n||"",Object.keys(c||{}).forEach(function(e){const l=null!=c[e]?c[e]:"";n=n.split(`[[${e}]]`).join(l)}),n} function getCurrencySymbolFromMoney(e){return e?e.replace(/[0-9.,\s]/g,""):""} function getDiscountDisplayValue(e,a){return"percentage"===e?parseFloat(a).toFixed(2).replace(/\.0+$/,"").replace(/\.00$/,""):formatPriceMoney(a)} function getOneTimeDiscountLabel(e,r,t){const i=recurpay?.settings?.translations||{},n=parseFloat(r)||0,o=parseFloat(t)||0,a=formatPriceMoney(n),_=formatPriceMoney(o),c=n.toFixed(2).replace(/\.0+$/,"").replace(/\.00$/,""),l=getCurrencySymbolFromMoney(formatPriceMoney(n));let m="";return m="percentage"===e?i.premium_one_time_percentage_discount_label||i.premium_one_time_discount_label||"[[DISCOUNT]]% ↓":"fixed"===e?i.premium_one_time_fixed_discount_label||"Save [[SAVING_AMOUNT]]":"price"===e?i.premium_one_time_price_discount_label||"Save [[SAVING_AMOUNT]]":i.premium_one_time_discount_label||"[[DISCOUNT]]% ↓",replaceTranslationPlaceholders(m,{DISCOUNT:"percentage"===e?c:a,DISCOUNT_PERCENTAGE:c,SAVING_AMOUNT:_,CURRENCY:l})} function getSubscriptionDiscountLabel(e,t,n){const r=recurpay?.settings?.translations||{},o=getDiscountDisplayValue(e,t),i=formatPriceMoney(n||0),s=getCurrencySymbolFromMoney(formatPriceMoney(t));let a=r.premium_subscription_discount_label||"[[SAVING_AMOUNT]]";return replaceTranslationPlaceholders(a,{DISCOUNT:o,DISCOUNT_PERCENTAGE:o,SAVING_AMOUNT:i,CURRENCY:s})} function normalizeProductPlans(product) { const topLevelPlans = Array.isArray(product?.plans) ? product.plans : []; const normalizedPlans = []; const seenKeys = new Set(); topLevelPlans.forEach(function(plan) { if (!plan) return; const groupProducts = Array.isArray(plan.products) ? plan.products : []; const groupShippingPolicy = plan.shipping_policy || {}; const groupId = plan.selling_plan_group_id || ""; const sellingPlans = Array.isArray(plan.selling_plans) && plan.selling_plans.length ? plan.selling_plans : [plan]; sellingPlans.forEach(function(sellingPlan, sellingPlanIndex) { if (!sellingPlan) return; const sellingPlanNumericId = sellingPlan.id != null ? String(sellingPlan.id) : ""; const sellingPlanGid = sellingPlan.selling_plan_id ? String(sellingPlan.selling_plan_id) : ""; const dedupeKey = sellingPlanGid || sellingPlanNumericId || `${groupId}::${sellingPlan.name || ""}::${sellingPlanIndex}`; if (seenKeys.has(dedupeKey)) return; seenKeys.add(dedupeKey); normalizedPlans.push({ id: sellingPlan.id != null ? sellingPlan.id : plan.id, parent_plan_id: plan.id, selling_plan_group_id: groupId, selling_plan_id: sellingPlan.selling_plan_id || "", name: sellingPlan.name || plan.name || "", description: sellingPlan.description || plan.description || "", delivery_policy: sellingPlan.delivery_policy || {}, billing_policy: sellingPlan.billing_policy || {}, pricing_polices: Array.isArray(sellingPlan.pricing_polices) ? sellingPlan.pricing_polices : [], position: sellingPlan.position != null ? sellingPlan.position : plan.position, recommended: sellingPlan.recommended != null ? !!sellingPlan.recommended : !!plan.recommended, type: plan.type || "regular", products: groupProducts, shipping_policy: groupShippingPolicy }); }); }); normalizedPlans.sort(function(a, b) { return (parseInt(a.position, 10) || 0) - (parseInt(b.position, 10) || 0); }); return normalizedPlans; } function getPlanShipmentCount(deliveryPolicy, billingPolicy) { var deliveryFrequency = parseInt(deliveryPolicy?.frequency, 10) || 0; var billingFrequency = parseInt(billingPolicy?.frequency, 10) || 0; var deliveryInterval = (deliveryPolicy?.interval || "").toLowerCase(); var billingInterval = (billingPolicy?.interval || "").toLowerCase(); if (!deliveryFrequency || !billingFrequency) return 1; if ( deliveryInterval && billingInterval && deliveryInterval === billingInterval && billingFrequency >= deliveryFrequency && billingFrequency % deliveryFrequency === 0 ) { return billingFrequency / deliveryFrequency; } return 1; } function recurPDP(data) { var prepaidCount = 0, regularCount = 0, prepaidDiscount = [], maxPrepaidDiscount = "", getPlanDesc = "", pdpTemplate = "", GetPlans = "", plans = Array.isArray(data?.plans) ? data.plans : []; const GetPlansLength = plans.length; $.each(plans, function(key, plan) { if (!plan) return; var DiscountPercentageHtml = "", DescriptionHtml = "", PlanHtml = "", PlanDiscount = 0, PlanDiscountType = "percentage", PlanType = "regular"; var pricingPolicy = ( Array.isArray(plan.pricing_polices) && plan.pricing_polices.length) ? plan.pricing_polices[0] : null; var deliveryPolicy = plan.delivery_policy || {}; var billingPolicy = plan.billing_policy || {}; var rawSellingPlanId = plan.selling_plan_id || ""; var sellingPlanId = rawSellingPlanId ? String(rawSellingPlanId).split("/").pop() : ""; var deliveryFrequency = parseInt(deliveryPolicy.frequency, 10) || ""; var deliveryInterval = deliveryPolicy.interval || ""; var billingFrequency = parseInt(billingPolicy.frequency, 10) || ""; var billingInterval = billingPolicy.interval || ""; var shipmentCount = getPlanShipmentCount(deliveryPolicy, billingPolicy); PlanType = plan.type || "regular"; if (shipmentCount > 1) { PlanType = "prepaid"; } if (PlanType === "prepaid") { prepaidCount += 1; if (pricingPolicy && pricingPolicy.discount) { prepaidDiscount.push(pricingPolicy.discount.value); } } else { regularCount += 1; } if (pricingPolicy && pricingPolicy.discount) { PlanDiscountType = pricingPolicy.discount.type || "percentage"; PlanDiscount = parseFloat(pricingPolicy.discount.value) || 0; if (PlanDiscount !== 0) { if (PlanDiscountType === "percentage") { DiscountPercentageHtml = '(' + PlanDiscount + '% Off)'; } else if (PlanDiscountType === "fixed") { DiscountPercentageHtml = '(Save ' + formatPriceMoney(PlanDiscount) + ')'; } else if (PlanDiscountType === "price") { DiscountPercentageHtml = '(Price ' + formatPriceMoney(PlanDiscount) + ')'; } } } if (plan.description) { DescriptionHtml = '"; } var optionAttrs = ' data-plan="' + (plan.id || "") + '"' + ' data-selling-plan="' + sellingPlanId + '"' + ' data-plan-name="' + (plan.name || "") + '"' + ' data-plan-shipment="' + shipmentCount + '"' + ' data-plan-discount="' + PlanDiscount + '"' + ' data-plan-discount-type="' + PlanDiscountType + '"' + ' data-delivery-frequency="' + deliveryFrequency + '"' + ' data-delivery-interval="' + deliveryInterval + '"' + ' data-billing-frequency="' + billingFrequency + '"' + ' data-billing-interval="' + billingInterval + '"' + ' data-plan-type="' + PlanType + '"' + ' data-recommended-frequency="' + (!!plan.recommended) + '"'; var optionAttrsWithoutSellingPlan = ' data-plan="' + (plan.id || "") + '"' + ' data-plan-name="' + (plan.name || "") + '"' + ' data-plan-shipment="' + shipmentCount + '"' + ' data-plan-discount="' + PlanDiscount + '"' + ' data-plan-discount-type="' + PlanDiscountType + '"' + ' data-delivery-frequency="' + deliveryFrequency + '"' + ' data-delivery-interval="' + deliveryInterval + '"' + ' data-billing-frequency="' + billingFrequency + '"' + ' data-billing-interval="' + billingInterval + '"' + ' data-plan-type="' + PlanType + '"' + ' data-recommended-frequency="' + (!!plan.recommended) + '"'; if (recurpay.checkout == "shopify") { if (plan.recommended === true) { PlanHtml += '"; } else { PlanHtml += '"; } } else { if (plan.recommended === true) { PlanHtml += '"; } else { PlanHtml += '"; } } GetPlans += PlanHtml; getPlanDesc += DescriptionHtml; }); if (regularCount > 0 && prepaidCount > 0 && prepaidDiscount.length) { maxPrepaidDiscount = Math.max.apply(Math, prepaidDiscount); } if (recurpay.oneTimePurchaseFirst === true) { pdpTemplate += '
'; } else { pdpTemplate += '
'; } pdpTemplate += '
'; pdpTemplate += ''; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += ''; pdpTemplate += '
' + recurpay.settings.translations.premium_subscription_label + "
"; pdpTemplate += '
' + recurpay.settings.translations.premium_subscription_label_description + "
"; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += '
'; let encodedPlans = encodeURIComponent(GetPlans); if ( recurpay.settings.translations.premium_frequency_dropdown_label != "" && recurpay.settings.translations.premium_frequency_dropdown_label != null && recurpay.settings.translations.premium_frequency_dropdown_label != undefined ) { pdpTemplate += '
' + recurpay.settings.translations.premium_frequency_dropdown_label + "
"; if (GetPlansLength == 1) { pdpTemplate += '"; } else { pdpTemplate += '"; } } else { if (GetPlansLength == 1) { pdpTemplate += '"; } else { pdpTemplate += '"; } } pdpTemplate += '
' + getPlanDesc + '
"; pdpTemplate += "
"; pdpTemplate += '
' + recurpay.settings.translations.premium_one_time_saving_icon + ""; pdpTemplate += '
'; pdpTemplate += "" + recurpay.settings.translations.premium_one_time_saving_msg + ""; pdpTemplate += ''; pdpTemplate += ''; pdpTemplate += '' + recurpay.settings.translations.premium_one_time_saving_label + ""; pdpTemplate += "
"; pdpTemplate += '
' + recurpay.settings.translations.premium_subscription_saving_icon + ""; pdpTemplate += '
'; pdpTemplate += "" + recurpay.settings.translations.premium_subscription_saving_msg + ""; pdpTemplate += '' + recurpay.settings.translations.premium_subscription_discount_label + ""; pdpTemplate += '' + recurpay.settings.translations.premium_subscription_saving_label + ""; pdpTemplate += "
"; pdpTemplate += "
"; pdpTemplate += '
'; pdpTemplate += ''; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += ''; pdpTemplate += '
' + recurpay.settings.translations.premium_onetime_label + "
"; pdpTemplate += '
'; pdpTemplate += "
"; pdpTemplate += ''; pdpTemplate += ''; pdpTemplate += ''; if (recurpay.checkout == "shopify") { pdpTemplate += ''; } pdpTemplate = pdpTemplate .split("[[SAVING_AMOUNT]]") .join(""); pdpTemplate = pdpTemplate .split("[[DISCOUNT_PERCENTAGE]]") .join(""); return pdpTemplate; } function updateGeneralSettings(primary_background,primary_foreground,secondary_background) { let settings_url=recurpay.generalURL+'/storefront/api/2024-07/widgets/configurations?'+recurpay.urlParam; $.ajax( { url:settings_url,type:"POST",data: { subscription_brand_color:primary_background,subscription_button_color:primary_background,subscription_button_text_color:primary_foreground,subscription_secondary_color:secondary_background,cart_upsell_brand_color:primary_background,cart_upsell_button_color:primary_background,cart_upsell_button_text_color:primary_foreground,cart_upsell_secondary_color:secondary_background }, success:function(response) { console.log(response); }, error:function(error) { console.log(error); } }); } function renderRecurpayAppBlockWidget($appBlock) { if ($appBlock.find('.recurpay-pdp-widget').length) return; let $productContainer = $appBlock.closest(productContainerSelector); let $form = $productContainer.find(atcFormSelector).first(); if (!$form.length) { $form = $productContainer.find('form').filter(function() { return $(this).find('input[name="id"], input[ref="variantId"]').length > 0; }).first(); } let product_id = $form.find('input[name="product-id"]').val() || $appBlock.closest('[data-product-id]').attr('data-product-id') || recurpay.product.id; let default_variant_id = $form.find('input[name="id"], select[name="id"], input[ref="variantId"]').val(); $appBlock.append(`
`); var pid = String(product_id); var plans = recurpay.globalPlanObjectMap && recurpay.globalPlanObjectMap[pid]; if (plans && plans.length) { $appBlock.find('.recurpay-pdp-widget').html(recurPDP({ id: pid, plans: plans })); recurpay.settings && recurpay.settings.sell_only_as_subscription === true ? updateSelectors(true) : updateSelectors(); var v = default_variant_id || recurpay.product.availableVariant; if (v) { recurDiscountedPrice(v); recurpay.handlePlanOnVariant(v); } } } if ($(document).find(appBlockSelector).length > 0) { var recurpayReinjectTimer = null; var run = function () { $(appBlockSelector).each(function () { renderRecurpayAppBlockWidget($(this)); }); }; run(); new MutationObserver(function () { clearTimeout(recurpayReinjectTimer); recurpayReinjectTimer = setTimeout(run, 50); }).observe(document.body, { childList: true, subtree: true }); } else if($(pdpSelector).length <= 0) { if(window.location.href.indexOf("/products/") > -1 && $(document).find(appBlockSelector).length <= 0) { if($(atcFormSelector).find(atcSelector).filter(':visible').length) { if($(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('display') == 'flex' && $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('flex-direction') == 'row') { $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().before('
'); } else if($(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('display') == 'grid' || $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('display') == 'inline-grid') { $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().before('
'); } else { if($(atcFormSelector).parents('.product__info-container').find(atcSelector).length) { $(atcFormSelector).parents('.product__info-container').find(atcSelector).filter(':visible').first().before('
'); } else { $(atcFormSelector).find(atcSelector).filter(':visible').first().before('
'); } } if($(pdpSelector).parent().css('position') == 'fixed' || $(pdpSelector).parent().css('position') == 'sticky' || $(pdpSelector).parent().css('position') == 'absolute' ) { $(pdpSelector).parent().addClass("recurpay-z-index"); } } else if($(atcFormSelector).find(atcSelector).length) { if($(atcFormSelector).find(atcSelector).first().parent().css('display') == 'flex' && $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('flex-direction') == 'row') { $(atcFormSelector).find(atcSelector).first().parent().before('
'); } else { $(atcFormSelector).find(atcSelector).first().before('
'); } if($(pdpSelector).parent().css('position') == 'fixed' || $(pdpSelector).parent().css('position') == 'sticky' || $(pdpSelector).parent().css('position') == 'absolute' ) { $(pdpSelector).parent().addClass("recurpay-z-index"); } } else { $(atcFormSelector).append('
') } } } if($(pdpSelector).length) { recurpay.allProducts = []; for(i=0;i<$(pdpSelector).length; i++) { if($(pdpSelector).eq(i).attr("data-product-id") != undefined && $(pdpSelector).eq(i).attr("data-product-available") != undefined ) { recurpay.allProducts.push($(pdpSelector).eq(i).attr("data-product-id")); } } $.ajax({ url: recurpay.pdpAPI, type: 'POST', async: true, contentType: 'application/json', data: JSON.stringify({ products: recurpay.allProducts.map(id => ({ id: parseInt(id) })) }), success: function(response) { const payload = response?.data || {}; const rawProducts = Array.isArray(payload.products) ? payload.products : []; const settings = payload.configurations || {}; const store = payload.store || {}; const productMap = {}; rawProducts.forEach(function(product) { if (!product || !product.id) return; const productId = String(product.id); if (!productMap[productId]) { productMap[productId] = { ...product, plans: Array.isArray(product.plans) ? [...product.plans] : [], variants: Array.isArray(product.variants) ? [...product.variants] : [] }; } else { const existing = productMap[productId]; if (Array.isArray(product.plans)) { existing.plans = existing.plans.concat(product.plans); } if ((!existing.variants || !existing.variants.length) && Array.isArray(product.variants)) { existing.variants = product.variants; } } }); const normalizedProducts = Object.values(productMap).map(function(product) { return { ...product, plans: normalizeProductPlans(product) }; }); if (!normalizedProducts.length) { console.log("No products found in widget response", response); return; } const productsWithPlans = normalizedProducts.filter(function(product) { return Array.isArray(product.plans) && product.plans.length; }); if (!productsWithPlans.length) { console.log("No product/plans found in widget response", response); return; } recurpay.productDatas = normalizedProducts.map(function(product) { return { product: product }; }); if (settings.is_one_time_purchase_default === true) { recurpay.subscriptionFirst = false; } else { recurpay.subscriptionFirst = true; } if (settings.is_one_time_purchase_first === true) { recurpay.oneTimePurchaseFirst = true; } else { recurpay.oneTimePurchaseFirst = false; } recurpay.multiply_price_with_quantity = !!settings.is_price_multiplied_by_quantity; recurpay.show_price_in_freq_dropdown = !!settings.is_price_shown_in_frequency; if (settings.default_purchase_redirection !== undefined) { recurpay.action = settings.default_purchase_redirection; } if (settings.is_manual_payment_subscription !== undefined) { recurpay.manualPaymentSubscription = !!settings.is_manual_payment_subscription; } if (settings.translations && !$.isEmptyObject(settings.translations)) { recurpay.settings = settings; recurpay.hasScript = !!settings.has_scripts; let brandPrimaryBg = recurpay.shop_brand_primary_background_color; let brandPrimaryFg = recurpay.shop_brand_primary_foreground_color; let brandSecondaryBg = recurpay.shop_brand_secondary_background_color; if ( settings.snippet_color_codes && settings.snippet_color_codes.is_default_widget_configuration && (brandPrimaryBg || brandSecondaryBg) ) { document.documentElement.style.setProperty('--recurpay_primary_color', brandPrimaryBg); document.documentElement.style.setProperty('--recurpay_secondary_color', brandSecondaryBg); document.documentElement.style.setProperty('--recurpay_button_text_color', brandPrimaryFg); document.documentElement.style.setProperty('--recurpay_button_bg_color', brandPrimaryBg); document.documentElement.style.setProperty('--recurpay_savings_bg_color', recurpay.hexToRgbA(brandPrimaryBg)); updateGeneralSettings(brandPrimaryBg, brandPrimaryFg, brandSecondaryBg); } else if (settings.snippet_color_codes) { document.documentElement.style.setProperty('--recurpay_primary_color', settings.snippet_color_codes.subscription_brand_color); document.documentElement.style.setProperty('--recurpay_secondary_color', settings.snippet_color_codes.subscription_secondary_color); document.documentElement.style.setProperty('--recurpay_button_text_color', settings.snippet_color_codes.subscription_button_text_color); document.documentElement.style.setProperty('--recurpay_button_bg_color', settings.snippet_color_codes.subscription_button_color); document.documentElement.style.setProperty('--recurpay_savings_bg_color', recurpay.hexToRgbA(settings.snippet_color_codes.subscription_brand_color)); } } recurpay.globalPlanObjectMap = recurpay.globalPlanObjectMap || {}; normalizedProducts.forEach(function(product) { const normalizedProduct = { id: parseInt(product.id, 10), plans: Array.isArray(product.plans) ? product.plans : [], variants: Array.isArray(product.variants) ? product.variants : [] }; if (!normalizedProduct.plans.length) return; recurpay.globalPlanObjectMap[String(normalizedProduct.id)] = normalizedProduct.plans; const pdpHTML = recurPDP(normalizedProduct); const getElem = $('.recurpay-pdp-widget[data-product-id="' + normalizedProduct.id + '"]'); if ($(getElem).length && $(getElem).attr("data-product-available") == "true") { $(getElem).html(pdpHTML); } if (normalizedProduct.variants.length) { const variantId = recurpay.product.availableVariant || normalizedProduct.variants[0].id; recurDiscountedPrice(variantId); recurpay.handlePlanOnVariant(variantId); } }); recurpay.hasScript = settings.has_scripts || false; if ( recurpay.product.availableVariant !== "" && recurpay.product.availableVariant !== undefined ) { recurpay.product.selectedVariant = recurpay.product.availableVariant; recurDiscountedPrice(recurpay.product.availableVariant); recurpay.handlePlanOnVariant(recurpay.product.availableVariant); } else { const firstProductWithVariants = normalizedProducts.find(function(product) { return Array.isArray(product.variants) && product.variants.length; }); } if (settings.sell_only_as_subscription === true) { updateSelectors(true); } else { updateSelectors(); } if (store.created_at) { const createdDate = new Date(store.created_at); const releaseDate = new Date('2024-07-16T00:00:00.000Z'); if (createdDate.toISOString().split('T')[0] < releaseDate.toISOString().split('T')[0]) { $(footerManageSubcriptionSelector).hide(); } } fetchVariants(); }, error: function(xhr) { console.log("PDP widget load failed", xhr); } }); } else { if((window.location.href.indexOf("/products/") > -1) && (window.location.href.indexOf("recurpay_preview=true") > -1)) { var domain_array = recurpay.shopDomainURL.split('.'); var domain_string = domain_array[0]; var recurpay_domain = 'https://' + domain_string + '.recurpay.com'; var modalHTML = ""; modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '' modalHTML += '
' modalHTML += 'Note: This is not visible to your customers' modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '
Looks like the subscription option is not visible on your store due to some conflict with theme. Talk to us on Live Chat to get it resolved instantly
' modalHTML += '
' modalHTML += '
' if($('[data-recurpay-visibility-modal]').length <= 0) { if($('body').length) { $('body').append(modalHTML); } else if($('html').length) { $('html').append(modalHTML); } } } if((window.location.href.indexOf("/products/") > -1)) { recurpay.logEvent("product_widget","Failed to show product snippet", "critical"); } } function recurProperties(e){var a=$(e).parents(pdpSelector);if($(a).find("[name='recurpay__group_main'][value='subscription']").is(":checked")){var r=$(a).find('[name="recurpay-input"] option:selected').attr("data-plan-name"),t=$(a).find('[name="recurpay-input"] option:selected').attr("data-plan"),o=e.closest(appBlockSelector).length>0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector):$(a),i=function(c,n,v){o.find(c).length<=0?o.append(``):o.find(c).attr("name",n).val(v)};e.closest(appBlockSelector).length>0?(i(".recurpay_plan_name","properties[_Plan]",r),i(".recurpay_plan_id","properties[_PlanId]",t)):($(a).find(".recurpay_plan_name").attr("name","properties[_Plan]").val(r),$(a).find(".recurpay_plan_id").attr("name","properties[_PlanId]").val(t));if(recurpay.checkout=="shopify"&&recurpay.manualPaymentSubscription)e.closest(appBlockSelector).length>0?(i(".recurpay_manual_plan_id","properties[_RecurpayPlanId]",t),i(".recurpay_manual_payment","properties[_RecurpayManualPaymentSubscription]","1")):($(a).find(".recurpay_manual_plan_id").length<=0?$(a).append(``):$(a).find(".recurpay_manual_plan_id").attr("name","properties[_RecurpayPlanId]").val(t),$(a).find(".recurpay_manual_payment").length<=0?$(a).append(``):$(a).find(".recurpay_manual_payment").attr("name","properties[_RecurpayManualPaymentSubscription]").val("1"));parseInt(recurpay.subscriptionInfluence&&recurpay.subscriptionInfluenceCount)>=1&&(e.closest(appBlockSelector).length>0?i(".recurpay_purchase_data","properties[_PurchaseData]",recurpay.subscriptionInfluenceCount):$(a).find(".recurpay_purchase_data").attr("name","properties[_PurchaseData]").val(recurpay.subscriptionInfluenceCount));$(a).find(".recurpay__description[data-description-id]").hide();$(a).find('.recurpay__description[data-description-id="'+t+'"]').show();if(recurpay.checkout=="shopify"&&!recurpay.manualPaymentSubscription){var n=$(a).find('[name="recurpay-input"] option:selected').attr("data-selling-plan");e.closest(appBlockSelector).length>0?i(".recurpay_selling_plan_id","selling_plan",n):$(a).find(".recurpay_selling_plan_id").attr("name","selling_plan").val(n);window._RestockRocket&&typeof window._RestockRocket.getSellingPlan=="function"&&($('.restock-rocket-form-input[name="selling_plan"]').attr("name",""),$(".restock-rocket-preorder-description").hide())}else recurpay.checkout=="shopify"&&recurpay.manualPaymentSubscription&&(e.closest(appBlockSelector).length>0?o.find(".recurpay_selling_plan_id").attr("name","").val(""):$(a).find(".recurpay_selling_plan_id").attr("name","").val(""))}else{var o=e.closest(appBlockSelector).length>0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector):$(a);o.find(".recurpay_plan_name").attr("name","");o.find(".recurpay_plan_id").attr("name","");o.find(".recurpay_purchase_data").attr("name","");o.find(".recurpay_manual_plan_id").attr("name","").val("");o.find(".recurpay_manual_payment").attr("name","").val("");if(recurpay.checkout=="shopify"){o.find(".recurpay_selling_plan_id").attr("name","");window._RestockRocket&&typeof window._RestockRocket.getSellingPlan=="function"&&(p=window._RestockRocket.getSellingPlan(),$(".restock-rocket-form-input").attr("name","selling_plan"),$(".restock-rocket-form-input").val(p.shopify_selling_plan_id),$(".restock-rocket-preorder-description").show())}}offerSavings(a)} function addSubscription(btn) { let $appBlock = $(btn).closest(appBlockSelector); let isInsideAppBlock = $appBlock.length > 0 && $(pdpSelector).closest(appBlockSelector).length > 0; let $form = null; if ($appBlock.parents(appBlockParentSelector).length && $appBlock.parents(appBlockParentSelector).find(atcSelector).length) { $form = isInsideAppBlock ? $appBlock.parents(appBlockParentSelector).find(atcSelector).parents(atcFormSelector) : $(btn).parents(atcFormSelector); } else if ($appBlock.closest(".product-grid__item").length && $appBlock.closest(".product-grid__item").find(atcSelector).length) { $form = isInsideAppBlock ? $appBlock.closest(".product-grid__item").find(atcSelector).parents(atcFormSelector) : $(btn).parents(atcFormSelector); } else { $form = isInsideAppBlock ? $(atcSelector).parents(atcFormSelector) : $(btn).parents(atcFormSelector); } let $variantSelector = $form.find('[name="id"]'); let $quantitySelector = $form.find('[name="quantity"]'); let $inputSelect = isInsideAppBlock ? $appBlock.find(pdpSelector).find('[name="recurpay-input"] option:selected') : $form.find(pdpSelector).find('[name="recurpay-input"] option:selected'); let subscriptionPlanId = $inputSelect.attr('data-plan') || ''; let subscriptionPlanName = $inputSelect.attr('data-plan-name') || ''; let subscriptionPlanType = $inputSelect.attr('data-plan-type') || ''; let planVariant = $variantSelector.length > 0 ? parseInt($variantSelector.val()) : parseInt(recurpay.product.availableVariant); let planQuantity = $quantitySelector.length > 0 ? parseInt($quantitySelector.val()) : 1; recurProperties($(btn).closest(pdpSelector).find('[name="recurpay__group_main"]')); let planParams = {}; if (recurpay.checkout == "shopify") { let sellingPlanId = isInsideAppBlock ? $appBlock.find(pdpSelector).find('[name="recurpay-input"] option:selected').attr('data-selling-plan') : $form.find(pdpSelector).find('[name="recurpay-input"] option:selected').attr('data-selling-plan'); planParams = { id: planVariant, quantity: planQuantity, properties: { '_Plan': subscriptionPlanName, '_PlanId': subscriptionPlanId } }; if (!recurpay.manualPaymentSubscription) { if (!sellingPlanId || sellingPlanId === 'undefined' || sellingPlanId === 'null') { console.warn('[Recurpay] selling_plan ID is missing — cannot add subscription to cart.'); return; } planParams.selling_plan = sellingPlanId; } if (recurpay.manualPaymentSubscription) { planParams.properties['_RecurpayPlanId'] = subscriptionPlanId; planParams.properties['_RecurpayManualPaymentSubscription'] = 1; } } else { planParams = { id: planVariant, quantity: planQuantity, properties: { '_Plan': subscriptionPlanName, '_PlanId': subscriptionPlanId } }; } if (recurpay.checkout == "recurpay" && !recurpay.prepaidMixedCart && subscriptionPlanType == "prepaid") { $.getJSON('/cart', function(response) { response.items = []; response.items.push(planParams); recurpay.recurCart(response); }); } else { if (recurpay.action === "default" && $(atcFormSelector).find(atcSelector).length) { if ($form.data("recurpaySubmitting")) return; $form.data("recurpaySubmitting", true); try { if ($form[0].requestSubmit) { $form[0].requestSubmit(); } else { $form[0].submit(); } } finally { setTimeout(function () { $form.removeData("recurpaySubmitting"); }, 500); } return; } else { $.ajax({ type: 'POST', url: '/cart/add.js', dataType: 'json', data: planParams, success: function() { if (recurpay.checkout == "recurpay" && recurpay.action == "checkout") { $.getJSON('/cart', function(response) { recurpay.recurCart(response); }); } else if (recurpay.action == "cart") { document.location.href = '/cart'; } else { document.location.href = '/checkout'; } }, error: function(xhr) { var err = eval("(" + xhr.responseText + ")"); $('[data-recurpay-error]').html(err.description).show().delay(3000).fadeOut(); } }); } } } function loadRecurpayScripts() { $.ajax( { url:recurpay.scriptsAPI,type:'GET',async:true,success:function(htmlContent) { if(!$.trim(htmlContent))return; var $tempDiv=$('
').html(htmlContent); $tempDiv.find('style').each(function() { $('head').append($('