(function () {
var head = document.getElementsByTagName('head')[0];
var startingTime = new Date().getTime();
if (typeof jQuery == 'undefined' && !AM?.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) {
callback(jQuery);
} else {
window.setTimeout(function () {
checkReady(callback);
}, 20);
}
};
AM.Config = Object.assign(AM.Config, "undefined" != typeof _AMConfig && null !== _AMConfig ? _AMConfig : {})
window.AMConfig = AM.Config;
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) {
AM.Config = Object.assign(AM.Config, "undefined" != typeof _AMConfig && null !== _AMConfig ? _AMConfig : {})
window.AMConfig = AM.Config;
var product = AMConfig.product;
if (standAloneProduct) {
AMConfig.product = product = standAloneProduct;
}
processProductVariants(product);
var localVariantsByTitle = AMConfig.variantsByTitle;
var localVariantsById = AMConfig.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);
}
AMConfig.variantsByTitle = _variantsByTitle;
AMConfig.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
}
var customerTagMatchedForCurrentUrl = "";
var customerTagMatchedForHtmlElement = "";
var unMatchedRules = [];
var matchedRules = [];
var unMatchedDiscountRules = [];
var matchedDiscountRules = [];
var restrictPage = false;
var customerTags = AMConfig['customer_tags'] || [];
customerTags = customerTags.map(item => item.toLowerCase())
var rulesByCustomerTag = JSON.parse(AMConfig.rulesByCustomerTag)
var allCustomerTags = (Object.keys(rulesByCustomerTag));
var skipRules = false;
var matchCustomerTag = function(customerTags, customerTag, rule) {
if (customerTags.indexOf(customerTag) === -1) {
unMatchedRules.push({selector: rule.selector, message: rule?.message || ""})
} else {
matchedRules.push(rule.selector)
}
}
var matchDiscountWithCustomerTag = function(customerTags, customerTag, rule) {
if (customerTags.indexOf(customerTag) !== -1) {
matchedDiscountRules.push({discountUrl: rule.discountUrl, discountMessage: rule?.discountMessage || "", discountCodeDetails: rule?.discountCodeDetails || "", membershipName: rule?.membershipName || ""})
}
}
if (AMConfig?.product) {
jQuery.each(AMConfig.product?.selling_plan_groups, function (index, sellingPlanGroup) {
if (sellingPlanGroup.app_id === 'appstle-memberships') {
if (!skipRules) {
skipRules = true;
}
}
})
}
if (AM.Config["enableMessagingForNonMembers"] === "true") { // Show banner flag when not logged in
if (!(__st?.cid)) {
if (!sessionStorage['appstle_membership_not_logged_in_banner_closed']) {
addNotLoggedInBanner();
}
}
}
function addNotLoggedInBanner() {
jQuery(".appstle-not-logged-in-banner").remove();
if (AM.Config["nonMemberMessaging"]) {
jQuery(`
`));
}
wrapper.append(field['type'] !== 'checkbox' ? jQuery(`
`): ``);
if (field['type'] === 'text') {
wrapper.append(jQuery(`
`))
} else if (field['type'] === 'checkbox') {
wrapper.append(jQuery(`
`))
} else if (field['type'] === 'select') {
var selectField = jQuery(`
`);
field['option'].split(',').forEach(function(option) {
selectField.append(jQuery(`
`))
})
wrapper.append(selectField)
} else if (field['type'] === 'radio') {
field['option'].split(',').forEach(function(option, index) {
wrapper.append(jQuery(`
`))
})
}
}
})
wrapper.insertAfter('#appstle_membership_widget' + widgetId + ' .appstle_membership_wrapper')
}
}
}
function changeHandlerForSelect() {
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_membership_wrapper select').on('change', function (event) {
updateStateOfWidget();
updateFormFields(getSelectedSellingPlanId())
});
updateFormFields(getSelectedSellingPlanId());
}
function triggerChangeEvent(selector) {
jQuery(selector).change();
}
function registerAndTriggerEventsForFormFields() {
changeEventHandlerForRadio();
changeHandlerForSelect();
}
function unbindEventListeners() {
jQuery('.appstle_membership_wrapper input[type=radio], .appstle_membership_wrapper select').off('change')
}
function getSelectedSellingPlanPrice() {
var selectedSellingPlan = getSelectedSellingPlanId();
if (selectedSellingPlan) {
var selectedSellingPlanAllocation = getSellingPlanAllocation(localWindowVariant.id, parseInt(selectedSellingPlan));
return formatPrice(selectedSellingPlanAllocation.per_delivery_price);
} else {
return null;
}
}
function getSelectedSellingPlanId() {
var value = null;
try {
value = jQuery("#appstle_membership_widget" + widgetId).find('.appstle_membership_wrapper_option.appstle_include_dropdown select')[0].value;
} catch (e) {
}
return value;
}
function updateSelectValueToRadio() {
var selectedSellingPlan = getSelectedSellingPlanId();
if (selectedSellingPlan) {
var variantId = jQuery('#appstle_membership_widget' + widgetId).closest('form[action="/cart/add"]').find('[name=id]')[0] == undefined ? localWindowVariant.id : jQuery('#appstle_membership_widget' + widgetId).closest('form[action="/cart/add"]').find('[name=id]')[0].value;
var selectedSellingPlanAllocation = getSellingPlanAllocation(variantId, parseInt(selectedSellingPlan));
var formattedSelectedSellingPlanPrice = formatPrice(selectedSellingPlanAllocation.per_delivery_price);
jQuery('#appstle_membership_widget' + widgetId + ' #appstle_selling_plan_label_2' + widgetId).attr('value', selectedSellingPlan);
var isPrepaidPlan = selectedSellingPlanAllocation.per_delivery_price !== selectedSellingPlanAllocation.price;
var selectedPriceText = buildSelectedPriceText(
formattedSelectedSellingPlanPrice,
isPrepaidPlan,
formatPrice(selectedSellingPlanAllocation.price));
let selectedDiscountSub = getSellingPlanDiscountPercentage();
let multipleDiscount = getSellingPlanDiscountPercentage(true);
var toolTipPrepaidText = buildSelectedTooltipPrePaidText(formattedSelectedSellingPlanPrice, formatPrice(selectedSellingPlanAllocation.price));
var toolTipDiscountText = buildSelectedTooltipDiscountText(selectedSellingPlanAllocation, multipleDiscount);
var tooltipText = buildTooltipDetailsText(toolTipPrepaidText, isPrepaidPlan, toolTipDiscountText);
var subscribesaveText = buildSubscriptionOptionText(isPrepaidPlan, selectedDiscountSub);
var prepaidPerDeliveryPriceText = buildPrepaidPerDeliveryPriceText(formattedSelectedSellingPlanPrice);
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_prepaid_description').remove();
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_membership_wrapper_option.appstle_include_dropdown .appstle_membership_amount').html(selectedPriceText);
if (isPrepaidPlan) {
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_membership_amount_wrapper').append(
`
${prepaidPerDeliveryPriceText || ( formatPrice(selectedSellingPlanAllocation.price) + '/delivery')}
`
)
}
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_membership_wrapper_option.appstle_include_dropdown .appstle_membership_radio_wrapper .appstle_subscribe_save_text').html(subscribesaveText);
if (checkIfSellingPlanGroupIsSelected() && tooltipText && tooltipText.trim()) {
if (AM.Config.showStaticTooltip) {
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_tooltip_wrapper_static').html(tooltipText);
} else {
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_tooltip_wrapper .appstle_tooltip .appstle_tooltip_content').html(tooltipText);
}
} else {
if (AM.Config.showStaticTooltip && AM.Config.tooltipDesctiption && AM.Config.tooltipDesctiption.trim()) {
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_tooltip_wrapper_static').html(AM.Config.tooltipDesctiption);
} else {
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_tooltip_wrapper .appstle_tooltip .appstle_tooltip_content').html(AM.Config.tooltipDesctiption);
}
}
}
}
function checkIfSellingPlanGroupIsSelected() {
var selected = false;
try {
selected = jQuery('#appstle_membership_widget' + widgetId).find('.appstle_membership_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(AM.Config.selectedDiscountFormat, selectedDiscountModel);
// selected discount customization end
return selectedDiscountFormatDisplay;
}
function updateSellingPlanValueToFinalPrice() {
var selectorsObject = {
regular: {
sellingPrice: AMConfig.priceSelector,
saleBadgeTop: AMConfig.badgeTop
}
}
var selectors = selectorsObject.regular;
jQuery('.appstle_membership_final_price').remove();
jQuery('.appstle_membership_element').remove();
jQuery('.appstle_membership_compare_price').remove();
var formattedPrice = getSelectedSellingPlanPrice();
var selectedDiscount = getSellingPlanDiscountPercentage();
var sellingPrice = jQuery(selectors.sellingPrice);
sellingPrice.css('text-decoration', '');
// sellingPrice.css('display', '');
if (!selectors.sellingPrice || !selectedDiscount) {
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_membership_final_price')
clonedSellingPrice.text(formattedPrice);
sellingPrice.css('text-decoration', 'line-through');
(clonedSellingPrice.length > 0) && clonedSellingPrice.insertBefore(sellingPrice);
subscriptionPercentageSavingElement.insertAfter(sellingPrice);
}
}
}
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-memberships') {
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(formatPrice(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 = formatPrice(priceAdjustment?.value);
} else {
selectedPriceAdjustment = priceAdjustment?.value + '%';
}
return selectedPriceAdjustment
}
function updateWidgetElements() {
registerAndTriggerEventsForFormFields();
updateStateOfWidget();
}
function updateStateOfWidget() {
updateSelectValueToRadio();
updateSellingPlanValueToFinalPrice();
}
function getCssAsString(cssObject) {
var cssObjectWithValidValues = {};
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(';');
}
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_membership_widget' + widgetId).length === 0) {
return;
}
var paramsObj = urlParamsToObject();
var formElement = jQuery('#appstle_membership_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_membership_widget' + widgetId + ' #appstle_selling_plan_label_2' + widgetId);
var sellingPlanDropdown = jQuery('#appstle_membership_widget' + widgetId + ' select#appstle_selling_plan' + widgetId)
sellingPlanGroup[0].checked = true;
sellingPlanDropdown.find('option').each(function (index, option) {
if (jQuery(option).attr('value') === paramsObj['selling_plan']) {
sellingPlanDropdown[0].selectedIndex = index;
}
});
sellingPlanGroup.change();
sellingPlanDropdown.change();
}
}
}
if (Shopify && Shopify.Checkout && Shopify.Checkout.hasSellingPlan && AM?.Config?.showCheckoutSubscriptionBtn) {
var destination = 'https://janeausten.co.uk/pages/membership-dashboard';
var message = AM.Config.orderStatusManageSubscriptionDescription || 'Continue to your account to view and manage your memberships.';
if (Shopify.checkout && Shopify.checkout.customer_id) {
console.log("cusomterId=" + Shopify.checkout.customer_id);
var settings = {
"async": true,
"crossDomain": true,
"url": "https://membership-admin.appstle.com/api/external/v2/customer-payments/token/" + Shopify.checkout.customer_id + "?api_key=" + window?.AMConfig?.api_key,
"method": "GET",
"headers": {
"accept": "*/*",
"cache-control": "no-cache",
}
}
jQuery.ajax(settings).done(function (response) {
destination = 'https://janeausten.co.uk/pages/membership-dashboard';
Shopify.Checkout.OrderStatus.addContentBox(
'
' + (AM.Config.orderStatusManageSubscriptionTitle || 'Membership') + '
' + (AM.Config.orderStatusManageSubscriptionButtonText || 'Manage your membership') + ''
);
});
} else {
Shopify.Checkout.OrderStatus.addContentBox(
'
' + (AM.Config.orderStatusManageSubscriptionTitle || 'Membership') + '
' + (AM.Config.orderStatusManageSubscriptionButtonText || 'Manage your membership') + ''
);
}
}
function accountPageStyle() {
var css = AMConfig.css;
jQuery(
``).appendTo(jQuery('head'));
}
function addStyle(widgetId) {
var css = AMConfig.css;
jQuery(
`
`
).appendTo(jQuery('head'));
}
}
function renderStandAloneWidget() {
var standaloneElements = Array.prototype.slice.call(jQuery(".appstle_membership_stand_alone_selector:not(.appstle_standalone_element_processed)"));
var index = -1
function attatchWidgetToStandAloneElement() {
if (standaloneElements?.length) {
let standAloneElement = standaloneElements.shift();
let product = $(standAloneElement).data("product-data");
if (product) {
product.collections = $(standAloneElement).data("product-collection-data");
}
index = index + 1;
jQuery(standAloneElement).addClass("appstle_standalone_element_processed");
if(!jQuery(standAloneElement).parents('form').find('.appstle_member_widget').length) {
if (!product) {
jQuery.getJSON(location.origin + `/products/${jQuery(standAloneElement).data("product-handle")}.js`)
.then((productHandleData) => {
jQuery(standAloneElement).attr("data-product-data", JSON.stringify(productHandleData));
renderWidget(JSON.parse(JSON.stringify(productHandleData)), $(standAloneElement), index);
attatchWidgetToStandAloneElement();
})
} else {
renderWidget(product, $(standAloneElement), index);
attatchWidgetToStandAloneElement();
}
} else {
attatchWidgetToStandAloneElement();
}
} else {
setTimeout(() => {
jQuery(".appstle-hidden").removeClass("appstle-hidden");
}, 100)
}
}
attatchWidgetToStandAloneElement()
}
jQuery(".appstle_member_widget").remove();
// Init appstle render widget
if (appstleStandAloneSelectorExists()) {
renderStandAloneWidget();
} else {
renderWidget(undefined, undefined, 0);
setTimeout(() => {
jQuery(".appstle-hidden").removeClass("appstle-hidden");
}, 100)
}
function appstleListenForDOMChanges() {
try {
var id = "";
id = jQuery("body").attr("id")
if (!id) {
id = "appstleCustomBodyMarker";
jQuery("body").attr("id", id)
}
const targetNode = document.getElementById(id);
const config = { attributes: true, childList: true, subtree: true };
const callback = function() {
renderStandAloneWidget()
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
} catch (e) {
console.log("Exception happened in mutation Observer", e)
}
}
appstleListenForDOMChanges();
// 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(`${window?.AM?.Config?.quickViewClickSelector}`).on("click",function(){
if(jQuery(`${window?.AM?.Config?.quickViewClickSelector}`).length > 0)
{
var initiateQuickView = function() {
if (appstleStandAloneSelectorExists()) {
renderStandAloneWidget();
} else {
if(jQuery("#appstle_membership_widget0")?.length == 0)
{
renderWidget(undefined, undefined, 0);
}
}
}
if(window?.AM?.Config?.quickViewModalPollingSelector)
{
var pollQuickView = function() {
if (jQuery(".quickshop.quickshop-visible.quickshop-loaded").length || jQuery(`${window?.AM?.Config?.quickViewModalPollingSelector}`).length) {
initiateQuickView()
} else {
setTimeout(()=> {
pollQuickView();
},200)
}
}
pollQuickView();
}
else {
setTimeout(()=> {
initiateQuickView()
}, 500)
}
}
})
function formatPrice(price) {
var moneyFormat = AM.Config.moneyFormat;
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 = '';
}
var formatString = window?.shopifyCurrencyFormat || window?.moneyFormat || window?.Currency?.money_format_no_currency || themeMoneyFormat || moneyFormat || shopifyMoneyFormat;
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;
}
var spanElement = document.createElement('span');
spanElement.innerHTML = formatString.replace(placeholderRegex, value);
return spanElement.textContent || spanElement.innerText;
}
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("span.price, span.appstle_hide_old_price").hide(); // hide old price from home page
$(this).html(buildSubscribeSaveSelector(subscription_price));
}
$(this).show();
})
}
function attachMutationObserver(selector, callback) {
const targetNode = document.querySelector(selector);
const config = { attributes: true, childList: true, subtree: true };
const observer = new MutationObserver(callback);
if (targetNode && config) {
observer.observe(targetNode, config);
}
}
function addFeaturePageCSS() {
let cssFeaturedProduct = AMConfig?.css;
jQuery(`
`).appendTo(jQuery('head'));
}
function buildSubscribeSaveSelector(subscription_price) {
let subscribeSaveModel = {
subscriptionPrice: formatPrice(subscription_price)
};
return Mustache.render(AMConfig?.subscriptionPriceDisplayText, subscribeSaveModel);
}
function appstleStandAloneSelectorExists() {
return jQuery(".appstle_membership_stand_alone_selector").length > 0
}
function appstlePriceDisplaySelectorExists() {
return jQuery(".appstle_stand_alone_price_display_selector").length > 0
}
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 = $('form 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"] === "/cart/add.js") {
var currentBodyObj = null;
var sellingPlan = $('form 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?.findIndex(data => data.id == currentVariantId);
if(sellingPlanVariantIndex >= 0)
{
var filteredVariant = currentBodyArray.filter(data => data.id != currentVariantId);
var sellingPlanIncludedVariant = JSON.parse(JSON.stringify(currentBodyArray[sellingPlanVariantIndex]));
sellingPlanIncludedVariant[ "selling_plan"] = $('form 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 = $('form 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);
}
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/');
}
// standalone selector only one or product page and no cart page.
if((jQuery(".appstle_membership_stand_alone_selector")?.length === 1 || urlIsProductPage() === true) && window?.AM?.Config?.enableSellingPlanInterceptor === true) {
fetchAddJsSellingPlanInterCeptor()
}
})();
});
})();