(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(`
×
`).appendTo('body') jQuery(".appstle-not-logged-in-banner").append(jQuery.parseHTML(AM.Config["nonMemberMessaging"])) } } function addBanner(discountMessage) { jQuery(".appstle-discount-banner").remove(); jQuery(`
×
`).appendTo('body') jQuery(".appstle-discount-banner").append(jQuery.parseHTML(discountMessage)) } function showDiscountOptions(membershipName, discountCodeDetails, message, argProduct) { if (!standAloneElement) return; var parentSelector = AMConfig?.parentSelector || ""; var priceBlockSelector = AMConfig?.priceBlockSelector || ""; var priceBlockSelectorElement = ''; var priceBlockIdentifier = '.appstle-membership-price-block_small, .appstle-membership-price-block_big'; priceBlockSelectorElement = jQuery(standAloneElement).parents(parentSelector).find(priceBlockSelector); jQuery(standAloneElement).parents(parentSelector).find(priceBlockIdentifier).remove(); var productPagePriceDescriptionBlockParentSelector = AMConfig?.productPagePriceDescriptionBlockParentSelector || ""; var productPagePriceDescriptionBlockPriceSelector = AMConfig?.productPagePriceDescriptionBlockPriceSelector || ""; var productPagePriceDescriptionPriceBlockElement = jQuery(standAloneElement).parents(productPagePriceDescriptionBlockParentSelector).find(productPagePriceDescriptionBlockPriceSelector); if (isProductEligibleToShowDiscountPriceBlock(discountCodeDetails, argProduct)) { if (priceBlockSelectorElement.length) { var discountPriceBlockHtml = $(`
`); discountPriceBlockHtml.find('span').html(message) discountPriceBlockHtml.insertAfter(priceBlockSelectorElement) } if (productPagePriceDescriptionPriceBlockElement.length) { var productPagePriceDescriptionBlockHtml = $(`
${membershipName}
*
*Discount auto applied in checkout.
`); productPagePriceDescriptionBlockHtml.find('.appstlePriceDescriptionDiscountMessage').html(message) productPagePriceDescriptionBlockHtml.insertBefore(productPagePriceDescriptionPriceBlockElement) } } } function removeDiscountOptions() { if (!standAloneElement) return; var parentSelector = AMConfig?.parentSelector || ""; var priceBlockIdentifier = '.appstle-membership-price-block_small, .appstle-membership-price-block_big'; jQuery(standAloneElement).parents(parentSelector).find(priceBlockIdentifier).remove(); } function isDiscountOptionsPresent() { if (!standAloneElement) return; var parentSelector = AMConfig?.parentSelector || ""; var priceBlockIdentifier = '.appstle-membership-price-block_small, .appstle-membership-price-block_big'; return jQuery(standAloneElement).parents(parentSelector).find(priceBlockIdentifier).length; } function isProductEligibleToShowDiscountPriceBlock(discountCodeDetails, product) { if (checkDiscountSpecificToProduct(discountCodeDetails, product) && checkDiscountSpecificToCollection(discountCodeDetails, product)) { if (isDiscountEligibleForOneTimePurchase(discountCodeDetails, product) || isDiscountEligibleForSubscriptionProduct(discountCodeDetails, product)) { return true; } else { return false; } } else { return false; } } function isDiscountEligibleForOneTimePurchase(discountCodeDetails, product) { return !product?.requires_selling_plan && discountCodeDetails?.codeDiscountNode?.codeDiscount?.customerGets?.appliesOnOneTimePurchase } function isDiscountEligibleForSubscriptionProduct(discountCodeDetails, product) { return product?.selling_plan_groups.length && discountCodeDetails?.codeDiscountNode?.codeDiscount?.customerGets?.appliesOnSubscription } function checkDiscountSpecificToProduct(discountCodeDetails, product) { var productSpecificSharableUrls = discountCodeDetails?.codeDiscountNode?.codeDiscount?.customerGets?.items?.products?.edges; var isProductValid = false; if (productSpecificSharableUrls?.length) { productSpecificSharableUrls.forEach(item => { if (item?.node?.id?.split("/")?.pop() === String(product?.id)) { isProductValid = true; } }); return isProductValid; } else { return true; } } function checkDiscountSpecificToCollection(discountCodeDetails, product) { var collectionSpecificSharableUrls = discountCodeDetails?.codeDiscountNode?.codeDiscount?.customerGets?.items?.collections?.edges; var isProductValid = false; if (collectionSpecificSharableUrls?.length) { collectionSpecificSharableUrls.forEach(item => { if (product?.collections && product?.collections?.length) { var productCollectionHandles = product?.collections.map(item => item.handle) if (productCollectionHandles.indexOf(item?.node?.handle) > -1) { isProductValid = true; } } }); return isProductValid; } else { return true; } } if (!skipRules) { allCustomerTags.forEach(customerTag => { var rulesArray = JSON.parse(rulesByCustomerTag[customerTag][0]); rulesArray.forEach(rule => { if (rule.rule === 'element') { if (rule?.path) { (rule.path.split(",")).forEach(function(path) { if (rule.pathMatch === "exact") { if (location.pathname === path) { matchCustomerTag(customerTags, customerTag, rule); } } else { if (location.pathname.match(path) && !location.pathname.match("/cart") && !location.pathname.match("/account") && !location.pathname.match("/checkout")) { matchCustomerTag(customerTags, customerTag, rule); } } }) } else if (rule?.bucketCategoryValue) { if(rule?.bucketCategory === "tags") { if (AMConfig?.product && AMConfig?.product?.tags) { rule?.bucketCategoryValue.split(',') .forEach(function(tag, index) { if (AMConfig?.product?.tags?.indexOf(tag?.trim()) !== -1) { matchCustomerTag(customerTags, customerTag, rule); } }) } } else if (rule?.bucketCategory === "collections") { if (AMConfig?.product && AMConfig?.product?.collections && AMConfig?.product?.collections?.length) { var collectionHandles = AMConfig?.product?.collections.map(item => item.handle); rule?.bucketCategoryValue.split(',') .forEach(function(collenctionHandle, index) { if (collectionHandles?.indexOf(collenctionHandle?.trim()) !== -1) { matchCustomerTag(customerTags, customerTag, rule); } }) } } else if (rule?.bucketCategory === "type") { if (AMConfig?.product && AMConfig?.product?.type) { if (AMConfig?.product?.type === rule?.bucketCategoryValue) { matchCustomerTag(customerTags, customerTag, rule); } } } else if (rule?.bucketCategory === "vendor") { if (AMConfig?.product && AMConfig?.product?.vendor) { if (AMConfig?.product?.vendor === rule?.bucketCategoryValue) { matchCustomerTag(customerTags, customerTag, rule); } } } } // else { // matchCustomerTag(customerTags, customerTag, rule); // } } else if (rule.rule === 'discount') { matchDiscountWithCustomerTag(customerTags, customerTag, rule); } }) }) var elementsToRemove = jQuery.grep(unMatchedRules, function(value) { return jQuery.inArray(value.selector, matchedRules) < 0; }); elementsToRemove.forEach(function (element, index) { var elementToReplace; if (standAloneElement) { if (standAloneElement.parents('form[action*="cart/add"]').length && !standAloneElement.parents('form[action*="cart/add"]').find(".appstle_membership_blocker_item_removed").length) { if (standAloneElement.parents('form[action*="cart/add"]').find(element.selector).length) { elementToReplace = standAloneElement.parents('form[action*="cart/add"]').find(element.selector) } else { elementToReplace = jQuery(element.selector); } } else if (standAloneElement.parents(AMConfig?.productPagePriceDescriptionBlockParentSelector).length && !standAloneElement.parents(AMConfig?.productPagePriceDescriptionBlockParentSelector).find(".appstle_membership_blocker_item_removed").length) { if (standAloneElement.parents(AMConfig?.productPagePriceDescriptionBlockParentSelector).find(element.selector).length) { elementToReplace = standAloneElement.parents(AMConfig?.productPagePriceDescriptionBlockParentSelector).find(element.selector) } else { elementToReplace = jQuery(element.selector); } } else if (standAloneElement.parents(AMConfig?.parentSelector).length && !standAloneElement.parents(AMConfig?.parentSelector).find(".appstle_membership_blocker_item_removed").length) { if (standAloneElement.parents(AMConfig?.parentSelector).find(element.selector).length) { elementToReplace = standAloneElement.parents(AMConfig?.parentSelector).find(element.selector) } else { elementToReplace = jQuery(element.selector); } } } else { elementToReplace = jQuery(element.selector); } setTimeout(function() { if(element?.message) { var blockedElement = jQuery(`
`); jQuery(blockedElement).html(element?.message); jQuery(elementToReplace).replaceWith(blockedElement); } else { jQuery(elementToReplace).replaceWith(``); } }, 30); }); if (matchedDiscountRules.length) { var origOpen = window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open = function() { this.addEventListener('load', function() { var url = this.responseURL; if ((url.indexOf("cart/change.js") !== -1) || (url.indexOf("cart/add.js") !== -1) || (url.indexOf("cart/update.js") !== -1)) { getHighestDiscount(JSON.parse(JSON.stringify(matchedDiscountRules))); } }); 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) || (url.indexOf("cart/add.js") !== -1) || (url.indexOf("cart/update.js") !== -1)) { getHighestDiscount(JSON.parse(JSON.stringify(matchedDiscountRules))); } resolve(response); }) .catch((error) => { reject(response); }) }); } var discountOnCheckoutDetails = []; getHighestDiscount(matchedDiscountRules) function getHighestDiscount(matchedDiscountRules) { if (matchedDiscountRules.length) { var lastDiscount = matchedDiscountRules.shift(); fetch(lastDiscount?.discountUrl) .then(function(res) { if (res.ok) { jQuery.get('/checkout', function(res) { var resDocument = jQuery(jQuery.parseHTML(res)); var discountCode = resDocument.find(`[aria-label="Remove ${(lastDiscount?.discountCodeDetails?.codeDiscountNode?.codeDiscount?.title).toUpperCase()}"]`).length || resDocument.find(`[aria-label="Rimuovi ${(lastDiscount?.discountCodeDetails?.codeDiscountNode?.codeDiscount?.title).toUpperCase()}"]`).length; if (true) { var cartSubTotal = resDocument.find('[data-checkout-subtotal-price-target]').attr('data-checkout-subtotal-price-target'); discountOnCheckoutDetails.push(jQuery.extend({}, lastDiscount, { applieDiscountCode: discountCode, subTotal: 0, })) }; getHighestDiscount(matchedDiscountRules) }) } }) .catch(function(err) { console.log("appstle discount apply failed") if (AMConfig?.showDiscountWidget === "true") { removeDiscountOptions(); } }) } else { discountOnCheckoutDetails.sort(function(a, b) { return a['subTotal'] - b['subTotal']; }); var lastDiscount = discountOnCheckoutDetails.shift(); if (AMConfig?.showDiscountWidget === "true") { showDiscountOptions(lastDiscount?.membershipName, lastDiscount?.discountCodeDetails, lastDiscount?.discountMessage, product); } fetch(lastDiscount?.discountUrl) .then(function(res) { if (res.ok) { sessionStorage["appstle_membership_discount_applied"] = lastDiscount?.discountUrl; addBanner(lastDiscount?.discountMessage) } }) .catch(function(err) { console.log("appstle discount apply failed") if (AMConfig?.showDiscountWidget === "true") { removeDiscountOptions(); } }) } } } } 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 = AMConfig.customer_tags || []; var isVisible = true; if (!customerId && AMConfig.memberOnlySellingPlansJson && AMConfig.memberOnlySellingPlansJson[sellingPlanId]) { isVisible = false; } if (customerId && AMConfig.nonMemberOnlySellingPlansJson && AMConfig.nonMemberOnlySellingPlansJson[sellingPlanId]) { isVisible = false; } if (isVisible && customerId && AMConfig.memberOnlySellingPlansJson && AMConfig.memberOnlySellingPlansJson[sellingPlanId]) { if (AMConfig.memberOnlySellingPlansJson[sellingPlanId].memberInclusiveTags && AMConfig.memberOnlySellingPlansJson[sellingPlanId].memberInclusiveTags.trim()) { var sellingPlanTags = AMConfig.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 } : { sellingPlanName: sellingPlan.name, totalPrice: sellingPlan?.totalPrice, sellingPlanPrice: sellingPlan.formattedPrice, secondSellingPlanPrice: sellingPlan.secondFormattedPrice, discountText: sellingPlan.discountText }; var sellingPlanDisplayText = Mustache.render(AM.Config.sellingPlanTitleText, sellingPlanModel); return sellingPlanDisplayText; } function buildAtcButtonSelector() { var atcButtonSelector = AMConfig.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(AM.Config.oneTimePriceText, priceModel); return priceText; } function buildSubscriptionOptionText(isPrepaidPlan, discountValue) { let subscriptionOptionModel = { discountValue: discountValue }; let subscriptionOptionText = Mustache.render(AM.Config.subscriptionOptionText, subscriptionOptionModel); return subscriptionOptionText; } function buildSelectedPriceText(price, isPrePaid, totalPrice) { var priceModel = isPrePaid ? { pricePerDelivery: price, totalPrice: totalPrice } : { price: price, }; var text = isPrePaid ? AM.Config.selectedPrepaidSellingPlanPriceText : AM.Config.selectedPayAsYouGoSellingPlanPriceText; var priceText = Mustache.render(text, priceModel); return priceText; } function buildPrepaidPerDeliveryPriceText(price) { var priceModel = { prepaidPerDeliveryPrice: price, } return Mustache.render(AM.Config.totalPricePerDeliveryText, priceModel); } function buildSelectedTooltipPrePaidText(price, totalPrice) { var prepaidPricetooltipModel = { pricePerDelivery: price, totalPrice: totalPrice } var text = AM.Config.tooltipDescriptionOnPrepaidPlan; var prepaidPricetooltipText = Mustache.render(text, prepaidPricetooltipModel); return prepaidPricetooltipText; } function buildSelectedTooltipDiscountText(selectedSellingPlanAllocationObj, multipleDiscount) { if (selectedSellingPlanAllocationObj?.price_adjustments?.length == 2) { var discountModel = { firstPrice: formatPrice(selectedSellingPlanAllocationObj?.price_adjustments[0]?.price), secondPrice: formatPrice(selectedSellingPlanAllocationObj?.price_adjustments[1]?.price), discountOne: multipleDiscount.length > 0 ? multipleDiscount[0] : "", discountTwo: multipleDiscount.length == 2 ? multipleDiscount[1] : "" }; return Mustache.render(AM.Config.tooltipDescriptionOnMultipleDiscount, discountModel); } } function buildTooltipDetailsText(prepaidText, isPrePaid, discountText) { var tooltipDetailModel = isPrePaid ? { prepaidDetails: prepaidText, discountDetails: discountText, defaultTooltipDescription: AM.Config.tooltipDesctiption } : { defaultTooltipDescription: AM.Config.tooltipDesctiption, discountDetails: discountText }; // let text = AM.Config.tooltipDesctiption + (isPrePaid ? "
{{prepaidDetails}}" : "") + (discountText!= undefined ? "
{{discountDetails}}": ""); let text = AM.Config.tooltipDescriptionCustomization; var tooltipText = Mustache.render(text, tooltipDetailModel); return tooltipText; } function populateDropdown(purchaseOptions, variant) { var sellingPlanVariants = []; jQuery.each(product.selling_plan_groups, function (index, sellingPlanGroup) { if (sellingPlanGroup.app_id === 'appstle-memberships') { 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 = 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; } let discountText; var priceAdjustment = sellingPlan?.price_adjustments[0]; if (priceAdjustment?.value_type !== 'percentage') { discountText = formatPrice(priceAdjustment?.value); } else { discountText = priceAdjustment?.value + '%'; } sellingPlanVariants.push({ "name": sellingPlan.name, "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 (!AMConfig?.sortByDefaultSequence) { sellingPlanVariants.sort(function (sellingPlanA, sellingPlanB) { return sellingPlanA.price - sellingPlanB.price; }) } jQuery(sellingPlanVariants).each(function (index, sellingPlan) { var sellingPlanDisplayText = buildSellingPlantText(sellingPlan); jQuery('