var appstleInit = function () {
var head = document.getElementsByTagName('head')[0];
var startingTime = new Date().getTime();
if (typeof jQuery == 'undefined' && !RS?.Config?.disableLoadingJquery) {
var jQueryScript = document.createElement('script');
jQueryScript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js';
jQueryScript.type = 'text/javascript';
head.appendChild(jQueryScript);
}
if (typeof Mustache == 'undefined') {
var mustacheScript = document.createElement('script');
mustacheScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.1.0/mustache.js';
mustacheScript.type = 'text/javascript';
head.appendChild(mustacheScript);
}
// Poll for jQuery to come into existance
var checkReady = function (callback) {
if (window.jQuery && window.Mustache && window.Shopify) {
callback(jQuery);
} else {
window.setTimeout(function () {
checkReady(callback);
}, 20);
}
};
const urlParams = new URLSearchParams(window.location.search);
var globalUrlParameter = urlParams.get('variant');
// Start polling...
checkReady(function ($) {
(function () {
var endingTime = new Date().getTime();
var tookTime = endingTime - startingTime;
console.log("jQuery is loaded, after " + tookTime + " milliseconds!");
function renderWidget(standAloneProduct, standAloneElement, widgetId) {
if(!window["Shopify"]) {
return;
}
RS.Config = Object.assign(RS.Config, "undefined" != typeof _RSConfig && null !== _RSConfig ? _RSConfig : {})
window.RSConfig = RS.Config;
var product = RSConfig.product;
if (standAloneProduct) {
product = standAloneProduct;
}
processProductVariants(product);
var localVariantsByTitle = RSConfig.variantsByTitle;
var localVariantsById = RSConfig.variantsById;
var localWindowVariant;
function processProductVariants(product) {
if (!product) {
return;
}
var variants = product.variants;
var _variantsByTitle = {};
var _variantsById = {};
for (var index = 0; index < variants.length; index++) {
var variant = variants[index];
_variantsByTitle[variant.title] = Object.assign({}, variant);
_variantsById[variant.id] = Object.assign({}, variant);
}
RSConfig.variantsByTitle = _variantsByTitle;
RSConfig.variantsById = _variantsById;
}
function urlParamsToObject() {
var queryStringTokens = location.search.substr(1).split("&");
var result = {};
for (var index = 0; index < queryStringTokens.length; index++) {
var keyValues = queryStringTokens[index].split("=")
result[keyValues[0]] = keyValues[1];
}
return result
}
function urlParam(key) {
return urlParamsToObject()[key] || null
}
function detectVariant(previousVariantId, selector, product) {
var variantId = urlParam("variant");
if (selector.closest('form[action$="/cart/add"]').find('[name=id]').length > 0 && selector.closest('form[action$="/cart/add"]').find('[name=id]')[0].value) {
variantId = selector.closest('form[action$="/cart/add"]').find('[name=id]')[0].value;
return localVariantsById[variantId];
} else if (variantId) {
return localVariantsById[variantId];
} else if (Object.values(localVariantsById).some(data => data?.title == $("form select[name='options[Bundle]']")?.val())) {
return Object.values(localVariantsById).find(data => data?.title == $("select[name='options[Bundle]']").val())
} else {
var titleTokens;
titleTokens = function () {
var variantTokens = [];
var singleOptionSelector = selector.closest('form[action$="/cart/add"]').find("select.single-option-selector");
if (singleOptionSelector != null && singleOptionSelector.selectedIndex != null && singleOptionSelector.selectedIndex !== -1) {
variantTokens.push(singleOptionSelector[singleOptionSelector.selectedIndex].value)
} else {
variantTokens.push(void 0);
}
return variantTokens
}();
var variant = localVariantsByTitle[titleTokens.join(" / ")]
if (variant) {
return variant;
} else {
var variant = product.variants[0];
return variant;
}
}
}
function getSellingPlanAllocation(variantId, sellingPlanId) {
var variant = localVariantsById[variantId];
return variant.selling_plan_allocations.find(function (plan) {
return plan.selling_plan_id === sellingPlanId;
});
}
function compareCustomerTags(array1, array2) {
return array1.filter(function (n) {
return array2.indexOf(n) != -1;
});
}
function isSellingPlanVisible(sellingPlanId) {
var customerId = __st.cid;
var userTags = RSConfig.customer_tags || [];
var isVisible = true;
if (!customerId && RSConfig.memberOnlySellingPlansJson && RSConfig.memberOnlySellingPlansJson[sellingPlanId]) {
isVisible = false;
}
if (customerId && RSConfig.nonMemberOnlySellingPlansJson && RSConfig.nonMemberOnlySellingPlansJson[sellingPlanId]) {
isVisible = false;
}
if (isVisible && customerId && RSConfig.memberOnlySellingPlansJson && RSConfig.memberOnlySellingPlansJson[sellingPlanId]) {
if (RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberInclusiveTags && RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberInclusiveTags.trim()) {
var sellingPlanTags = RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberInclusiveTags.split(",");
var tagFound = compareCustomerTags(userTags, sellingPlanTags);
isVisible = (tagFound.length > 0);
}
}
return isVisible;
}
function buildSellingPlantText(sellingPlan) {
var sellingPlanModel = sellingPlan.totalPrice == sellingPlan.formattedPrice ?
{
sellingPlanName: sellingPlan.name,
sellingPlanPrice: `${sellingPlan.formattedPrice}`,
secondSellingPlanPrice: `${sellingPlan.secondFormattedPrice}`,
discountText: sellingPlan?.discountText,
totalPrice: `${sellingPlan?.totalPrice}`,
}
: {
sellingPlanName: sellingPlan.name,
totalPrice: `${sellingPlan?.totalPrice}`,
sellingPlanPrice: `${sellingPlan.formattedPrice}`,
secondSellingPlanPrice: `${sellingPlan.secondFormattedPrice}`,
discountText: sellingPlan.discountText
};
var sellingPlanDisplayText = Mustache.render(RS.Config.sellingPlanTitleText, sellingPlanModel);
return wrapPriceWithSpanTag(sellingPlanDisplayText);
}
function buildAtcButtonSelector() {
var atcButtonSelector = RSConfig.atcButtonSelector || "form[action$='/cart/add'] [type='submit']"
var atcButtonSelectorModel = {
productId: product.id,
};
atcButtonSelector = Mustache.render(atcButtonSelector, atcButtonSelectorModel);
return atcButtonSelector;
}
function buildOneTimePriceText(price) {
var priceModel = {
price: price,
};
var priceText = Mustache.render(RS.Config.oneTimePriceText, priceModel);
return wrapPriceWithSpanTag(priceText);
}
function buildSubscriptionOptionText(isPrepaidPlan, discountValue) {
let subscriptionOptionModel = {
discountValue: discountValue
};
let subscriptionOptionText = Mustache.render(RS.Config.subscriptionOptionText, subscriptionOptionModel);
return wrapPriceWithSpanTag(subscriptionOptionText);
}
function buildSelectedPriceText(price, isPrePaid, totalPrice) {
var priceModel = isPrePaid ? {
pricePerDelivery: price,
totalPrice: totalPrice
} : {
price: price,
};
var text = isPrePaid ? RS.Config.selectedPrepaidSellingPlanPriceText : RS.Config.selectedPayAsYouGoSellingPlanPriceText;
var priceText = Mustache.render(text, priceModel);
return wrapPriceWithSpanTag(priceText);
}
function buildPrepaidPerDeliveryPriceText(price) {
var priceModel = {
prepaidPerDeliveryPrice: price,
}
return wrapPriceWithSpanTag(Mustache.render(RS.Config.totalPricePerDeliveryText, priceModel));
}
function buildSelectedTooltipPrePaidText(price, totalPrice) {
var prepaidPricetooltipModel = {
pricePerDelivery: price,
totalPrice: totalPrice
}
var text = RS.Config.tooltipDescriptionOnPrepaidPlan;
var prepaidPricetooltipText = Mustache.render(text, prepaidPricetooltipModel);
return wrapPriceWithSpanTag(prepaidPricetooltipText);
}
function buildSelectedTooltipDiscountText(selectedSellingPlanAllocationObj, multipleDiscount) {
if (selectedSellingPlanAllocationObj?.price_adjustments?.length == 2) {
var discountModel = {
firstPrice: formatPriceWithQuantity(selectedSellingPlanAllocationObj?.price_adjustments[0]?.price),
secondPrice: formatPriceWithQuantity(selectedSellingPlanAllocationObj?.price_adjustments[1]?.price),
discountOne: multipleDiscount.length > 0 ? multipleDiscount[0] : "",
discountTwo: multipleDiscount.length == 2 ? multipleDiscount[1] : ""
};
return wrapPriceWithSpanTag(Mustache.render(RS.Config.tooltipDescriptionOnMultipleDiscount, discountModel));
}
}
function buildTooltipDetailsText(prepaidText, isPrePaid, discountText) {
var tooltipDetailModel = isPrePaid ? {
prepaidDetails: prepaidText,
discountDetails: discountText,
defaultTooltipDescription: RS.Config.tooltipDesctiption
}
:
{
defaultTooltipDescription: RS.Config.tooltipDesctiption,
discountDetails: discountText
};
// let text = RS.Config.tooltipDesctiption + (isPrePaid ? "{{prepaidDetails}}" : "") + (discountText!= undefined ? "{{discountDetails}}": "");
let text = RS.Config.tooltipDescriptionCustomization;
var tooltipText = Mustache.render(text, tooltipDetailModel);
return wrapPriceWithSpanTag(tooltipText);
}
function populateDropdown(purchaseOptions, variant) {
var sellingPlanVariants = [];
jQuery.each(product.selling_plan_groups, function (index, sellingPlanGroup) {
if (sellingPlanGroup.app_id === 'appstle') {
jQuery.each(sellingPlanGroup.selling_plans, function (subIndex, sellingPlan) {
var visible = isSellingPlanVisible(sellingPlan.id);
if (visible) {
var sellingPlanAllocation = getSellingPlanAllocation(variant.id, sellingPlan.id);
if (!sellingPlanAllocation) {
return
}
var price = sellingPlanAllocation.per_delivery_price;
var totalPrice = formatPriceWithQuantity(sellingPlanAllocation?.price);
var formattedPrice = formatPriceWithQuantity(price);
var secondPrice = null;
var secondFormattedPrice = null;
if (sellingPlanAllocation
&& sellingPlanAllocation.price_adjustments
&& sellingPlanAllocation.price_adjustments.length === 2) {
secondPrice = sellingPlanAllocation.price_adjustments[1].price;
secondFormattedPrice = formatPriceWithQuantity(secondPrice);
} else {
secondPrice = price;
secondFormattedPrice = formattedPrice;
}
let discountText;
var priceAdjustment = sellingPlan?.price_adjustments[0];
if (priceAdjustment?.value_type !== 'percentage') {
discountText = formatPriceWithQuantity(priceAdjustment?.value);
} else {
discountText = priceAdjustment?.value + '%';
}
sellingPlanVariants.push({
"name": sellingPlan.name,
"description": sellingPlan.description,
"id": sellingPlan.id,
"formattedPrice": formattedPrice,
"price": price,
"totalPrice": totalPrice,
"secondPrice": secondPrice,
"secondFormattedPrice": secondFormattedPrice,
"discountText": discountText
});
}
});
}
});
if (sellingPlanVariants.length > 0) {
if (sellingPlanVariants.length < 2) {
jQuery(purchaseOptions).find('.appstle_subscribe_option').children().hide();
var singleSellingPlanDisplayText = buildSellingPlantText(sellingPlanVariants[0]);
var planText = jQuery(`
${singleSellingPlanDisplayText}
`);
planText.appendTo(purchaseOptions.find('.appstle_subscribe_option'))
if (sellingPlanVariants[0]?.description) {
jQuery(`${sellingPlanVariants[0]?.description}
` ).appendTo(purchaseOptions.find('.appstle_subscribe_option'));
}
}
if (!RSConfig?.sortByDefaultSequence) {
sellingPlanVariants.sort(function (sellingPlanA, sellingPlanB) {
return sellingPlanA.price - sellingPlanB.price;
})
}
jQuery(sellingPlanVariants).each(function (index, sellingPlan) {
var sellingPlanDisplayText = buildSellingPlantText(sellingPlan);
if (!RSConfig?.switchRadioButtonWidget) {
jQuery('', {
value: sellingPlan.id,
html: sellingPlanDisplayText
}).appendTo(purchaseOptions.find('select'));
} else {
jQuery(`
${sellingPlan?.description ? `
${sellingPlan?.description}
` : ``}
`).appendTo(purchaseOptions.find('.appstleRadioSellingPlanWrapper'));
}
});
} else {
try {
jQuery('#appstle_subscription_widget' + widgetId).remove()
var timer = setTimeout(function () {
jQuery('#appstle_subscription_widget' + widgetId).remove()
clearTimeout(timer)
})
} catch (e) {
}
}
/*sellingPlanVariants.length > 0 ? purchaseOptions.find('.appstle_subscription_amount')
.text(sellingPlanVariants[0].formattedPrice) : '';*/
return sellingPlanVariants;
}
var appstleSubscriptionFunction = function () {
if (urlIsProductPage() === true || appstleStandAloneSelectorExists()) {
var atcButtonSelector = buildAtcButtonSelector();
var atcButton = jQuery(atcButtonSelector).first();
if (standAloneElement) {
atcButton = standAloneElement;
}
var purchaseOptionsText;
var purchaseOptions;
var variantId;
var subscriptionWrapper;
var subscriptionWidget;
var subscriptionTooltip;
var appstleWidgetPlaceHolderSelector = "#appstle-subscription-widget-placeholder";
atcButton.parents(RSConfig?.widgetParentSelector).find(RSConfig?.quantitySelector).on('change, click', function () {
setTimeout(updateStateOfWidget, 100)
});
var reload = function () {
// RSConfig.switchRadioButtonWidget = true;
try {
// if(!product.available)
// {
// return;
// }
atcButton = jQuery(atcButtonSelector).first();
if (standAloneElement) {
atcButton = standAloneElement;
}
var variant = detectVariant(variantId, atcButton, product);
if (variant) {
var localVariantId = variant.id;
if (variantId) {
if (variantId === localVariantId) {
return;
}
}
var appstle_selling_plan_groups;
if (product.selling_plan_groups && product.selling_plan_groups.length > 0) {
appstle_selling_plan_groups = product.selling_plan_groups.filter(function (group) {
return group.app_id === 'appstle'
})
}
if (appstle_selling_plan_groups && appstle_selling_plan_groups.length > 0 && RS.Config.widgetEnabled) {
localWindowVariant = variant;
var widgetPlacement = RS.Config.selectors.atcButtonPlacement;
if (!subscriptionWrapper) {
subscriptionWidget = jQuery('');
purchaseOptionsText = RS.Config.purchaseOptionsText ? jQuery('' + RS.Config.purchaseOptionsText + '
') : '';
subscriptionWrapper = jQuery('');
subscriptionTooltip = RS.Config.tooltipTitle && RS.Config.showTooltip && !RS.Config.showStaticTooltip ?
jQuery(``) : RS.Config.showTooltip && RS.Config.showStaticTooltip && jQuery(`${RS.Config.tooltipDesctiption}
`);
purchaseOptionsText ? purchaseOptionsText.appendTo(subscriptionWidget) : '';
addSubscriptionItems(subscriptionWrapper, variant);
subscriptionWrapper.appendTo(subscriptionWidget);
subscriptionTooltip ? subscriptionTooltip.appendTo(subscriptionWidget) : '';
} else {
unbindEventListeners();
subscriptionWrapper.children().remove();
addSubscriptionItems(subscriptionWrapper, variant);
subscriptionTooltip ? subscriptionWrapper.insertBefore(subscriptionTooltip) : subscriptionWrapper.appendTo(subscriptionWidget);
}
if(!product?.available)
{
if(RS.Config?.widgetEnabledOnSoldVariant == "false")
{
return;
}
}
if (jQuery(appstleWidgetPlaceHolderSelector).length) {
atcButton = jQuery(appstleWidgetPlaceHolderSelector).first();
widgetPlacement === 'FIRST_CHILD'
}
if (widgetPlacement === 'BEFORE') {
subscriptionWidget.insertBefore(atcButton);
} else if (widgetPlacement === 'AFTER') {
subscriptionWidget.insertAfter(atcButton);
} else if (widgetPlacement === 'FIRST_CHILD') {
subscriptionWidget.prependTo(atcButton);
} else if (widgetPlacement === 'LAST_CHILD') {
subscriptionWidget.appendTo(atcButton);
}
updateWidgetElements();
jQuery(document).trigger("appstle_widget_updated");
}
variantId = localVariantId;
}
} catch (e) {
console.log(e)
}
}
setTimeout(function () {
reload();
updateWidgetUIBasedOnQueryParams();
}, 13);
// CODE FOR CALL A FUNCTION AUTOMATICALLY WHEN URL VARIANT ID WILL CHANGE. IT WILL CHECK ON EVERY 5ms
// setInterval(()=>{
// var currentURLparam = new URLSearchParams(window.location.search)
// var currentParameter = currentURLparam.get('variant');
// if(globalUrlParameter != currentParameter)
// reload();
// updateHistoryState();
// globalUrlParameter= currentParameter;
// }, 500)
if (standAloneElement) {
standAloneElement.closest('form[action$="/cart/add"]').on('change', function () {
setTimeout(function () {
reload();
updateHistoryState();
if(window?._transcy)
{
window?._transcy?.methods?.reConvertCurrency()
}
}, parseInt(RSConfig?.scriptLoadDelay) > 0 ? parseInt(RSConfig?.scriptLoadDelay) : 30);
});
standAloneElement.closest('form[action$="/cart/add"]').on('click', function () {
setTimeout(function () {
reload();
updateHistoryState();
if(window?._transcy)
{
window?._transcy?.methods?.reConvertCurrency()
}
}, parseInt(RSConfig?.scriptLoadDelay) > 0 ? parseInt(RSConfig?.scriptLoadDelay) : 30);
});
} else {
jQuery(document).on('change', function () {
setTimeout(function () {
reload();
updateHistoryState();
if(window?._transcy)
{
window?._transcy?.methods?.reConvertCurrency()
}
}, parseInt(RSConfig?.scriptLoadDelay) > 0 ? parseInt(RSConfig?.scriptLoadDelay) : 30);
});
jQuery(document).on('click', function () {
setTimeout(function () {
reload();
updateHistoryState();
if(window?._transcy)
{
window?._transcy?.methods?.reConvertCurrency()
}
}, parseInt(RSConfig?.scriptLoadDelay) > 0 ? parseInt(RSConfig?.scriptLoadDelay) : 30);
});
}
}
if (urlIsAccountPage() === true) {
var subscriptionLinkSelector = RSConfig.selectors.subscriptionLinkSelector;
var subscriptionLinkPlacement = RSConfig.selectors.subscriptionLinkPlacement;
var manageSubscriptionLink = RSConfig.manageSubscriptionBtnFormat
if (subscriptionLinkPlacement.toLowerCase() === "after")
jQuery(subscriptionLinkSelector).after(manageSubscriptionLink)
else if (subscriptionLinkPlacement.toLowerCase() === "first_child")
jQuery(subscriptionLinkSelector).first(manageSubscriptionLink)
else if (subscriptionLinkPlacement.toLowerCase() === "last_child")
jQuery(subscriptionLinkSelector).last(manageSubscriptionLink)
else
jQuery(subscriptionLinkSelector).before(manageSubscriptionLink)
accountPageStyle();
}
}
deferJquery(appstleSubscriptionFunction);
function hidePaymentButtons() {
jQuery(RSConfig.selectors.payment_button_selectors).hide();
}
function showPaymentButtons() {
jQuery(RSConfig.selectors.payment_button_selectors).show();
}
function urlIsAccountPage() {
return window.location.pathname === '/account'
// if(window.location.pathname.includes('/account') || window.location.pathname === '/account')
// {
// return true
// }
}
function deferJquery(method) {
if (window.jQuery)
method();
else
setTimeout(function () {
deferJquery(method)
}, 50);
}
function addSubscriptionItems(subscriptionWrapper, variant) {
if (!product.requires_selling_plan) {
var oneTimePurchaseOption = jQuery(
`
`
);
oneTimePurchaseOption.appendTo(subscriptionWrapper);
}
var subscriptionDropdown = jQuery(
`
${RS.Config.sellingPlanSelectTitle ? `
` : ``}
${!RSConfig?.switchRadioButtonWidget ? `
` : `
`}
`
)
var sellingPlanVariants = populateDropdown(subscriptionDropdown, variant)
if (sellingPlanVariants && sellingPlanVariants.length > 0) {
if(RSConfig?.showSubOptionBeforeOneTime)
{
subscriptionDropdown.prependTo(subscriptionWrapper);
} else {
subscriptionDropdown.appendTo(subscriptionWrapper);
}
}
addStyle(widgetId);
}
function changeEventHandlerForRadio() {
jQuery('#appstle_subscription_widget' + widgetId).find('.appstle_subscription_wrapper input[type=radio]').on('change',
function () {
var subsOption = jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscribe_option');
var loyaltyTable = jQuery('#appstle_subscription_widget' + widgetId + ' .appstleLoyaltyTable');
if (subsOption.length > 0) {
if (checkIfSellingPlanGroupIsSelected()) {
subsOption.removeClass('appstle_hide_subsOption')
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option.appstle_include_dropdown').addClass('appstle_selected_background')
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option').first().removeClass('appstle_selected_background')
loyaltyTable.show();
} else {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option.appstle_include_dropdown').removeClass('appstle_selected_background')
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option').first().addClass('appstle_selected_background')
subsOption.addClass('appstle_hide_subsOption');
loyaltyTable.hide();
}
}
updateStateOfWidget();
});
}
function changeHandlerForSelect() {
if (!RSConfig?.switchRadioButtonWidget) {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper select').on('change', function (event) {
updateStateOfWidget();
});
} else {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscribe_option input').on('change', function (event) {
updateStateOfWidget();
});
}
}
function toggleTooltip() {
$( "[data-appstle-icon]" ).click(function() {
$(this).toggleClass('appstle-tooltip-show');
});
}
function triggerChangeEvent(selector) {
jQuery(selector).change();
}
function registerAndTriggerEventsForFormFields() {
changeEventHandlerForRadio();
changeHandlerForSelect();
toggleTooltip();
}
function unbindEventListeners() {
jQuery('.appstle_subscription_wrapper input[type=radio], .appstle_subscription_wrapper select').off('change')
}
function getSelectedSellingPlanPrice() {
var selectedSellingPlan = getSelectedSellingPlanId();
if (selectedSellingPlan) {
var selectedSellingPlanAllocation = getSellingPlanAllocation(localWindowVariant.id, parseInt(selectedSellingPlan));
return formatPriceWithQuantity(selectedSellingPlanAllocation.per_delivery_price);
} else {
return null;
}
}
function getCurrentQuantity() {
var atc = jQuery(buildAtcButtonSelector()).first();
return Array.prototype.slice.call(atc.parents(RSConfig?.widgetParentSelector).find(RSConfig?.quantitySelector)).map((el) => Number($(el).val())).reduce(function(a, b) {
return Math.max(a, b);
}, -Infinity);
}
function getCurrentQuantityPrice(price) {
return price * ((RSConfig?.updatePriceOnQuantityChange === "true") ? (parseInt(getCurrentQuantity()) || 1) : 1)
}
function formatPriceWithQuantity(price) {
return formatPrice(getCurrentQuantityPrice(price));
}
function getSelectedSellingPlanId() {
var value = null;
try {
if (!RSConfig?.switchRadioButtonWidget) {
value = jQuery("#appstle_subscription_widget" + widgetId).find('.appstle_subscription_wrapper_option.appstle_include_dropdown select').val();
} else {
value = jQuery("#appstle_subscription_widget" + widgetId).find('.appstle_subscribe_option input:checked').val();
}
} catch (e) {
}
return value;
}
function getVariantId() {
return jQuery('#appstle_subscription_widget' + widgetId).closest('form[action$="/cart/add"]').find('[name=id]')[0] == undefined ? localWindowVariant.id : jQuery('#appstle_subscription_widget' + widgetId).closest('form[action$="/cart/add"]').find('[name=id]')[0].value;
}
function updateOneTimePurchaseValueToRadio() {
var variantId = getVariantId();
var price = null;
if (standAloneElement) {
price = ((standAloneProduct?.variants.filter(variant => String(variant?.id) === String(variantId))).pop()).price
} else {
price = RSConfig?.variantsById[variantId]?.price
}
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option:not(.appstle_include_dropdown) .appstle_subscription_amount').html(wrapPriceWithSpanTag(buildOneTimePriceText(formatPriceWithQuantity(price))));
}
function updateSelectValueToRadio() {
var selectedSellingPlan = getSelectedSellingPlanId();
if (selectedSellingPlan) {
var variantId = getVariantId();
getLoyaltyProductData(selectedSellingPlan, checkIfSellingPlanGroupIsSelected())
var selectedSellingPlanAllocation = getSellingPlanAllocation(variantId, parseInt(selectedSellingPlan));
var formattedSelectedSellingPlanPrice = formatPriceWithQuantity(selectedSellingPlanAllocation.per_delivery_price);
var sellingPlanDescription = getSellingPlanDescription(selectedSellingPlanAllocation?.selling_plan_group_id, selectedSellingPlanAllocation?.selling_plan_id)
jQuery('#appstle_subscription_widget' + widgetId + ' #appstle_selling_plan_label_2' + widgetId).attr('value', selectedSellingPlan);
var isPrepaidPlan = selectedSellingPlanAllocation.per_delivery_price !== selectedSellingPlanAllocation.price;
var selectedPriceText = wrapPriceWithSpanTag(buildSelectedPriceText(
formattedSelectedSellingPlanPrice,
isPrepaidPlan,
formatPriceWithQuantity(selectedSellingPlanAllocation.price)));
let selectedDiscountSub = getSellingPlanDiscountPercentage();
let multipleDiscount = getSellingPlanDiscountPercentage(true);
var toolTipPrepaidText = buildSelectedTooltipPrePaidText(formattedSelectedSellingPlanPrice, formatPriceWithQuantity(selectedSellingPlanAllocation.price));
var toolTipDiscountText = buildSelectedTooltipDiscountText(selectedSellingPlanAllocation, multipleDiscount);
var tooltipText = buildTooltipDetailsText(toolTipPrepaidText, isPrepaidPlan, toolTipDiscountText);
var subscribesaveText = buildSubscriptionOptionText(isPrepaidPlan, selectedDiscountSub);
var prepaidPerDeliveryPriceText = buildPrepaidPerDeliveryPriceText(formattedSelectedSellingPlanPrice);
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_prepaid_description').remove();
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option.appstle_include_dropdown .appstle_subscription_amount').html(selectedPriceText);
if (isPrepaidPlan && prepaidPerDeliveryPriceText) {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_amount_wrapper').append(
`${wrapPriceWithSpanTag(prepaidPerDeliveryPriceText) || (wrapPriceWithSpanTag(formatPriceWithQuantity(selectedSellingPlanAllocation.price)) + '/delivery')}
`
)
}
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option.appstle_include_dropdown .appstle_subscription_radio_wrapper .appstle_subscribe_save_text').html(subscribesaveText);
if (checkIfSellingPlanGroupIsSelected() && tooltipText && tooltipText.trim()) {
if (RS.Config.showStaticTooltip) {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_tooltip_wrapper_static').html(tooltipText);
} else {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_tooltip_wrapper .appstle_tooltip .appstle_tooltip_content').html(tooltipText);
}
} else {
if (RS.Config.showStaticTooltip && RS.Config.tooltipDesctiption && RS.Config.tooltipDesctiption.trim()) {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_tooltip_wrapper_static').html(RS.Config.tooltipDesctiption);
} else {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_tooltip_wrapper .appstle_tooltip .appstle_tooltip_content').html(RS.Config.tooltipDesctiption);
}
}
jQuery('#appstle_subscription_widget' + widgetId + " .appstleSelectedSellingPlanOptionDescription").html(sellingPlanDescription);
}
}
function getLoyaltyProductData(selectedSellingPlan, show) {
var sellingPlanData = RSConfig?.sellingPlansJson?.find(function(item) {return item?.id.split("/").pop() === String(selectedSellingPlan)});
var productHandles = [];
if (sellingPlanData?.appstleCycles?.length) {
sellingPlanData?.appstleCycles?.forEach(function(cycle) {
productHandles.push(cycle?.freeProductHandle)
})
}
getAllProductData(productHandles, selectedSellingPlan, show)
}
function getAllProductData(productHandles, selectedSellingPlan, show) {
var currentProductHandle = productHandles.shift();
if (!window?.["products"]?.[currentProductHandle]) {
fetch(`/products/${currentProductHandle}.js`)
.then(res => {
if (res.ok) {
return res.json();
}
})
.then(res => {
if (!window["products"]) {
window["products"] = {};
}
window["products"][currentProductHandle] = res;
if(productHandles.length) {
getAllProductData(productHandles, selectedSellingPlan, show)
} else {
createLoyaltyTableData(selectedSellingPlan, show)
}
})
} else {
if(productHandles.length) {
getAllProductData(productHandles, selectedSellingPlan, show)
} else {
createLoyaltyTableData(selectedSellingPlan, show)
}
}
}
function createLoyaltyTableData(selectedSellingPlan, show) {
var tableData = [];
jQuery('#appstle_subscription_widget' + widgetId + ' .appstleLoyaltyTable').remove();
var sellingPlanData = RSConfig?.sellingPlansJson?.find(function(item) {return item?.id.split("/").pop() === String(selectedSellingPlan)});
var output = null;
if (sellingPlanData?.freeTrialEnabled) {
tableData.push({perkText: getPerkText(0, sellingPlanData.freeTrialCount, sellingPlanData.freeTrialInterval, sellingPlanData?.freeTrialEnabled)})
}
if (sellingPlanData?.afterCycle2) {
tableData.push({perkText: getPerkText(getBillingCycleText(sellingPlanData.afterCycle2), sellingPlanData.discountOffer2, sellingPlanData.discountType2, false)})
}
if (sellingPlanData?.appstleCycles?.length) {
sellingPlanData?.appstleCycles?.forEach(function(cycle) {
var productName = ""
if (cycle.discountType === "FREE_PRODUCT") {
productName = window?.products?.[cycle.freeProductHandle]?.title;
if (window?.products?.[cycle.freeProductHandle]?.variants.length > 1) {
var variant = window?.products?.[cycle.freeProductHandle]?.variants.filter(variant => variant.id === parseInt(cycle?.freeVariantId));
var variantTitle = (variant.pop())?.title;
productName = productName + " - " + variantTitle;
}
}
tableData.push({perkText: getPerkText(getBillingCycleText(cycle.afterCycle), cycle.value, cycle.discountType, false, productName)})
})
}
let loyaltyDetailLabelText = RSConfig?.loyaltyDetailsLabelText || "Subscriber Rewards";
if (tableData.length) {
var template = `
${loyaltyDetailLabelText}
{{#items}}
{{{perkText}}} |
{{/items}}
`
tableData = {"items": tableData};
output = Mustache.render(template, tableData);
jQuery(output).insertAfter('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper')
}
}
function getPerkText(billingCycle, discount, discountType, freeTrail, productName) {
if(RSConfig?.loyaltyPerkDescriptionText)
{
// NEED TO VERIFY
var selectedPerkText = {
discount: discount,
discountType: discountType,
formatDiscountedPrice: formatPrice(discount*100),
freeProductName: productName,
isDiscountTypePercentage: discountType === "PERCENTAGE",
isDiscountTypeShipping: discountType === "SHIPPING",
isDiscountTypeFreeProduct: discountType === "FREE_PRODUCT",
isDiscountTypeFixed: discountType === "FIXED",
isFreeTrial: freeTrail,
isCartPage: false,
billingCycleBlock: `${billingCycle}`
}
return Mustache.render(JSON.parse(RS.Config.labels)['appstle.subscription.wg.loyaltyPerkDescriptionTextV2'], selectedPerkText);
}
if (discountType === "PERCENTAGE") {
return `After ${billingCycle} order, get ${discount + "% off"}.`
} else if (discountType === "SHIPPING") {
return `After ${billingCycle} order, get ${`shipping at ${formatPrice(discount*100)}`}.`
} else if (discountType === "FREE_PRODUCT") {
return `After ${billingCycle} order, get FREE PRODUCT (${productName}).`
} else if (discountType === "FIXED") {
return `After ${billingCycle} order, get ${formatPrice(discount*100) + " off"}.`
}
if (freeTrail) {
return `Get ${discount} ${discountType}${discount > 1 ? 's' : ''} free trial.`
} else {
if (discountType === "PERCENTAGE") {
return `After ${billingCycle} order, get ${discount + "% off"}.`
} else if (discountType === "SHIPPING") {
return `After ${billingCycle} order, get ${`shipping at ${formatPrice(discount*100)}`}.`
} else if (discountType === "FREE_PRODUCT") {
return `After ${billingCycle} order, get FREE PRODUCT (${productName}).`
} else if (discountType === "FIXED") {
return `After ${billingCycle} order, get ${formatPrice(discount*100) + " off"}.`
}
}
}
function getSellingPlanDescription(groupId, sellingPlanId) {
var sellingPlanGroup = (product?.selling_plan_groups.filter(sellingPlanGroup => sellingPlanGroup?.id === groupId)).pop();
var sellingPlan = (sellingPlanGroup?.selling_plans?.filter(sellingPlan => sellingPlan?.id === sellingPlanId)).pop();
return sellingPlan.description || '';
}
function checkIfSellingPlanGroupIsSelected() {
var selected = false;
try {
selected = jQuery('#appstle_subscription_widget' + widgetId).find('.appstle_subscription_wrapper_option.appstle_include_dropdown input')[0].checked;
} catch (e) {
}
return selected;
}
function buildDiscountText(selectedDiscount) {
// selected discount customization start
var selectedDiscountModel = {
selectedDiscountPercentage: selectedDiscount
}
var selectedDiscountFormatDisplay = Mustache.render(RS.Config.selectedDiscountFormat, selectedDiscountModel);
// selected discount customization end
return wrapPriceWithSpanTag(selectedDiscountFormatDisplay);
}
function updateSellingPlanValueToFinalPrice() {
var selectorsObject = {
regular: {
sellingPrice: RSConfig.priceSelector,
saleBadgeTop: RSConfig.badgeTop
}
}
var selectors = selectorsObject.regular;
jQuery('.appstle_subscription_final_price').remove();
jQuery('.appstle_subscription_element').remove();
jQuery('.appstle_subscription_compare_price').remove();
var formattedPrice = getSelectedSellingPlanPrice();
var selectedDiscount = getSellingPlanDiscountPercentage();
var sellingPrice = jQuery(selectors.sellingPrice);
sellingPrice.css('text-decoration', '');
// sellingPrice.css('display', '');
sellingPrice.removeAttr('data-appstle-price-modified')
if (!selectors.sellingPrice || !selectedDiscount) {
sellingPrice.attr('data-appstle-price-modified', true)
return;
}
if (checkIfSellingPlanGroupIsSelected() && sellingPrice.length === 1) {
var selectedDiscountFormatDisplay = buildDiscountText(selectedDiscount);
if (selectedDiscountFormatDisplay) {
var subscriptionPercentageSavingElement =
jQuery(`
${selectedDiscountFormatDisplay}
`)
subscriptionPercentageSavingElement && subscriptionPercentageSavingElement.css('top', selectors.saleBadgeTop);
var clonedSellingPrice = sellingPrice.first().clone();
clonedSellingPrice.addClass('appstle_subscription_final_price')
clonedSellingPrice.html(formattedPrice);
sellingPrice.css('text-decoration', 'line-through');
(clonedSellingPrice.length > 0) && clonedSellingPrice.insertBefore(sellingPrice);
subscriptionPercentageSavingElement.insertAfter(sellingPrice);
}
}
sellingPrice.attr('data-appstle-price-modified', true)
}
if(jQuery(RSConfig.priceSelector).length) {
const targetNode = document.querySelector(RSConfig.priceSelector);
const config1 = { attributes: true, childList: true, subtree: true };
const callback = function(mutationsList, observer) {
if(!jQuery(RSConfig.priceSelector + '[data-appstle-price-modified="true"]').length) {
updateSellingPlanValueToFinalPrice()
}
};
const observer = new MutationObserver(callback);
if(targetNode && config1) {
observer.observe(targetNode, config1);
}
}
function getSellingPlanDiscountPercentage(isMultipleDiscount) {
var selectedSellingPlan = parseInt(getSelectedSellingPlanId());
if (!selectedSellingPlan) {
return null;
}
var selectedSellingPlanGroup;
product.selling_plan_groups.forEach(function (sellingPlanGroup) {
if (sellingPlanGroup.app_id === 'appstle') {
sellingPlanGroup.selling_plans.forEach(function (sellingPlan) {
var visible = isSellingPlanVisible(sellingPlan.id);
if (visible && sellingPlan.id === selectedSellingPlan) {
selectedSellingPlanGroup = sellingPlanGroup;
}
})
}
})
var selectedSellingPlan;
selectedSellingPlanGroup.selling_plans.forEach(function (selling_plan) {
if (selling_plan.id === selectedSellingPlan) {
selectedSellingPlan = selling_plan;
}
})
if (isMultipleDiscount && selectedSellingPlan?.price_adjustments?.length == 2) {
var multipleDiscount = [];
selectedSellingPlan?.price_adjustments?.forEach((discountValue) => {
if (discountValue?.value_type !== 'percentage') {
multipleDiscount.push(formatPriceWithQuantity(discountValue?.value))
} else {
multipleDiscount.push(discountValue?.value + '%');
}
})
return multipleDiscount;
}
var priceAdjustment = selectedSellingPlan?.price_adjustments[0];
if (priceAdjustment == null || priceAdjustment.value == null || priceAdjustment.value == 0) {
return null;
}
var selectedPriceAdjustment;
if (priceAdjustment?.value_type !== 'percentage') {
selectedPriceAdjustment = formatPriceWithQuantity(priceAdjustment?.value);
} else {
selectedPriceAdjustment = priceAdjustment?.value + '%';
}
return selectedPriceAdjustment
}
function updateWidgetElements() {
registerAndTriggerEventsForFormFields();
updateStateOfWidget();
}
function updateStateOfWidget() {
updateSelectValueToRadio();
updateOneTimePurchaseValueToRadio();
updateSellingPlanValueToFinalPrice();
}
function getCssAsString(cssObject) {
var cssObjectWithValidValues = {};
if(cssObject) {
Object.keys(cssObject).forEach(function (key) {
if (cssObject[key]) {
cssObjectWithValidValues[key] = cssObject[key]
}
})
return JSON.stringify(cssObjectWithValidValues)
.split('"').join('')
.split('{').join('')
.split('}').join('')
.split(',').join(';');
}
return "";
}
function updateHistoryState() {
if (!localWindowVariant) {
return;
}
var variantId = localWindowVariant.id;
if (!history.replaceState || !variantId) {
return;
}
var newurl =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname +
'?';
if (checkIfSellingPlanGroupIsSelected()) {
var selectedSellingPlanId = getSelectedSellingPlanId();
if (selectedSellingPlanId) {
newurl += 'selling_plan=' + selectedSellingPlanId + '&';
}
}
newurl += 'variant=' + variantId;
if (newurl !== location.href) {
window.history.replaceState({path: newurl}, '', newurl);
}
}
function updateWidgetUIBasedOnQueryParams() {
if (jQuery('#appstle_subscription_widget' + widgetId).length === 0) {
return;
}
var paramsObj = urlParamsToObject();
var formElement = jQuery('#appstle_subscription_widget' + widgetId).closest('form[action$="/cart/add"]')
if ((formElement.find('input[value=' + paramsObj["variant"] + ']').length > 0 || formElement.find('option[value=' + paramsObj["variant"] + ']').length > 0) && formElement.find('option[value=' + paramsObj["selling_plan"] + ']').length > 0) {
if (paramsObj['selling_plan']) {
var sellingPlanGroup = jQuery('#appstle_subscription_widget' + widgetId + ' #appstle_selling_plan_label_2' + widgetId);
sellingPlanGroup[0].checked = true;
var sellingPlanDropdown = null;
if (!RSConfig?.switchRadioButtonWidget) {
sellingPlanDropdown = jQuery('#appstle_subscription_widget' + widgetId + ' select#appstle_selling_plan' + widgetId)
} else {
sellingPlanDropdown = jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscribe_option')
}
if (!RSConfig?.switchRadioButtonWidget) {
sellingPlanDropdown.find('option').each(function (index, option) {
if (jQuery(option).attr('value') === paramsObj['selling_plan']) {
sellingPlanDropdown[0].selectedIndex = index;
}
});
} else {
sellingPlanDropdown.find('input[type=radio]').each(function (index, option) {
$(option).removeAttr("checked");
if (jQuery(option).attr('value') === paramsObj['selling_plan']) {
$(option).attr("checked", true)
}
});
}
sellingPlanGroup.change();
sellingPlanDropdown.change();
}
}
}
function accountPageStyle() {
var css = RSConfig.css;
jQuery(
``).appendTo(jQuery('head'));
}
function addStyle(widgetId) {
var css = RSConfig.css;
jQuery(
`
`
).appendTo(jQuery('head'));
}
jQuery('.appstle-hidden').removeClass('appstle-hidden');
}
function getBillingCycleText(billingCycle) {
var j = billingCycle % 10,
k = billingCycle % 100;
if (j == 1 && k != 11) {
return billingCycle + `st`;
}
if (j == 2 && k != 12) {
return billingCycle + `nd`;
}
if (j == 3 && k != 13) {
return billingCycle + `rd`;
}
return billingCycle + `th`;
}
function renderStandAloneWidget() {
var standaloneElements = Array.prototype.slice.call(jQuery(".appstle_stand_alone_selector"));
let index = -1
function attatchWidgetToStandAloneElement() {
if (standaloneElements?.length) {
let standAloneElement = standaloneElements.shift();
let product = $(standAloneElement).data("product-data");
index = index + 1;
if(!jQuery(standAloneElement).parents('form').find('.appstle_sub_widget').length) {
if (!product) {
fetch(location.origin + `/products/${jQuery(standAloneElement).data("product-handle")}.js`)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${ response.status }`);
}
return response.json();
})
.then((productHandleData) => {
jQuery(standAloneElement).attr("data-product-data", productHandleData);
renderWidget(productHandleData, $(standAloneElement), index);
attatchWidgetToStandAloneElement();
})
.catch((err) => {
console.log(err)
})
} else {
renderWidget(product, $(standAloneElement), index);
attatchWidgetToStandAloneElement();
}
} else {
attatchWidgetToStandAloneElement();
}
}
}
attatchWidgetToStandAloneElement()
}
function urlIsProductPage() {
// return null != decodeURIComponent(window.location.pathname).match(/\/products\/(([a-zA-Z0-9]|[\-\.\_\~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[\ud83c\ud83d\ud83e][\ud000-\udfff]){1,})\/?/)
return decodeURIComponent(window.location.pathname).includes('/products/');
}
jQuery(".appstle_sub_widget").remove();
// Init appstle render widget
if (appstleStandAloneSelectorExists()) {
renderStandAloneWidget();
} else {
renderWidget(undefined, undefined, 0);
}
// Code For Quick View Page (It will load on click of quickview page) It's compulsory to have a standalone script otherwise it won't work
jQuery(document).on("click", (`${window?.RS?.Config?.quickViewClickSelector}` || "a.grid-product__link"), function(){
if(jQuery(`${window?.RS?.Config?.quickViewClickSelector}` || "a.grid-product__link").length > 0)
{
var initiateQuickView = function() {
if (appstleStandAloneSelectorExists()) {
renderStandAloneWidget();
} else {
if(jQuery("#appstle_subscription_widget0")?.length == 0)
{
renderWidget(undefined, undefined, 0);
}
}
}
if(`${window?.RS?.Config?.quickViewModalPollingSelector}` || window?.Shopify?.shop == 'mahalia-coffee.myshopify.com')
{
var pollQuickView = function() {
if (jQuery(".quickshop.quickshop-visible.quickshop-loaded").length || jQuery(`${window?.RS?.Config?.quickViewModalPollingSelector}`).length) {
initiateQuickView()
} else {
setTimeout(()=> {
pollQuickView();
},200)
}
}
pollQuickView();
}
else {
setTimeout(()=> {
initiateQuickView()
}, 500)
}
}
})
function wrapPriceWithSpanTag(price) {
var textArea = document.createElement('textarea');
textArea.innerHTML = decodeURI(encodeURI(price));
return textArea.value;
}
function formatPrice(price) {
var configMoneyFormat = RS.Config.moneyFormat;
var moneyFormat = configMoneyFormat;
if (configMoneyFormat) {
moneyFormat = configMoneyFormat?.replace('{% raw %}', '')?.replace('{% endraw %}', '');
}
if (typeof price === 'string') {
price = price.replace('.', '');
}
var value = '';
var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
var shopifyMoneyFormat = typeof Shopify !== 'undefined' && Shopify.money_format && Shopify.money_format.length > 1 ? Shopify.money_format : '';
var themeMoneyFormat;
if (typeof theme !== 'undefined') {
if (theme.moneyFormat) {
themeMoneyFormat = theme.moneyFormat;
} else if (theme.money_format) {
themeMoneyFormat = theme.money_format;
} else if (theme.settings && theme.settings.moneyFormat) {
themeMoneyFormat = theme.settings.moneyFormat;
} else {
themeMoneyFormat = theme.strings ? theme.strings.moneyFormat : '';
}
} else {
themeMoneyFormat = '';
}
function htmlDecode(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
var formatString = '';
if (RS.Config?.formatMoneyOverride === 'true') {
formatString = RS.Config.moneyFormat;
} else {
formatString = window?.shopifyCurrencyFormat || window?.moneyFormat || window?.Currency?.money_format_no_currency || themeMoneyFormat || RSConfig?.shopMoneyFormat || moneyFormat || shopifyMoneyFormat || htmlDecode(RSConfig.shopMoneyFormatWithCurrencyFormat);
}
function formatWithDelimiters(number, precision, thousands, decimal) {
thousands = thousands || ',';
decimal = decimal || '.';
if (isNaN(number) || number === null) {
return 0;
}
number = (number / 100.0).toFixed(precision);
var parts = number.split('.');
var dollarsAmount = parts[0].replace(
/(\d)(?=(\d\d\d)+(?!\d))/g,
'$1' + thousands
);
var centsAmount = parts[1] ? decimal + parts[1] : '';
return dollarsAmount + centsAmount;
}
switch (formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(price, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(price, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(price, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(price, 0, '.', ',');
break;
case 'amount_no_decimals_with_space_separator':
value = formatWithDelimiters(price, 0, ' ');
break;
case 'amount_with_apostrophe_separator':
value = formatWithDelimiters(price, 2, "'");
break;
}
return wrapPriceWithSpanTag(formatString.replace(placeholderRegex, value));
}
// collection page price selector logic
function displaySubscriptionPrice() {
if (appstlePriceDisplaySelectorExists()) {
addFeaturePageCSS();
jQuery(".appstle_stand_alone_price_display_selector").each(function (index) {
let product = $(this).data("product-data");
let subscription_price = Number.MAX_SAFE_INTEGER;
let has_subscription_price = false
product?.variants?.forEach(variant => {
variant?.selling_plan_allocations?.forEach(allocation => {
if (allocation?.price_adjustments[0]?.price < subscription_price) {
subscription_price = allocation?.price_adjustments[0]?.price
has_subscription_price = true;
}
})
})
if (has_subscription_price) {
$(this).siblings(RSConfig?.landingPagePriceSelector || RS?.Config?.landingPagePriceSelector || "span.price, span.appstle_hide_old_price, .price").hide(); // hide old price from home page
$(this).html(wrapPriceWithSpanTag(buildSubscribeSaveSelector(subscription_price)));
}
$(this).show();
})
}
}
setTimeout(displaySubscriptionPrice, 30);
function addFeaturePageCSS() {
let cssFeaturedProduct = RSConfig?.css;
jQuery(`
`).appendTo(jQuery('head'));
}
function buildSubscribeSaveSelector(subscription_price) {
let subscribeSaveModel = {
subscriptionPrice: formatPrice(subscription_price)
};
return wrapPriceWithSpanTag(Mustache.render(RSConfig?.subscriptionPriceDisplayText, subscribeSaveModel));
}
function appstleStandAloneSelectorExists() {
return jQuery(".appstle_stand_alone_selector").length > 0
}
function appstlePriceDisplaySelectorExists() {
return jQuery(".appstle_stand_alone_price_display_selector").length > 0
}
function appstleSubscriptionCustomerPortalInit(selector) {
selector = selector || "#AppstleCustomerPortal";
if (document.querySelector(selector)) {
return jQuery.get(`/${RSConfig?.manageSubscriptionUrl}?renderType=html`)
.then(result => {
jQuery(selector).html(result);
document.dispatchEvent( new Event('AppstleSubscription:CustomerPortal:Embedded') );
window.dispatchEvent( new Event('AppstleSubscription:CustomerPortal:Embedded') );
})
.catch(error => console.log('error', error));
}
}
window.appstleSubscriptionCustomerPortalInit = appstleSubscriptionCustomerPortalInit;
appstleSubscriptionCustomerPortalInit();
document.dispatchEvent( new Event('AppstleSubscription:CustomerPortal:ReadyToEmbed') );
window.dispatchEvent( new Event('AppstleSubscription:CustomerPortal:ReadyToEmbed') );
function fetchAddJsSellingPlanInterCeptor() {
const { fetch: originalFetch } = window;
jQuery.ajaxSetup({
beforeSend: function (xhr,settings) {
console.log(xhr);
console.log(settings.data);
console.log(settings.url);
if(settings?.url === "/cart/add.js")
{
var sellingPlanID = $('.appstle_sub_widget input[name=selling_plan]:checked').val()
if(sellingPlanID)
{
settings.data = settings.data + `&selling_plan=${sellingPlanID}`
}
}
}
});
(function(send) {
XMLHttpRequest.prototype.send = function(data) {
if (this["_url"].indexOf("/cart/add.js") !== -1) {
var currentBodyObj = null;
var sellingPlan = $('.appstle_sub_widget input[name=selling_plan]:checked').val()
if (sellingPlan) {
try {
if (data.substr(0,1) === "{" && data.substr(-1) === "}") {
currentBodyObj = JSON.parse(data);
currentBodyObj.selling_plan = sellingPlan
send.call(this, JSON.stringify(currentBodyObj));
} else if (data.substr(0,1) !== "{" && data.substr(-1) !== "}" && data.indexOf("&") !== -1) {
send.call(this, data + `&selling_plan=${sellingPlan}`);
} else {
send.call(this, data);
}
} catch (e) {
send.call(this, data);
}
} else {
send.call(this, data);
}
} else {
send.call(this, data);
}
};
})(XMLHttpRequest.prototype.send);
window.fetch = function() {
var resource = arguments[0];
var config = arguments[1];
if(resource === "/cart/add.js")
{
var currentVariantId = urlParams.get('variant')
var newBodyArray = {}
var currentBodyArray = JSON.parse(config?.body);
if(getClassOf(currentBodyArray) === "Object" && getClassOf(currentBodyArray?.items) == "Array")
{
var sellingPlanVariantIndex = currentBodyArray?.items?.findIndex(data => data.id == currentVariantId);
if(sellingPlanVariantIndex >= 0)
{
var filteredVariant = currentBodyArray?.items?.filter(data => data.id != currentVariantId);
var sellingPlanIncludedVariant = JSON.parse(JSON.stringify(currentBodyArray?.items[sellingPlanVariantIndex]));
sellingPlanIncludedVariant[ "selling_plan"] = $('.appstle_sub_widget input[name=selling_plan]:checked').val();
filteredVariant.push(sellingPlanIncludedVariant);
newBodyArray.items = JSON.parse(JSON.stringify(filteredVariant));
config.body = JSON.stringify(newBodyArray);
return originalFetch.apply(this, arguments);
}
else {
return originalFetch.apply(this, arguments);
}
}
else if (getClassOf(currentBodyArray) === "Object") {
var currentBodyObj = JSON.parse(config?.body);
currentBodyObj.selling_plan = $('.appstle_sub_widget input[name=selling_plan]:checked').val()
config.body = JSON.stringify(currentBodyObj);
return originalFetch.apply(this, arguments);
}
}
else {
return originalFetch.apply(this, arguments);
}
};
}
function getClassOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
// standalone selector only one or product page and no cart page.
if((jQuery(".appstle_stand_alone_selector")?.length === 1 || urlIsProductPage() === true) && (window?.RS?.Config?.enableAddJSInterceptor === "true"))
{
fetchAddJsSellingPlanInterCeptor()
}
//============================ CART PAGE WIDGET START HERE =========================================================
if (window?.RS?.Config?.enableCartWidgetFeature !== "true") {
return;
}
$(function () {
//global variable
var cartRowSelector = window?.RS?.Config?.selectors.cartRowSelector;
var cartLineItemSelector = window?.RS?.Config?.selectors.cartLineItemSelector;
var appstleCustomSelector = "[data-appstle-selector]";
var cartLineItemPerQuantityPriceSelector = window?.RS?.Config?.selectors.cartLineItemPerQuantityPriceSelector;
var cartLineItemTotalPriceSelector = window?.RS?.Config?.selectors.cartLineItemTotalPriceSelector;
var lineItemSellingPlanNameSelector = window?.RS?.Config?.selectors.cartLineItemSellingPlanNameSelector;
var cartSubTotalSelector = window?.RS?.Config?.selectors.cartSubTotalSelector;
var cartLineItemPriceSelector = window?.RS?.Config?.selectors.cartLineItemPriceSelector;
var cartPageSellingPlan = [];
var totalSubscriptionPlanOnCartPage = 0;
var prevChangeResponse = "";
function appstleCartPageSubscription() {
if (!jQuery("#appstle_overlay").length) {
addLoader();
}
removeEventListners();
checkingSellingPlan();
}
function appstleListenForDOMChanges() {
var elementId = "";
if (jQuery("main").attr("id")) {
elementId = jQuery("main").attr("id");
} else {
jQuery("main").attr("id", "appstleCustomId");
elementId = "appstleCustomId";
}
const targetNode = document.getElementById(elementId);
const config = { attributes: true, childList: true, subtree: true };
const callback = function() {
if (!jQuery(cartLineItemSelector + ".appstleCartWidgetProcessed").length && jQuery(cartRowSelector).length) {
appstleCartPageSubscription();
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}
if (location.pathname === '/cart') {
var origOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
this.addEventListener('load', function() {
var url = this.responseURL;
console.log("origOpe.n -> url=" + url);
if (url.indexOf("cart/change.js") !== -1) {
if (prevChangeResponse !== JSON.stringify(this.response)) {
if (!jQuery("#appstle_overlay").length) {
addLoader();
}
setTimeout(appstleCartPageSubscription, 100);
prevChangeResponse = JSON.stringify(this.response);
}
}
});
origOpen.apply(this, arguments);
};
const originalFetch = window.fetch;
window.fetch = function() {
return new Promise((resolve, reject) => {
originalFetch.apply(this, arguments)
.then((response) => {
var url = response.url;
if (url.indexOf("cart/change.js") !== -1) {
if (!jQuery("#appstle_overlay").length) {
addLoader();
}
setTimeout(appstleCartPageSubscription, 100);
}
resolve(response);
})
.catch((error) => {
reject(response);
})
});
}
appstleCartPageSubscription();
addCartPageCSS();
appstleListenForDOMChanges();
}
function addLoader(text) {
if (!jQuery("#appstle_overlay").length) {
jQuery('body').append("");
}
}
function removeEventListners() {
jQuery('.appstle_subscription_cart_wrapper select').each((idx, item) => {
jQuery(item).off()
});
jQuery(".appstle_subscribe_selected input").each((idx, item) => {
jQuery(item).off()
});
jQuery(".appstle_subscribe_title").each((idx, item) => {
jQuery(item).off()
});
jQuery(".appstle_selected_frequency").each((idx, item) => {
jQuery(item).off()
});
}
function getPerkText(billingCycle, discount, discountType, freeTrail, isFirst, productName) {
if(RSConfig?.loyaltyPerkDescriptionText)
{
// NEED TO VERIFY
var selectedPerkText = {
discount: discount,
discountType: discountType,
formatDiscountedPrice: formatPrice(discount*100),
freeProductName: productName,
isDiscountTypePercentage: discountType === "PERCENTAGE",
isDiscountTypeShipping: discountType === "SHIPPING",
isDiscountTypeFreeProduct: discountType === "FREE_PRODUCT",
isFreeTrial: freeTrail,
isCartPage: true,
billingCycleBlock: `${billingCycle}`
}
return Mustache.render(RS.Config.loyaltyPerkDescriptionText, selectedPerkText);
}
if (freeTrail) {
return `Get ${discount} ${discountType}${discount > 1 ? 's' : ''} free trial.`
} else {
if (discountType === "PERCENTAGE") {
if (isFirst) {
return `Get ${discount + "% off"} after ${billingCycle} recurring order.`
} else {
return `Thereafter ${billingCycle} recurring order, get ${discount + "% off"}.`
}
} else if (discountType === "SHIPPING") {
if (isFirst) {
return `Get ${`shipping at ${formatPrice(discount*100)}`} after ${billingCycle} recurring order.`
} else {
return `Thereafter ${billingCycle} recurring order, get ${`shipping at ${formatPrice(discount*100)}`}.`
}
} else if (discountType === "FREE_PRODUCT") {
if (isFirst) {
return `Get aFREE PRODUCT (${productName}) after ${billingCycle} recurring order.`
} else {
return `Thereafter ${billingCycle} recurring order, get FREE PRODUCT (${productName}).`
}
} else if (discountType === "FIXED") {
if (isFirst) {
return `Get ${formatPrice(discount*100) + " off"} after ${billingCycle} recurring order.`
} else {
return `Thereafter ${billingCycle} recurring order, get ${formatPrice(discount*100) + " off"}.`
}
}
}
}
function createDiscountText(selectedSellingPlan, selectItem) {
var sellingPlanData = RSConfig?.sellingPlansJson?.find(function(item) {return item?.id.split("/").pop() === String(selectedSellingPlan)});
var text = '';
if (sellingPlanData?.freeTrialEnabled) {
text = getPerkText(0, sellingPlanData.freeTrialCount, sellingPlanData.freeTrialInterval, sellingPlanData?.freeTrialEnabled, true)
}
if (sellingPlanData?.afterCycle2) {
text = text + `${sellingPlanData?.freeTrialEnabled ? ' ' : ''}` + getPerkText(getBillingCycleText(sellingPlanData.afterCycle2), sellingPlanData.discountOffer2, sellingPlanData.discountType2, false, !sellingPlanData?.freeTrialEnabled)
}
if (sellingPlanData?.appstleCycles?.length && !sellingPlanData?.freeTrialEnabled) {
sellingPlanData?.appstleCycles?.forEach(function(cycle, index) {
var productName = ""
if (cycle?.discountType === "FREE_PRODUCT") {
productName = window?.products?.[cycle.freeProductHandle]?.title;
if (window?.products?.[cycle?.freeProductHandle]?.variants.length > 1) {
var variant = window?.products?.[cycle?.freeProductHandle]?.variants.filter(variant => variant?.id === parseInt(cycle?.freeVariantId));
var variantTitle = (variant.pop())?.title;
productName = productName + " - " + variantTitle;
}
}
if ((sellingPlanData?.afterCycle2) && index < 1) {
text = text + " " + getPerkText(getBillingCycleText(cycle.afterCycle), cycle.value, cycle.discountType, false, false, productName)
} else if (!sellingPlanData?.afterCycle2) {
if (index < 2) {
if (index == 0) {
text = getPerkText(getBillingCycleText(cycle.afterCycle), cycle.value, cycle.discountType, false, true, productName)
} else {
text = text + " " + getPerkText(getBillingCycleText(cycle.afterCycle), cycle.value, cycle.discountType, false, false, productName)
}
}
}
})
}
selectItem.find(".appstle_applied_discountText").html(text)
}
function getLoyaltyProductData(selectedSellingPlan, selectItem) {
var sellingPlanData = RSConfig?.sellingPlansJson?.find(function(item) {return item?.id.split("/").pop() === String(selectedSellingPlan)});
var productHandles = [];
if (sellingPlanData?.appstleCycles?.length) {
sellingPlanData?.appstleCycles?.forEach(function(cycle) {
productHandles.push(cycle?.freeProductHandle)
})
}
return getAllProductData(productHandles, selectedSellingPlan, selectItem)
}
function getAllProductData(productHandles, selectedSellingPlan, selectItem) {
var currentProductHandle = productHandles.shift();
if (!window?.["products"]?.[currentProductHandle]) {
return fetch(`/products/${currentProductHandle}.js`)
.then(res => {
if (res.ok) {
return res.json();
}
})
.then(res => {
if (!window["products"]) {
window["products"] = {};
}
window["products"][currentProductHandle] = res;
if(productHandles.length) {
return getAllProductData(productHandles, selectedSellingPlan, selectItem)
} else {
return createDiscountText(selectedSellingPlan, selectItem)
}
})
} else {
if(productHandles.length) {
return getAllProductData(productHandles, selectedSellingPlan, selectItem)
} else {
return createDiscountText(selectedSellingPlan, selectItem)
}
}
}
function checkingSellingPlan(sellingPlanIdToBeSet, removeSellingPlan) {
fetchCartData()
.then((cartResponse) => cartResponse.json())
.then((cartDataArray) => {
var hasSubscriptionPlan;
var handleURL = []
var productDataList = []
totalSubscriptionPlanOnCartPage = 0;
function updateCartLineItems() {
cartDataArray.items.forEach(function(cartItem, index) {
var productData = (productDataList.filter(prdData => prdData.handle === cartItem.handle)).pop();
var sellingPlanIsAvailable = checkIfSellingPlanIsAvailable(JSON.parse(JSON.stringify(productData)), cartItem?.variant_id);
var sellingPlanId = cartItem?.selling_plan_allocation?.selling_plan?.id;
if (sellingPlanIsAvailable) {
var appstle_cartpage_widget = jQuery(`
${window?.RS?.Config?.subscriptionOptionText}
{{deliveryText}}
{{appliedSellingPlanName}}
`);
populateSellingPlanDropdownOnCart(JSON.parse(JSON.stringify(productData)), appstle_cartpage_widget, sellingPlanId, JSON.parse(JSON.stringify(productData.variants.filter(item => item.id === cartItem.id).pop())))
jQuery(appstle_cartpage_widget).find('select').on('change', function (event) {
updateCartProductWithSelectedSellingPlan(cartDataArray?.items, cartItem, productData.id, event.target.value, false);
// window.location.reload();
});
jQuery(appstle_cartpage_widget).find('.appstle_subscribe_selected input').on('change', function (event) {
updateCartProductWithSelectedSellingPlan(cartDataArray?.items, cartItem, productData.id, jQuery(appstle_cartpage_widget).find('select').val(), true);
// window.location.reload();
});
jQuery(appstle_cartpage_widget).find(".appstle_subscribe_title, .appstle_selected_frequency").on("click", function() {
$(this).hide();
$(this).parents(".appstle_subscription_cart_wrapper").find('.appstle_radio_section').show();
})
var lineItemNew = jQuery(jQuery(cartRowSelector)[index]);
if (sellingPlanId) {
appstle_cartpage_widget.find(".appstle_subscribe_title").hide();
appstle_cartpage_widget.find(".appstle_subscribe_selected_wrapper").show();
lineItemNew.find(lineItemSellingPlanNameSelector).text(cartItem?.selling_plan_allocation?.selling_plan?.name);
lineItemNew.find(lineItemSellingPlanNameSelector).hide();
} else {
lineItemNew.find(lineItemSellingPlanNameSelector).hide();
}
lineItemNew.find(".appstle_subscription_cart_wrapper").remove();
if (lineItemNew.find(cartLineItemSelector).length === 1) {
appstle_cartpage_widget.insertBefore(lineItemNew.find(cartLineItemSelector));
} else {
appstle_cartpage_widget.insertBefore(lineItemNew.find(appstleCustomSelector));
}
lineItemNew.find(cartLineItemPerQuantityPriceSelector).html(formatPrice(cartItem.final_price))
lineItemNew.find(cartLineItemTotalPriceSelector).html(formatPrice(cartItem.final_line_price))
if (sellingPlanId && cartItem.selling_plan_allocation.compare_at_price) {
lineItemNew.find(cartLineItemPriceSelector).html("");
var priceHtml = `${formatPrice(cartItem.final_price)}${formatPrice(cartItem.selling_plan_allocation.compare_at_price)}`
lineItemNew.find(cartLineItemPriceSelector).html(priceHtml)
}
}
jQuery(jQuery(cartRowSelector)[index]).find(cartLineItemSelector).addClass("appstleCartWidgetProcessed");
});
jQuery(cartSubTotalSelector).html(formatPrice(cartDataArray?.total_price))
jQuery("#appstle_overlay").remove();
}
function getProductData() {
if (handleURL.length) {
fetch(`/products/${handleURL.shift()}.js`)
.then(function(prdData) {
return prdData.json();
})
.then(function(prdData) {
productDataList.push(prdData);
getProductData();
})
} else {
updateCartLineItems();
document.dispatchEvent(new Event('AppstleSubscription:CartWidget:Updated'));
window.dispatchEvent(new Event('AppstleSubscription:CartWidget:Updated'));
}
}
if (cartDataArray?.items?.length > 0) {
if (cartDataArray?.items?.length === jQuery(cartRowSelector).length) {
cartDataArray?.items.forEach(function(item) {
if (handleURL.indexOf(item?.handle) === -1) {
handleURL.push(item?.handle)
}
})
} else {
if(window?.RS?.Config?.selectors?.cartRowSelector && cartRowSelector?.length) {
location.reload();
}
}
getProductData();
} else {
jQuery("#appstle_overlay").remove();
}
})
}
function updateCartProductWithSelectedSellingPlan(items, lineItem, productId, sellingPlanId, removeSellingPlan) {
if (!sellingPlanId) {
return;
}
if (sellingPlanId === "appstle_unsubscribe") {
removeSellingPlan = true;
}
addLoader();
var config = {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'id': lineItem?.key,
'quantity': lineItem?.quantity || 1,
'selling_plan': removeSellingPlan ? "" : sellingPlanId
})
}
// set quanity is 0
fetch("/cart/change.js", config)
.then((res) => res.json())
.then(data => {
setTimeout(function() {
appstleCartPageSubscription();
}, 200)
})
.catch((err) => console.log(err))
}
function isSellingPlanVisible(sellingPlanId) {
var customerId = __st.cid;
var userTags = RSConfig.customer_tags || [];
var isVisible = true;
if (!customerId && RSConfig.memberOnlySellingPlansJson && RSConfig.memberOnlySellingPlansJson[sellingPlanId]) {
isVisible = false;
}
if (customerId && RSConfig.nonMemberOnlySellingPlansJson && RSConfig.nonMemberOnlySellingPlansJson[sellingPlanId]) {
isVisible = false;
}
if (isVisible && customerId && RSConfig.memberOnlySellingPlansJson && RSConfig.memberOnlySellingPlansJson[sellingPlanId]) {
if (RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberInclusiveTags && RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberInclusiveTags.trim()) {
var sellingPlanTags = RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberInclusiveTags.split(",");
var tagFound = compareCustomerTags(userTags, sellingPlanTags);
isVisible = (tagFound.length > 0);
}
if (RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberExclusiveTags && RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberExclusiveTags.trim()) {
var sellingPlanExclusiveTags = RSConfig.memberOnlySellingPlansJson[sellingPlanId].memberExclusiveTags.split(",");
var exclusiveTagFound = compareCustomerTags(userTags, sellingPlanExclusiveTags);
isVisible = !(exclusiveTagFound.length > 0);
}
}
return isVisible;
}
function buildSellingPlantText(sellingPlan) {
var sellingPlanModel = sellingPlan.totalPrice == sellingPlan.formattedPrice ?
{
sellingPlanName: sellingPlan.name,
sellingPlanPrice: `${sellingPlan.formattedPrice}`,
secondSellingPlanPrice: `${sellingPlan.secondFormattedPrice}`,
}
: {
sellingPlanName: sellingPlan.name,
totalPrice: `${sellingPlan?.totalPrice}`,
sellingPlanPrice: `${sellingPlan.formattedPrice}`,
secondSellingPlanPrice: `${sellingPlan.secondFormattedPrice}`
};
var sellingPlanDisplayText = Mustache.render(RS.Config.sellingPlanTitleText, sellingPlanModel);
return wrapPriceWithSpanTag(sellingPlanDisplayText);
}
function populateSellingPlanDropdownOnCart(product, selectItem, selectedSellingPlan, variant) {
var sellingPlanVariants = [];
jQuery.each(product.selling_plan_groups, function (index, sellingPlanGroup) {
if (sellingPlanGroup.app_id === 'appstle') {
jQuery.each(sellingPlanGroup.selling_plans, function (subIndex, sellingPlan) {
var visible = isSellingPlanVisible(sellingPlan.id);
if (visible) {
var sellingPlanAllocation = variant.selling_plan_allocations.find(function (plan) {
return plan.selling_plan_id === sellingPlan.id;
});
if (!sellingPlanAllocation) {
return
}
var price = sellingPlanAllocation.per_delivery_price;
var totalPrice = formatPrice(sellingPlanAllocation?.price);
var formattedPrice = formatPrice(price);
var secondPrice = null;
var secondFormattedPrice = null;
if (sellingPlanAllocation
&& sellingPlanAllocation.price_adjustments
&& sellingPlanAllocation.price_adjustments.length === 2) {
secondPrice = sellingPlanAllocation.price_adjustments[1].price;
secondFormattedPrice = formatPrice(secondPrice);
} else {
secondPrice = price;
secondFormattedPrice = formattedPrice;
}
var price_adjustments = sellingPlan.price_adjustments.shift();
sellingPlanVariants.push({
"name": sellingPlan.name,
"id": sellingPlan.id,
"formattedPrice": formattedPrice,
"price": price,
"totalPrice": totalPrice,
"secondPrice": secondPrice,
"secondFormattedPrice": secondFormattedPrice,
"discount": price_adjustments ? (price_adjustments.value_type === 'percentage' ? `${price_adjustments.value}%` : formatPrice(price_adjustments.value)) : '',
"deliveryText": sellingPlan.options[0].name
});
}
});
}
});
if (sellingPlanVariants.length > 0) {
sellingPlanVariants.sort(function (sellingPlanA, sellingPlanB) {
return sellingPlanA.price - sellingPlanB.price;
})
jQuery('', {
html: "Select Delivery Option",
value: ""
}).appendTo(selectItem.find('select'));
jQuery(sellingPlanVariants).each(function (index, sellingPlan) {
var sellingPlanDisplayText = buildSellingPlantText(sellingPlan);
jQuery('', {
value: sellingPlan.id,
html: sellingPlanDisplayText,
selected: selectedSellingPlan === sellingPlan?.id
}).appendTo(selectItem.find('select'));
});
if (!product?.requires_selling_plan) {
jQuery('', {
value: "appstle_unsubscribe",
html: "Unsubscribe"
}).appendTo(selectItem.find('select'));
}
var selectedSellingPlanItem = sellingPlanVariants.filter((item) => item?.id === selectedSellingPlan).pop()
if (selectedSellingPlanItem) {
var appstle_deliveryText = selectItem.find(".appstle_selected_frequency .appstle_deliveryText").text().split("{{deliveryText}}").join(selectedSellingPlanItem.deliveryText || "")
selectItem.find(".appstle_deliveryText").html(appstle_deliveryText);
var appstle_applied_sellingPlanName = selectItem.find(".appstle_selected_frequency .appstle_applied_sellingPlanName").text().split("{{appliedSellingPlanName}}").join(selectedSellingPlanItem.name)
selectItem.find(".appstle_applied_sellingPlanName").html(appstle_applied_sellingPlanName);
var appstle_subscribe_selected_text = selectItem.find(".appstle_subscribe_selected_text").text().split("{{{discountValue}}}").join(selectedSellingPlanItem.discount)
selectItem.find(".appstle_subscribe_selected_text").html(appstle_subscribe_selected_text);
getLoyaltyProductData(selectedSellingPlanItem.id, selectItem)
} else {
var appstle_highest_discount_text = selectItem.find(".appstle_highest_discount").text().split("{{{discountValue}}}").join(sellingPlanVariants[0].discount)
selectItem.find(".appstle_highest_discount").html(appstle_highest_discount_text);
}
}
return sellingPlanVariants;
}
function checkIfSellingPlanIsAvailable(productData, variantId) {
var variant = (productData?.variants.filter(function(item) {
return item.id === variantId
})).pop()
if (variant && variant?.selling_plan_allocations && variant?.selling_plan_allocations.length) {
return true;
}
return false;
}
function fetchCartData() {
return fetch('/cart.js');
}
function addCartPageCSS() {
var cssFeaturedProduct = RSConfig?.css;
jQuery(`
`).appendTo(jQuery('head'));
}
})
//============================ CART PAGE WIDGET END HERE =========================================================
})();
});
if (Shopify && Shopify.Checkout && Shopify.Checkout.hasSellingPlan && RS?.Config?.showCheckoutSubscriptionBtn) {
var destination = "/" + RS.Config.manageSubscriptionUrl;
var message = RS.Config.orderStatusManageSubscriptionDescription || 'Continue to your account to view and manage your subscriptions.';
if (Shopify.checkout && Shopify.checkout.customer_id) {
console.log("cusomterId=" + Shopify.checkout.customer_id);
// var settings = {
// "async": true,
// "crossDomain": true,
// "url": location.origin + "/apps/subscriptions?action=customer_payment_token&customer_id=" + Shopify.checkout.customer_id,
// "method": "GET",
// "headers": {
// "accept": "*/*",
// "cache-control": "no-cache",
// }
// }
fetch(location.origin + "/apps/subscriptions?action=customer_payment_token&customer_id=" + Shopify.checkout.customer_id).then(function (response) {
return response.json()
}).then(function(response) {
destination = destination + "?token=" + response.token;
Shopify.Checkout.OrderStatus.addContentBox(
'' + (RS.Config.orderStatusManageSubscriptionTitle || 'Subscription') + '
' + (RS.Config.orderStatusManageSubscriptionButtonText || 'Manage your subscription') + ''
);
})
} else {
Shopify.Checkout.OrderStatus.addContentBox(
'' + (RS.Config.orderStatusManageSubscriptionTitle || 'Subscription') + '
' + (RS.Config.orderStatusManageSubscriptionButtonText || 'Manage your subscription') + ''
);
}
}
};
appstleInit();