var appstleMembershipWidgetInit = 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
}
function restrict() {
var customerTagMatchedForCurrentUrl = "";
var customerTagMatchedForHtmlElement = "";
var unMatchedRules = [];
var matchedRules = [];
var allMatchedDiscountRules = [];
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 {
if (rule?.allowDuringTrial === false || rule?.allowDuringDunning === false) {
if (rule?.allowDuringTrial === false && AMConfig?.customerTrialTags.indexOf(customerTag) !== -1) {
unMatchedRules.push({selector: rule.selector, message: rule?.message || ""})
} else if (rule?.allowDuringDunning === false && AMConfig?.customerDunningTags.indexOf(customerTag) !== -1) {
unMatchedRules.push({selector: rule.selector, message: rule?.message || ""})
} else {
matchedRules.push(rule.selector);
}
} else {
matchedRules.push(rule.selector)
}
}
}
var matchDiscountWithCustomerTag = function(customerTags, customerTag, rule) {
if (rule?.applyDiscountAutomatically !== false) {
if (customerTags.indexOf(customerTag) !== -1) {
if (rule?.allowDuringTrial === false || rule?.allowDuringDunning === false) {
if (rule?.allowDuringTrial === false && AMConfig?.customerTrialTags.indexOf(customerTag) !== -1) {
} else if (rule?.allowDuringDunning === false && AMConfig?.customerDunningTags.indexOf(customerTag) !== -1) {
} else {
matchedDiscountRules.push({discountUrl: rule.discountUrl, discountMessage: rule?.discountMessage || "", discountCodeDetails: rule?.discountCodeDetails || "", membershipName: rule?.membershipName || ""})
}
} else {
matchedDiscountRules.push({discountUrl: rule.discountUrl, discountMessage: rule?.discountMessage || "", discountCodeDetails: rule?.discountCodeDetails || "", membershipName: rule?.membershipName || ""})
}
}
allMatchedDiscountRules.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(`
${sellingPlanVariants[0]?.description?.replace(
'{{sellingPlanName}}',
sellingPlanVariants[0]?.name
)}
`
).appendTo(purchaseOptions.find('.appstle_subscribe_option'));
} else {
if (sellingPlanVariants[0]?.description) {
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(`
`))
})
} else if (field['type'] === 'date') {
wrapper.append(jQuery(`
`
))
getJqueryUIFromCDN();
attatchDatePicker(field['config'], field['enabledDays'], field['nextOrderMinimumThreshold']);
}
}
});
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_form_field_input_alternate').on('change', function(event) {
// jQuery('.appstle_form_field_input').attr('min', getLocaleDate());
if (event.target.value) {
var utcDate = event.target.value + "T" + new Date().toISOString().split("T")[1];
jQuery('.appstle_form_field_input_iso').attr('value', new Date(utcDate).toISOString().split('.')[0] + "Z")
jQuery('.appstle_form_field_input_iso').val(new Date(utcDate).toISOString().split('.')[0] + "Z")
}
});
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_form_field_input').parents('.as-date-input-wrapper').find('input').each((index, item) => {
$(item).trigger('change');
});
}
}
}
function getJqueryUIFromCDN() {
// if (!window.jQuery) {
// window.jQuery = window.appstle_jQuery;
// window["$"] = window.appstle_jQuery;
// }
if (!jQuery('.jqueryUIFetched').length) {
if (typeof window['jQuery']?.datepicker == 'undefined') {
var jQueryUI = document.createElement('script');
jQueryUI.src = 'https://code.jquery.com/ui/1.13.2/jquery-ui.min.js';
jQueryUI.type = 'text/javascript';
head.appendChild(jQueryUI);
var jQueryUICss = document.createElement('link');
jQueryUICss.href = 'https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css';
jQueryUICss.rel = 'stylesheet';
head.appendChild(jQueryUICss);
// getJqueryi18()
jQuery('html').addClass('jqueryUIFetched');
}
}
}
function attatchDatePicker(config, enabledDays, nextOrderMinimumThreshold) {
var currentDate = new Date();
var firstEligibleDateFlag = false;
var days = [];
var daysRequired = 7
if (nextOrderMinimumThreshold && parseInt(nextOrderMinimumThreshold)) {
nextOrderMinimumThreshold = parseInt(nextOrderMinimumThreshold);
} else {
nextOrderMinimumThreshold = 0;
}
for (var i = 0; i <= daysRequired; i++) {
const currDate = new Date()
currDate.setDate(new Date().getDate() + i + nextOrderMinimumThreshold)
days.push(currDate)
}
var checkDate = function(dt) {
if (!enabledDays || !enabledDays?.length) {
if (!firstEligibleDateFlag) {
currentDate = new Date(dt);
firstEligibleDateFlag = true;
}
} else {
var currDate = new Date(dt);
if (typeof enabledDays === 'string') {
enabledDays = JSON.parse(enabledDays)
}
var allowedDate = enabledDays?.map(item => parseInt(item?.value));
if (allowedDate.indexOf(currDate.getDay()) !== -1) {
if (!firstEligibleDateFlag) {
currentDate = new Date(dt);
firstEligibleDateFlag = true;
}
}
}
}
days.forEach(item => {
checkDate(item)
})
if (window['jQuery']?.datepicker) {
if (jQuery('#appstle_membership_widget' + widgetId + ' .appstle_form_field_input_iso').length) {
var defaultOptions = {
altField: '#appstle_membership_widget' + widgetId + ' .appstle_form_field_input_alternate',
altFormat: "yy-mm-dd",
autoSize: true,
minDate: currentDate,
showOn: "both",
buttonImage: "https://ik.imagekit.io/mdclzmx6brh/calendar_month_FILL0_wght400_GRAD0_opsz48_iJLonfrRJ.png",
defaultDate: currentDate,
currentText: "Now",
beforeShowDay: function(dt) {
if (!enabledDays || !enabledDays?.length) {
return [true]
} else {
var currDate = new Date(dt);
if (typeof enabledDays === 'string') {
enabledDays = JSON.parse(enabledDays)
}
var allowedDate = enabledDays?.map(item => parseInt(item?.value));
if (allowedDate.indexOf(currDate.getDay()) !== -1) {
return [true]
} else {
return [false]
}
}
},
onSelect: function() {
// $(this).change();
$(this).parents('.as-date-input-wrapper').find('input').trigger('change')
}
}
if (config) {
config = JSON.parse(config)
} else {
config = {}
}
var dateOptions = jQuery.extend({}, defaultOptions, config)
window['jQuery']('#appstle_membership_widget' + widgetId + ' .appstle_form_field_input').datepicker(dateOptions);
window['jQuery']('#appstle_membership_widget' + widgetId + ' .appstle_form_field_input').datepicker( "setDate", currentDate );
window['jQuery']('#appstle_membership_widget' + widgetId + ' .appstle_form_field_input').parents('.as-date-input-wrapper').find('input').each((idx, item) => $(item).trigger('change'));
}
} else {
setTimeout(() => attatchDatePicker(config, enabledDays, nextOrderMinimumThreshold), 30)
}
}
function getCurrentSellingPlanId() {
var value = null;
try {
value = jQuery("#appstle_membership_widget" + widgetId).find('input[name=selling_plan]:checked').val();
} catch (e) {}
return value;
}
function changeHandlerForSelect() {
if (!AMConfig?.switchRadioButtonWidget) {
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_membership_wrapper select').on('change', function (event) {
updateStateOfWidget();
updateFormFields(getCurrentSellingPlanId());
});
} else {
jQuery('#appstle_membership_widget' + widgetId + ' .appstle_subscribe_option input').on('change', function (event) {
updateStateOfWidget();
updateFormFields(getCurrentSellingPlanId());
});
}
jQuery('#appstle_membership_widget' + widgetId + ' input[name="selling_plan"]').on('change', function (event) {
updateStateOfWidget();
updateFormFields(getCurrentSellingPlanId());
});
setTimeout(function() {
updateFormFields(getCurrentSellingPlanId());
}, 30)
}
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 {
if (!AMConfig?.switchRadioButtonWidget) {
value = jQuery("#appstle_membership_widget" + widgetId).find('.appstle_membership_wrapper_option.appstle_include_dropdown select').val();
} else {
value = jQuery("#appstle_membership_widget" + widgetId).find('.appstle_subscribe_option input:checked').val();
if (!value) {
value = jQuery("#appstle_membership_widget" + widgetId).find('input[name="selling_plan"]:checked').val();
}
}
} 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);
var sellingPlanDescription = getSellingPlanDescription(selectedSellingPlanAllocation?.selling_plan_group_id, selectedSellingPlanAllocation?.selling_plan_id)
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);
let selectedSellingPlanDetail = AM?.Config?.sellingPlansJson?.find(plan => plan.id === `gid://shopify/SellingPlan/${selectedSellingPlan}`);
let sellingPlanName = "";
if (selectedSellingPlanDetail?.frequencyName) {
sellingPlanName = selectedSellingPlanDetail?.frequencyName;
}
var subscribesaveText = buildSubscriptionOptionText(isPrepaidPlan, selectedDiscountSub, sellingPlanName);
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);
}
}
appendSellingPlanDescription(sellingPlanDescription);
}
}
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 appendSellingPlanDescription(sellingPlanDescription) {
if(sellingPlanDescription && $(`#appstle_membership_widget${widgetId} .appstleSelectedSellingPlanOptionDescription`).length === 0 && checkIfSellingPlanGroupIsSelected()){
if (jQuery( `#appstle_membership_widget${widgetId} .widgetSellingPlanWrapper` ).length) {
$( "
${sellingPlanDescription}
" ).insertAfter( `#appstle_membership_widget${widgetId} .widgetSellingPlanWrapper` );
} else {
$( "
${sellingPlanDescription}
" ).appendTo( `#appstle_membership_widget${widgetId} .appstle_subscribe_option` );
}
}
}
function checkIfSellingPlanGroupIsSelected() {
var selected = false;
try {
selected = jQuery('#appstle_membership_widget' + widgetId).find(`[name=selling_plan]:checked`).val();
} 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.html(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 getVariantId() {
var variant = urlParam("variant");
if (variant && AMConfig?.detectVariantFromURLParams) {
return variant;
} else {
if (standAloneElement) {
return jQuery(standAloneElement).closest('form[action$="/cart/add"]').find('[name=id]')[0] == undefined ? localWindowVariant.id : jQuery(standAloneElement).closest('form[action$="/cart/add"]').find('[name=id]')[0].value;
} else {
return 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;
}
}
}
function createJsonformat() {
var jsonWrapperOutput = {}
var variantId = getVariantId();
var price = null;
if (standAloneElement) {
price = ((standAloneProduct?.variants.filter(variant => String(variant?.id) === String(variantId))).pop()).price
} else {
price = AMConfig?.variantsById[variantId]?.price
}
jsonWrapperOutput.requires_selling_plan = product?.requires_selling_plan
jsonWrapperOutput.oneTimePuchaseText = AM.Config.oneTimePurchaseText
jsonWrapperOutput.oneTimePuchaseAmount = buildOneTimePriceText(formatPrice(price))
jsonWrapperOutput.subscribeText = AM.Config.subscriptionOptionText
jsonWrapperOutput.widgetId = widgetId
jsonWrapperOutput = Object.assign(Selling_Plan_Variants_Global,jsonWrapperOutput)
jsonWrapperOutput.tooltipTitle = AM.Config.tooltipTitle
jsonWrapperOutput.toolTipDescription = AM.Config.tooltipDesctiption
jsonWrapperOutput.companyWebsite = 'https://appstle.com/'
jsonWrapperOutput.companyName = 'POWERED BY APPSTLE'
jsonWrapperOutput.showStaticTooltip = AM.Config.showStaticTooltip
jsonWrapperOutput.purchaseOptionsText = AM.Config.purchaseOptionsText
jsonWrapperOutput.deliveryFrequencyText = AM.Config.sellingPlanSelectTitle
jsonWrapperOutput.showAppstleLink = AM.Config.showAppstleLink
jsonWrapperOutput.subscriptionOptionSelectedDefault = AM.Config.subscriptionOptionSelectedByDefault
jsonWrapperOutput.showSubOptionBeforeOneTime = AM.Config.showSubOptionBeforeOneTime
jsonWrapperOutput.showTooltip = AM.Config.showTooltip
jsonWrapperOutput.oneTimeFrequencyText = widgetLabels?.["appstle.membership.wg.oneTimeFrequencyTextV2"]
return jsonWrapperOutput
}
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 (AMConfig?.disableQueryParamsUpdate) return;
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 || formElement.find('input[value=' + paramsObj["selling_plan"] + ']').length > 0)) {
if (paramsObj['selling_plan']) {
var sellingPlanGroup = jQuery('#appstle_membership_widget' + widgetId + ' #appstle_selling_plan_label_2' + widgetId);
if (sellingPlanGroup.length) {
sellingPlanGroup[0].checked = true;
}
var sellingPlanDropdown = null;
if (!AMConfig?.switchRadioButtonWidget) {
sellingPlanDropdown = jQuery('#appstle_membership_widget' + widgetId + ' select#appstle_selling_plan' + widgetId)
} else {
sellingPlanDropdown = jQuery('#appstle_membership_widget' + widgetId + ' .appstle_subscribe_option')
}
if (!AMConfig?.switchRadioButtonWidget) {
sellingPlanDropdown.find('option').each(function (index, option) {
if (jQuery(option).attr('value') === paramsObj['selling_plan']) {
sellingPlanDropdown[0].selectedIndex = index;
}
});
} else {
if (sellingPlanDropdown?.length) {
sellingPlanDropdown.find('input[type=radio]').each(function (index, option) {
$(option).removeAttr("checked");
if (jQuery(option).attr('value') === paramsObj['selling_plan']) {
$(option).attr("checked", true)
}
});
} else {
jQuery('#appstle_membership_widget' + widgetId).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 = 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?.Currency?.money_format_no_currency || themeMoneyFormat || AMConfig?.shopMoneyFormat || moneyFormat || shopifyMoneyFormat || htmlDecode(AMConfig.shopMoneyFormatWithCurrencyFormat) || window?.moneyFormat;
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 appstleMembershipCustomerPortalInit(selector) {
selector = selector || "#AppstleMembershipCustomerPortal";
if (document.querySelector(selector)) {
return jQuery.get(`/${AMConfig?.manageSubscriptionUrl}?renderType=html`)
.then(result => {
jQuery(selector).html(result);
document.dispatchEvent( new Event('AppstleMembership:CustomerPortal:Embedded') );
window.dispatchEvent( new Event('AppstleMembership:CustomerPortal:Embedded') );
})
.catch(error => console.error('error', error));
}
}
window.appstleMembershipCustomerPortalInit = appstleMembershipCustomerPortalInit;
appstleMembershipCustomerPortalInit();
document.dispatchEvent( new Event('AppstleMembership:CustomerPortal:ReadyToEmbed') );
window.dispatchEvent( new Event('AppstleMembership: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 = $('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") !== -1) {
var currentBodyObj = null;
var sellingPlan = $('input[name=selling_plan]:checked').val()
if (sellingPlan) {
try {
if (data.substr(0,1) === "{" && data.substr(-1) === "}") {
currentBodyObj = JSON.parse(data);
var linkParams = new URLSearchParams(window.location.search)
var currentVariantId = linkParams.get('variant')
var newBodyArray = {}
if(getClassOf(currentBodyObj) === "Object" && getClassOf(currentBodyObj?.items) == "Array") {
var sellingPlanVariantIndex = currentBodyObj?.items?.findIndex(data => data.id == currentVariantId);
if(sellingPlanVariantIndex >= 0) {
var filteredVariant = currentBodyObj?.items?.filter(data => data.id != currentVariantId);
var sellingPlanIncludedVariant = JSON.parse(JSON.stringify(currentBodyObj?.items[sellingPlanVariantIndex]));
sellingPlanIncludedVariant[ "selling_plan"] = $('input[name=selling_plan]:checked').val();
filteredVariant.push(sellingPlanIncludedVariant);
newBodyArray.items = JSON.parse(JSON.stringify(filteredVariant));
send.call(this, JSON.stringify(newBodyArray));
} else {
send.call(this, JSON.stringify(currentBodyObj));
}
} else {
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 {
try {
if (getClassOf(data) === "FormData") {
data.set('selling_plan', $('input[name=selling_plan]:checked').val() || "")
send.call(this, data);
} else if (data?.substr(0,1) === "{" && data?.substr(-1) === "}") {
currentBodyObj = JSON.parse(data);
currentBodyObj.selling_plan = ""
send.call(this, JSON.stringify(currentBodyObj));
} else if (data?.substr(0,1) !== "{" && data?.substr(-1) !== "}" && data?.indexOf("&") !== -1) {
data = data.split(/&selling_plan=\d+/).join('')
send.call(this, data);
}else {
send.call(this, data);
}
} catch (e) {
send.call(this, data);
}
}
} else {
send.call(this, data);
}
};
})(XMLHttpRequest.prototype.send);
window.fetch = function() {
var resource = arguments[0];
var config = arguments[1];
if(typeof resource.indexOf === "function" && resource.indexOf('/cart/add') !== -1)
{
var linkParams = new URLSearchParams(window.location.search)
var currentVariantId = linkParams.get('variant')
if ((getClassOf(config.body) !== "FormData") && (getClassOf(config.body) !== "Object")) {
if (isJsonString(config?.body)) {
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"] = $('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 = $('input[name=selling_plan]:checked').val()
config.body = JSON.stringify(currentBodyObj);
return originalFetch.apply(this, arguments);
}
} else {
var selling_plan = $('input[name=selling_plan]:checked').val();
if (selling_plan) {
config.body = config.body + "&selling_plan=" + selling_plan;
}
return originalFetch.apply(this, arguments);
}
} else {
if (getClassOf(config.body) === "FormData") {
config.body.set('selling_plan', $('input[name=selling_plan]:checked').val() || "")
return originalFetch.apply(this, arguments);
}
}
}
else {
return originalFetch.apply(this, arguments);
}
};
}
function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
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/');
}
window.appstleMembershipAddToCart = function(instance) {
var form = (jQuery(instance).parents('form'))[0];
if (!form.checkValidity()) return;
var formDataObj = Object.fromEntries(new FormData(form))
var formDataItems = {
'items': [formDataObj]
}
var atcButtontext = jQuery(instance).find('[data-add-to-cart-text]');
var atcButtonLoader = jQuery(instance).find('[data-loader]');
atcButtontext.hide();
atcButtonLoader.show();
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formDataItems),
}).then(response => {
if (response.ok) {
window.location.href = '/cart';
} else {
atcButtontext.show();
atcButtonLoader.hide();
}
}).catch((error) => {
atcButtontext.show();
atcButtonLoader.hide();
});
}
// 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?.enableAddJSInterceptor === true) {
fetchAddJsSellingPlanInterCeptor()
}
})();
});
};
appstleMembershipWidgetInit();