var apoProductDefault = "default"; (ap_loadScript = function (t, i) { var e = document.createElement("script"); (e.type = "text/javascript"), e.readyState ? (e.onreadystatechange = function () { ("loaded" != e.readyState && "complete" != e.readyState) || ((e.onreadystatechange = null), i()); }) : (e.onload = function () { i(); }), (e.src = t), document.getElementsByTagName("head")[0].appendChild(e); }), (ap_addOptions = async function ($, customizeryConfig) { if(customizeryConfig.optionSets.length === 0 || window.apo_js_loaded.options){ if(typeof window.removeDisabledBtnAddCart === 'function'){ setTimeout(window.removeDisabledBtnAddCart, 200) } } if (window.apo_js_loaded.options) return; window.apo_js_loaded.options = true; window.ap_front_settings.config.is_clone_bt_addcart = true; var money_format = window.ap_front_settings && window.ap_front_settings.money_format ? window.ap_front_settings?.shop_id === '73060385049' ? window.ap_front_settings.money_with_currency_format : window.ap_front_settings.money_format : "${{amount}}"; if (Object.keys(window.apoOptionLocales.avisSettings).length > 0) { for(let settingItem in window.apoOptionLocales.avisSettings) { if (window.apoOptionLocales.avisSettings[settingItem]) customizeryConfig[settingItem] = window.apoOptionLocales.avisSettings[settingItem]; } } let isCssV3 = false; const OPTION_URL = { group: "group_product", only: "only_url", allowed: "allowed_open_url", }; const OPTION_URL_DISPLAY = { value: "click_value", view: "click_view", }; const AVIS_CLASS = { soldOutOption: "avis-option-soldout", }; const AVIS_SOLD_OUT = "Sold out"; var listOptions = []; var useAddchargeApoOption = customizeryConfig?.is_addcharge_apo_option ?? false; if ( !useAddchargeApoOption && customizeryConfig?.cart_page?.display_addon_cart ) useAddchargeApoOption = true; // Add setting: show watermark var isShowWatermarkOnProductPage = customizeryConfig.show_watermark_on_product_page; var shop_id = window.ap_front_settings?.shop_id; var totalPriceAdd = 0; var container_AP_POptions = "avpoptions-container__v2"; let isCustom149 = window.ap_front_settings?.product_info?.product_id === "8121233309931" && (shop_id === "61530898667" || shop_id === "67691053329"); let isThemeProperty = shop_id === "84988035369"; let isNotUseAvisHidden = false; // shop_id === "77859357001"; var joinAddCharge = window.ap_front_settings.joinAddCharge; if (shop_id === "59437023322") { joinAddCharge = "||"; } if (shop_id === "48439328922" && customizeryConfig?.widget) { let keyElement = !customizeryConfig?.widget || !customizeryConfig?.widget?.position || customizeryConfig?.widget?.position == "default" ? "default" : customizeryConfig?.widget?.position.split("_")[1]; if (keyElement === "selector" && customizeryConfig?.widget?.selector) { if (!document.querySelector(customizeryConfig?.widget?.selector)) return; } } let showPriceACCart = shop_id === "70719799540" || shop_id === "54416834757" || shop_id === "86711959862" || shop_id === "54416834757"; //a9b06b-ca.myshopify.com let KEY_FORMAT_PRICE = "addon_price"; let KEY_JOIN_PRICE = "(+"; let avisFormatPrice = `${KEY_JOIN_PRICE}${KEY_FORMAT_PRICE})`; if(shop_id === '10278593'){ avisFormatPrice = `(${KEY_FORMAT_PRICE})` } if(shop_id === '10278593'){ avisFormatPrice = `(${KEY_FORMAT_PRICE})` } let isNewValidateShop = ["59661713513","60173221974","66985525527","81382703435","90115932451","87503831334","87616127313"].includes(shop_id); if (!isNewValidateShop) { isNewValidateShop = customizeryConfig?.validate_settings === "inline"; } let isQtyDefaultZero = ["58362396724","81519247698","77601243472","83432636743", "63594234085","66916745498","73531588924","60284698735","59661713513","79486681403","50712903860"].includes(shop_id); if (!isQtyDefaultZero) { isQtyDefaultZero = customizeryConfig?.is_quantity_start_zero ?? false; } let isNotSyncQtyProductAc = ["55533404247"].includes(shop_id); let useSoldOutOption = customizeryConfig?.product_page?.out_of_stock_display === "hide_option"; (window.AP_POptions = window.AP_POptions || {}), (AP_POptions.$ = $); function getEventData(e, t) { return e._data ? e._data(t, "events") : e.data ? e.data(t, "events") : null; } var pluginAction = { getProduct: (t) => new Promise((o, n) => { let rootUrl = "/"; if (shop_id === "72799093070") { rootUrl = "/pt/"; } if (shop_id === "70071189821") { rootUrl = Shopify.routes.root; } o( fetch(rootUrl + `products/${t}.js`, { method: "GET" }) .then((t) => { if (t.status == "200") return t.json(); else null; }) .then((t) => t) ); }), getColecByPrId: async function (productId) { const fetchOptions = { method: "GET", headers: { "shop-id": shop_id, }, }; return new Promise((n, o) => { n( fetch( `${priceMod.avisUrl}product/collections?id=${productId}`, fetchOptions ) .then((t) => { return t.json(); }) .then((t) => t) ); }); }, queryProductInfo: async function(locales, ids){ if (!ids?.length) return ""; locales = window.apoOptionLocales?.convertLocales(locales); let idsArr = []; for(let id of ids) { idsArr.push(`gid://shopify/Product/${id}`); } let idsString = idsArr.join('","'); let query = `\n query productDetails @inContext(country: ${window.Shopify.country.toUpperCase() ?? "EN"}, language: ${locales.toUpperCase()}) {\n nodes(ids: ["${idsString}"]) {\n ... on Product {\n id\n handle\n title\n availableForSale\n variants(first:250){\n nodes{\n id\n availableForSale\n quantityAvailable\n compareAtPrice{\n currencyCode\n amount\n }\n currentlyNotInStock\n price{\n currencyCode\n amount\n }\n title\n sku\n }\n }\n }\n }\n }\n `; return query; }, fetchStoreFront: async function(queryData){ if (!window.apoOptionLocales?.config?.storefront_connect) return null; let root = window.Shopify && window.Shopify.routes && (window.Shopify.routes.root || window.Shopify.routes.root_url) || "/"; let url = `${root}api/${window.apoOptionLocales?.version}/graphql.json`; let data = { method: "POST", headers: { "Content-Type": "application/json", "X-Shopify-Storefront-Access-Token": window.apoOptionLocales?.config?.storefront_connect }, body: JSON.stringify({ query: queryData }) }; const response = await fetch(url, data); if (response.ok) { const json = await response.json(); return json; } return null; } }; var key_variant_conditional = "avis_shopify_option"; var formProductGenOptionJs = {}; var selectedVariantIdAll = {}; window.pubFormProductGenOptionJs = formProductGenOptionJs; var conditionalLogicInstances = { default: "" }; function intervalHandleShopifyVariant( elemOptionAvisContainer, productId, productInfo ) { setInterval(function () { let watchingVariant = conditionalLogicInstances[productId].watching[ key_variant_conditional ]; if (!watchingVariant) return; let variants = productInfo.variants; let variantId = variants[0].id.toString(); let formData = new FormData(formProductGenOptionJs[productId]); if (formData && formData.get("id")) variantId = formData.get("id"); else { const searchParams = new URLSearchParams(window.location.search); if (searchParams?.get("variant")) { variantId = searchParams?.get("variant"); } } let oldVariantId = selectedVariantIdAll[productId]; if (oldVariantId !== variantId) { conditionalLogicInstances[productId]?.s_check_input_variant( elemOptionAvisContainer, productId, productInfo ); } }, 300); } let variantIdTemp = ""; function handleChangeShopifyVariant( elemOptionAvisContainer, productId, productInfo ) { const observer = new MutationObserver(function () { // Handle change variant reload view clear avis option // || shop_id === "83272958226" if (shop_id === "60370419756" || shop_id === "72903328090" || shop_id === "90746126677") { if ( window?.ap_front_settings?.page_type === "product" && !document.querySelector(".avpoptions-container__v2") ) { if (shop_id === "72903328090" || shop_id === "90746126677") { let variantId = ""; const searchParams = new URLSearchParams(window.location.search); if (searchParams?.get("variant")) { variantId = searchParams?.get("variant"); } if (variantIdTemp !== variantId) { variantIdTemp = variantId; mainCheckAllRules(); } } else mainCheckAllRules(); } } setTimeout(function () { // handle when slow change shopify option if (shop_id === "29666866") { intervalHandleShopifyVariant( elemOptionAvisContainer, productId, productInfo ); } else { conditionalLogicInstances[productId]?.s_check_input_variant( elemOptionAvisContainer, productId, productInfo ); } }, 200); }); const config = { subtree: true, childList: true }; observer.observe(document, config); if (shop_id === "14252734" || shop_id === "57017368679") { intervalHandleShopifyVariant( elemOptionAvisContainer, productId, productInfo ); } } // 1. Check rules options var customizeryRules = new (function () { var e = this; return ( (e.getHandleFromUrl = function (e) { var t = e.replace(/\/$/, "").split("/"); return ( ("products" == t[t.length - 2] || "products_preview" === t.pop()) && t[t.length - 1].replace(/(.*)?\?.*$/, "$1") ); }), (e.getProduct = function (t, n) { if (t instanceof Object) return n(t); var i = e.getProductFromWindow(); i ? n(i) : t ? e.pullProduct(t, n) : n(!1); }), (e.getProductFromWindow = function () { return window.ap_front_settings && window.ap_front_settings.product_info.product instanceof Object ? window.ap_front_settings.product_info.product : undefined; }), (e.pullProduct = function (e, t) { return window.IS_AP_POptions ? void $.getJSON( "//" + window.shopConfiguration.uuid + ".myshopify.com/products/" + e + ".json", function (e) { t(e.product); } ) : void $.ajax({ dataType: "json", cache: !1, url: "/products/" + e + ".json", success: function (e) { t(e.product); }, error: function (e) { throw "AvisPlus Options product lookup error"; }, }); }), (e.checkRuleForProduct = function (ruleSetItem, product) { let t = ruleSetItem; let n = product; switch ( ((t.selector = String(t.selector).toLowerCase().trim()), t.type) ) { case "all": return !0; case "product_handle": return n.handle.toLowerCase().trim() === t.selector; case "product_url": var i = t.selector; return n.handle.toLowerCase().trim() === e.getHandleFromUrl(i); case "tag": return "string" == typeof n.tags ? ((n.tags = n.tags.toLowerCase()), n.tags.indexOf(", ") >= 0 ? n.tags.split(", ").indexOf(t.selector) >= 0 : n.tags === t.selector) : ((n.tags = n.tags.join(",").toLowerCase().split(",")), n.tags.indexOf(t.selector) >= 0); case "vendor": return n.vendor.toLowerCase().trim() === t.selector; case "type": if (n.type) return n.type.toLowerCase().trim() === t.selector; if (n.product_type) return n.product_type.toLowerCase().trim() === t.selector; } }), (e.checkConditionsForProduct = function (type, conditions, product) { switch (type) { case "all": let index = 0; for (let condition of conditions) { if (!e.checkConditionItemForProduct(condition, product)) break; index = index + 1; } return index == conditions.length; case "any": for (let condition of conditions) { if (e.checkConditionItemForProduct(condition, product)) return true; } return false; default: return false; } }), (e.checkConditionItemForProduct = function (condition, product) { if (!condition["type"] || !condition["selector"]) return false; let filter = String(condition.selector).toLowerCase().trim(); let keywordCompareType = condition["keywordCompareType"]; let data = null; switch (condition.type) { case "title": return e.compareKeyConditionItemForProduct( keywordCompareType, filter, product.title ); case "type": if (product["type"]) data = product.type; else if (product["product_type"]) data = product.product_type; return e.compareKeyConditionItemForProduct( keywordCompareType, filter, data ); case "vendor": return e.compareKeyConditionItemForProduct( keywordCompareType, filter, product["vendor"] ); case "tag": return e.compareKeyConditionItemForProductTag( keywordCompareType, filter, product.tags ); // console.log("product.tags 2", product.tags); case "price": return e.compareKeyConditionItemForProduct( keywordCompareType, parseFloat(filter) * 100, product["price"] ); case "collection": let collectionsOfProduct = product.collections; if (collectionsOfProduct.length == 0) return false; if (keywordCompareType == "is_equal_to") { return ( collectionsOfProduct.filter( (e) => e.title && String(e.title).toLowerCase() == filter ).length > 0 ); } return false; } return false; }), (e.compareKeyConditionItemForProductTag = function ( keywordCompareType, filter, data ) { if (!keywordCompareType) return false; switch (keywordCompareType) { case "is_equal_to": return "string" == typeof data ? ((data = data.toLowerCase()), data.indexOf(", ") >= 0 ? data.split(", ").indexOf(filter) >= 0 : data === filter) : ((data = data.join(",").toLowerCase().split(",")), data.indexOf(filter) >= 0); case "is_not_equal_to": return "string" == typeof data ? ((data = data.toLowerCase()), data.indexOf(", ") >= 0 ? data.split(", ").indexOf(filter) == -1 : data === filter) : ((data = data.join(",").toLowerCase().split(",")), data.indexOf(filter) == -1); case "contains": if ("string" == typeof data) data = data.toLowerCase(); else data = data.join(", ").toLowerCase(); return data.split(", ").find((x) => x.indexOf(filter) > -1); case "does_not_contain": if ("string" == typeof data) data = data.toLowerCase(); else data = data.join(", ").toLowerCase(); return ( data.split(", ").find((x) => x.indexOf(filter) > -1) === undefined ); case "starts_with": return "string" == typeof data ? ((data = data.toLowerCase()), data.indexOf(", ") >= 0 ? data.split(", ").some((item) => item.startsWith(filter)) : data === filter) : ((data = data.join(",").toLowerCase().split(",")), data.some((item) => item.startsWith(filter))); case "ends_with": return "string" == typeof data ? ((data = data.toLowerCase()), data.indexOf(", ") >= 0 ? data.split(", ").some((item) => item.endsWith(filter)) : data === filter) : ((data = data.join(",").toLowerCase().split(",")), data.some((item) => item.endsWith(filter))); default: return false; } }), (e.compareKeyConditionItemForProduct = function ( keywordCompareType, filter, data ) { if (!keywordCompareType) return false; if (data && "string" == typeof data) data = data.toLowerCase().trim(); switch (keywordCompareType) { case "is_equal_to": return filter == data; case "is_not_equal_to": return filter != data; case "starts_with": return data.startsWith(filter); case "ends_with": return data.endsWith(filter); case "does_not_contain": return data && data.indexOf(filter) == -1; case "contains": return data && data.indexOf(filter) >= 0; case "is_greater_than": return parseFloat(filter) < parseFloat(data); case "is_less_than": return parseFloat(filter) > parseFloat(data); default: return false; } }), (e.checkRuleSetForProduct = function (t, n) { var i = !1; return ( $.each(t, function (t, o) { if (o && o.selector && o.type && e.checkRuleForProduct(o, n)) return (i = !0), !1; }), i ); }), (e.checkAllRules = function ( optionSetsConfig, optionSetsKey, productInfo, productId, renderOptions ) { // t: customizeryConfig, n: optionSets, o: function add options return optionSetsConfig[optionSetsKey] && optionSetsConfig[optionSetsKey].length ? (productInfo || (productInfo = e.getHandleFromUrl(location.pathname)), // If dont't product, get handle product by url void e.getProduct(productInfo, async function (productInfo) { let optionSets = customizeryConfig["optionSets"]; let checkExistCollection = optionSets?.find( (x) => x.type === "automated" && x?.conditional_applying_product?.conditions && x.conditional_applying_product.conditions.find( (y) => y.type === "collection" && y.selector ) ); // Get collections if (productInfo?.id && checkExistCollection) { if (productId === apoProductDefault) { productInfo["collections"] = window?.ap_front_settings?.product_info?.collections; } else { let collections = await pluginAction.getColecByPrId( productInfo?.id ); productInfo["collections"] = collections?.data; } } return productInfo ? renderOptions( optionSetsConfig[optionSetsKey].filter(function ( optionSet ) { if ( (window.ap_front_settings.config && window.ap_front_settings.config.app_v && window.ap_front_settings.config.app_v.indexOf( "v2" ) > -1) || (optionSetsConfig["app_v"] && optionSetsConfig["app_v"].indexOf("v2") > -1) ) { if (!optionSet.type) return false; switch (optionSet.type) { case "all": return true; case "manual": if ( !optionSet["products"] || optionSet.products.length == 0 ) { return false; } else { return optionSet.products.includes( String(productInfo.id) ); } case "automated": if ( !optionSet["conditional_applying_product"] || !optionSet.conditional_applying_product[ "type" ] || !optionSet.conditional_applying_product[ "conditions" ] ) return false; return e.checkConditionsForProduct( optionSet.conditional_applying_product.type, optionSet.conditional_applying_product .conditions, productInfo ); default: return false; } } else { if ( !optionSet.rule_sets || !optionSet.rule_sets.length ) return false; if (optionSet.all_products) return true; var ruleSets = optionSet.rule_sets.filter(function ( ruleSet ) { return e.checkRuleSetForProduct( ruleSet, productInfo ); }); return ruleSets.length === optionSet.rule_sets.length; } }), productInfo ) : renderOptions(null); })) : renderOptions(null); }), e ); })(); // 2. Init option for product page var priceModAll = {}; window.avisAddChargeActive = priceModAll; function getAllProperties(productId) { let avisAddCartFormActive = formProductGenOptionJs[productId]; if ( avisAddCartFormActive?.className?.indexOf("avisAddCartFormActive") > -1 ) return; let properties = []; if (avisAddCartFormActive.localName === "form") { let formData = new FormData(avisAddCartFormActive); if (typeof formData?.forEach === "function") { formData.forEach((value, key) => { if (key.indexOf("properties") > -1) { let property = key.replace("properties[", "").replace("]", ""); properties.push({ key: property, value: value }); } }); } else { formData?.fd?.forEach((value, key) => { if (key.indexOf("properties") > -1) { let property = key.replace("properties[", "").replace("]", ""); properties.push({ key: property, value: value }); } }); } } priceModAll[productId]["properties"] = properties; if (shop_id === "69043421407") { let listOptionSelector = document.querySelector(".list-avis-options"); if (!listOptionSelector) { let totalAddCharge = document.querySelector(".apo-total-addcharge"); if (totalAddCharge) { listOptionSelector = document.createElement("div"); listOptionSelector.classList.add("list-avis-options"); listOptionSelector.setAttribute("style", "display:none !important"); totalAddCharge.parentNode.insertBefore( listOptionSelector, totalAddCharge ); } } if (listOptionSelector) { let itemOptionSelectors = listOptionSelector.querySelectorAll( ".avis-option-properties" ); let prevOption = null; let isHasPro = false; for (let itemProperty of properties) { isHasPro = true; let propertySelector = listOptionSelector.querySelector( `.avis-option-properties[data-key='${itemProperty.key}']` ); if (propertySelector) { if ( propertySelector.getAttribute("data-value") !== itemProperty.value ) { propertySelector.innerHTML = `${itemProperty.key}:${itemProperty.value}`; propertySelector.setAttribute("data-value", itemProperty.value); } } else { propertySelector = document.createElement("div"); propertySelector.classList.add("avis-option-properties"); propertySelector.setAttribute("data-key", itemProperty.key); propertySelector.setAttribute("data-value", itemProperty.value); propertySelector.innerHTML = `${itemProperty.key}:${itemProperty.value}`; if (prevOption) { prevOption.parentNode.insertBefore( propertySelector, prevOption.nextSibling ); } else { listOptionSelector.prepend(propertySelector); } } prevOption = propertySelector; } if (isHasPro) { listOptionSelector.removeAttribute("style"); } else listOptionSelector.setAttribute("style", "display:none !important"); for (var tempItem of itemOptionSelectors) { if ( !properties.find( (x) => x.key === tempItem.getAttribute("data-key") ) ) tempItem.remove(); } } } } var priceMod = { isEditOptionCart: false, cartCurrent: window.ap_front_settings.cart, cartItemLineEdit: -1, cartItemEdit: null, cartData: null, isCloneButtonAddCart: window.ap_front_settings.config.is_clone_bt_addcart ?? false, avisAddCartForm: $('form[action$="/cart/add"]'), avisAddCartFormActive: $('form[action$="/cart/add"]'), avisAddCartFormActiveJS: document.querySelector( 'form[action$="/cart/add"]' ), avisUrl: "https://apo-api.avisplus.io/shopify/api/", options: { appendPrice: !1, skipPriceModIfVisible: "" }, variantSubmissionAlters: [], orderId: new Date().getTime(), variantOrdering: [], activeVariants: {}, radioInput: {}, productVariantBundles: [], buttonAddCart: null, toggleSelector: function (elem) { elem.style.display = "block" != getComputedStyle(elem).display ? "block" : "none"; }, isHiddenSwatchTitle: function (option) { return option?.hidden_variant_title != null && option?.hidden_variant_title !== undefined ? option?.hidden_variant_title : customizeryConfig?.customize_options?.swatch?.hidden_variant_title; }, classHiddenSwatchTitle: function (isHiddenSwatchTitle) { return isHiddenSwatchTitle ? "avp-hiddenvarianttitleswatch" : ""; }, addLoadingAddCart: function (button) { button.setAttribute("disabled", "disabled"), button.classList.add("apo-loading"); }, removeLoadingAddCart: function (button) { button.removeAttribute("disabled", "disabled"), button.classList.remove("apo-loading"); }, getAllProductVariantBundles: async function (productHandles) { if (productHandles && productHandles.length > 0) { let products = await Promise.all( productHandles.map(async (handle) => { let productInfo = await pluginAction.getProduct(handle); if (productInfo) return productInfo; return null; }) ); priceMod.productVariantBundles = priceMod.productVariantBundles.concat(products); priceMod.productVariantBundles = priceMod.productVariantBundles.filter((x) => x); } }, getValueSelected: function (optionSelector) { let titleValueSelector = optionSelector.querySelector( ".avp-option-title .apo-title-value" ); if (!titleValueSelector) return; let listValues = optionSelector.querySelectorAll( "input[type='checkbox'],input[type='radio']" ); let result = ""; for (let value of listValues) { if (value.checked) { if(window.ap_front_settings.shop_id === "66784985269") { result += ` : ${value.value}`; }else if(window.ap_front_settings.shop_id === "90703069571") { result += ` ${value.value}`; }else { result += ` | ${value.value}`; } } } if (titleValueSelector) titleValueSelector.innerHTML = result; }, isLegacyValue: function (e) { return !e || "string" == typeof e || e instanceof String; }, hasVariant: function (optionValue) { let result = !priceMod.isLegacyValue(optionValue) && optionValue.type && (optionValue.type === "useexistingvariant" || optionValue.type === "chargeorbundle") && optionValue.productId && optionValue.is_exist && optionValue.productVariationId; return result; }, 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; }, formatWithDelimitersToNumber(number, precision, thousands, decimal) { thousands = thousands || ","; decimal = decimal || "."; if (isNaN(number) || number === null) { return 0; } number = (number / 100.0).toFixed(precision); return number; }, convertMoney: function (cents) { var value = ""; var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/; var formatString = money_format; switch (formatString.match(placeholderRegex)[1]) { case "amount": value = priceMod.formatWithDelimiters(cents, 2); break; case "amount_no_decimals": value = priceMod.formatWithDelimiters(cents, 0); break; case "amount_with_comma_separator": value = priceMod.formatWithDelimiters(cents, 2, ".", ","); break; case "amount_no_decimals_with_comma_separator": value = priceMod.formatWithDelimiters(cents, 0, ".", ","); break; case "amount_no_decimals_with_space_separator": value = priceMod.formatWithDelimiters(cents, 0, " "); break; case "amount_with_apostrophe_separator": value = priceMod.formatWithDelimiters(cents, 2, "'"); break; } if (shop_id === "69043421407") { value = value.replace(",", ".").replace(",", "."); } return value; }, isNumeric: function (str) { return !isNaN(str) && !isNaN(parseFloat(str)); }, formatMoney: function (cents, isZeroToEmpty = false) { if (typeof cents === "string") { cents = cents.replace(".", ""); } var value = priceMod.convertMoney(cents); if (isZeroToEmpty && value == "0") return null; var formatString = money_format; var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/; return formatString.replace(placeholderRegex, value); }, formatMoneyByConfig: function (price) { return avisFormatPrice.replace( KEY_FORMAT_PRICE, priceMod.formatMoney(price, true) ); }, formatMoneyOnlyPrice: function (cents) { if (typeof cents === "string") { cents = cents.replace(".", ""); } return priceMod.convertMoney(cents); }, formatMoneyToNumber: function (cents) { if (typeof cents === "string") { cents = cents.replace(".", ""); } var value = 0; var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/; var formatString = money_format; switch (formatString.match(placeholderRegex)[1]) { case "amount": value = priceMod.formatWithDelimitersToNumber(cents, 2); break; case "amount_no_decimals": value = priceMod.formatWithDelimitersToNumber(cents, 0); break; case "amount_with_comma_separator": value = priceMod.formatWithDelimitersToNumber(cents, 2, ".", ","); break; case "amount_no_decimals_with_comma_separator": value = priceMod.formatWithDelimitersToNumber(cents, 0, ".", ","); break; case "amount_no_decimals_with_space_separator": value = priceMod.formatWithDelimitersToNumber(cents, 0, " "); break; case "amount_with_apostrophe_separator": value = priceMod.formatWithDelimitersToNumber(cents, 2, "'"); break; } return value; }, formatNewMoney: function (cents) { if (typeof cents === "string") { cents = cents.replace(".", ""); } var formatString = money_format; var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/; return formatString.replace(placeholderRegex, cents); }, priceMarkup: function (e, t) { let formatPrice = priceMod.formatMoney(parseFloat(e), true); if (formatPrice){ if(shop_id === '10278593'){ return `(${formatPrice})` } return `(+${formatPrice})`; } return ""; }, getValueText: function (e, option) { if (priceMod.isLegacyValue(e)) return { value: e, display: e }; if (!e) { return { value: !1, display: !1 }; } let isSwatch = option.type === "swatch" || option.type === "swatch_single_color" || option.type === "swatch_single_image" || option.type === "swatch_multi_color" || option.type === "swatch_multi_image"; let valueClass = isSwatch ? "swatch-variant-title" : "choice-list-variatnt-title"; let isHasPrice = true; if ( e.type == "adjustprice" || e.price === "" || ((e.type == "useexistingvariant" || e.type == "chargeorbundle") && !e.is_exist) || ((e.price == "0" || !e.price) && e.type == "createcharge") ) isHasPrice = false; if ( option?.type === "select" && window.ap_front_settings.shop_id === "63321833641" ) isHasPrice = false; let nameValue = e.value; let borderRadius = ""; let buttonConfig = customizeryConfig?.customize_options?.button; if ( option?.type === "button_single" || option?.type === "button_multi" ) { borderRadius = `border-radius: ${buttonConfig?.border_radius ?? 4}px; padding: ${buttonConfig?.padding_top_bottom ?? 8}px ${buttonConfig?.padding_left_right ?? 8}px;`; } if (!nameValue?.trim() && option?.option_url === OPTION_URL.group) nameValue = e.url_name; let valueDisplay = nameValue; if ( !option?.hide_price && isHasPrice && option.option_show_price !== "only_label" ) { valueDisplay = `${nameValue} ${priceMod.priceMarkup(e.price)}`; } if (shop_id === "87616127313" && !option?.hide_price && isHasPrice && option.option_show_price !== "only_label") { valueDisplay = `

${nameValue}

${priceMod.priceMarkup(e.price)}`; } else if (shop_id === "87616127313") { valueDisplay = `

${nameValue}

` } let newValueDisplay = valueDisplay; let isShowDes = false; if (e.des_value && option.tooltip_display !== "desc") { newValueDisplay = `${newValueDisplay}`; newValueDisplay += `${e.des_value}`; isShowDes = true; } else if ( shop_id === "84354957654" && (option?.type === "radio" || option?.type === "checkbox") && option.new_help_text ) { newValueDisplay += `
${option.new_help_text}
`; } if (["radio", "checkbox"].includes(option.type) && !option.tooltip_display && e?.swatch?.file_image_url) { valueDisplay = ` ${valueDisplay} ${newValueDisplay} `; } else { if (option.type !== "select") { if (isShowDes) { valueDisplay = `${newValueDisplay}`; } else valueDisplay = `${valueDisplay}`; } } // if ( // (option?.type === "radio" || option?.type === "checkbox") && // e?.swatch?.file_image_url // ) { // // valueDisplay = ` // // ${valueDisplay} // // ${newValueDisplay} // // `; // } else let valueUrl = e?.url?.trim(); if ( option?.type !== "select" && option?.type !== "swatch_select_color" && option?.type !== "swatch_select_image" ) { if (option?.option_url === OPTION_URL.allowed && valueUrl) { if (option?.url_display === OPTION_URL_DISPLAY.view) { valueDisplay = ` ${valueDisplay}${option?.url_label ?? "View"} `; } else { valueDisplay = `${valueDisplay}`; } } else if ( option?.option_url === OPTION_URL.group || (option?.option_url === OPTION_URL.only && valueUrl) ) { valueDisplay = `${valueDisplay}`; } } let formatPrice = priceMod.formatMoney(parseFloat(e.price), true); let valueData = nameValue; if ( isHasPrice && formatPrice && e.type != "useexistingvariant" && e.type != "chargeorbundle" ) { valueData = `${valueData} [ ${formatPrice} ]`; } return { value: valueData, display: valueDisplay, }; }, getVariantString: function (e, t, n, productId) { return ( e + "-" + t + "-" + priceModAll[productId].variantOrdering.length ); }, findInputQuantityByInputValue: function (elemValue) { if (elemValue && elemValue.parents(".avp-value-grid").length > 0) { return elemValue .parents(".avp-value-grid") .find("input.avp-qty-input"); } return null; }, variantData: function (e, t) { return { name: e, productId: t.data("variant-product"), handle: t.data("product-handle"), variantId: t.data("variant-id"), price: t.data("variant-price"), quantity: 1, isOneTime: t.data("variant-onetime"), value: t.data("option-value"), type: t.data("option-type"), is_char: t.data("data-char") ?? false, $input: t, isShow: true, }; }, addVariant: function (e, t, n, productId) { (priceModAll[productId].activeVariants[t] = priceMod.variantData(e, n)), spLog( { string: t, data: priceMod.activeVariants[t] }, "adding variant to current", !0 ), priceModAll[productId].activeVariants[t].variantId && priceModAll[productId].activeVariants[t].variantId != "" && eventApi.productBundleAdd({ name: e, element: n, productBundle: priceModAll[productId].activeVariants[t], orderId: priceMod.orderId, }); }, removeVariant: function (e, t, n, productId) { var i = priceModAll[productId].activeVariants[t]; spLog({ string: t, data: i }, "removing variant from current", !0), delete priceModAll[productId].activeVariants[t], i.variantId && i.variantId != "" && eventApi.productBundleRemove({ name: e, element: n, productBundle: i, }); }, variantChangeSingle: async function (e, t, productId) { let optionType = t.data("option-type"); let isChoiseList = !checkOptionAddCharge(optionType); var n = t.data("variant-string"); ((isChoiseList && t.is(":checked")) || (!isChoiseList && (t.find("[field-name]")?.val() || t?.val() || t.find(".apo_value")?.val()))) && !priceModAll[productId].activeVariants[n] ? priceMod.addVariant(e, n, t, productId) : ((isChoiseList && !t.is(":checked")) || (!isChoiseList && !t.find("[field-name]")?.val() && !t?.val() && !t.find(".apo_value")?.val())) && priceModAll[productId].activeVariants[n] && priceMod.removeVariant(e, n, t, productId); if (isChoiseList && priceModAll[productId].activeVariants[n]) { let inputQuantity = priceMod.findInputQuantityByInputValue(t); if (inputQuantity && inputQuantity.length > 0) { priceModAll[productId].activeVariants[n]["quantity"] = parseInt( inputQuantity.val() ); } } else if (t.data("option-type") === "text" && t.data("data-char")) { let inputText = t[0].querySelector("input[type='text']"); if (inputText) { let value = inputText.value ?? ""; if (value) { value = value.replace(/\s/g, ""); let quantity = value.length ?? 1; priceModAll[productId].activeVariants[n]["quantity"] = quantity; } } } // quantity option addcharge if (optionType === "quantity") { let inputQuantity = t.find(".avp-quantity-input") if ( inputQuantity && inputQuantity.length > 0 && t.data("quantity-price-type") !== "any" ) { priceModAll[productId].activeVariants[n]["quantity"] = parseInt( inputQuantity.val() ?? 1 ); } } }, variantChange: async function (e, t, productId, elemOptionAvisContainer) { try { const promises = []; window.AP_POptions.$.each(t, function (t, n) { var i = $(n); if (i.data("variant-price") === 0 || i.data("variant-price")) { promises.push(priceMod.variantChangeSingle(e, i, productId)); } }); await Promise.all(promises); } catch (ex) { console.log("apo variantChange all", ex); } if (t.length) { let inputjQuery = t[0]; let optionSelector = ( inputjQuery?.length ? inputjQuery[0] : inputjQuery )?.closest(".avp-option"); if (optionSelector) { let addChargeSelector = optionSelector.querySelector( ".apo-title-addcharge" ); if ( addChargeSelector && addChargeSelector.getAttribute("use-addcharge") ) { let hasAddCharge = false; let priceAddCharge = 0; for (let item of t) { let optionName = $(item).data("variant-string"); if (optionName) { let dataAddCharge = priceModAll[productId].activeVariants[optionName]; if (dataAddCharge) { hasAddCharge = true; priceAddCharge += dataAddCharge.price * dataAddCharge.quantity; } } } addChargeSelector.innerHTML = hasAddCharge ? priceMod.formatMoneyByConfig(priceAddCharge) : ""; } priceMod.getValueSelected(optionSelector); } } if (elemOptionAvisContainer) createTotalAdd(elemOptionAvisContainer, productId); }, attachData: function (e, t, n, i, option, productId) { let isOneTime = option.is_onetime ?? false; if (priceMod.hasVariant(n)) { var o = $(e), r = priceMod.getVariantString( t, n.productVariationId, i, productId ); o.data("variant-string", r), o.data("variant-product", n.productId), o.data("variant-id", n.productVariationId), o.data("variant-price", n.price), o.data("variant-onetime", isOneTime), o.data("option-value", n.value), o.data("option-type", option.type); if (option.addcharge_per_character) o.data("data-char", true); priceModAll[productId].variantOrdering.push(r); } return e; }, postingQueue: [], postVariant: function (e, t) { var n = eventApi.beforeVariantPost({ variant: e, callback: t, properties: { _apo_parent_order: priceMod.orderId, // _apo_field_name: e.name, }, }); return ( !n && void window.AP_POptions.$.post( "/cart/add.js", { quantity: e.quantity, id: e.variantId, properties: Object.assign( e.properties ? e.properties : { _apo_parent_order: priceMod.orderId, // _apo_field_name: e.name, } ), }, function (e) { return ( spLog(e, "variant post complete", !0), e && e.variant_id ? void t() : t(new Error("Was not added to cart")) ); }, "json" ).fail(function (e, n, i) { return ( spLog({ xhr: e, status: n, error: i }, "variant post fail", !0), e && e.responseJSON && e.responseJSON.status && 422 === e.responseJSON.status ? t(e.responseJSON, !0) : void t(i) ); }) ); }, postVariants: function (e, t) { if (priceMod.postingQueue.length) { var n = priceMod.postingQueue.shift(); priceMod.postVariant(n, function (n, i) { if (n) { if (i && n.description) return ( spLog(n, "customer facing error", !0), alert(n.description), void t(n) ); spLog(n, "removing variant from current", !0); } priceMod.postVariants(e, t); }); } else t(); }, postCartVariant: function (item) { fetch("/cart/add.js", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(item), }) .then((e) => e.json()) .then((e) => { if ( e && (e.status == "bad_request" || e.status == 404 || e.status == 422 || e.status == "too_many_requests") ) { console.log("Error Avis: Add cart ", e); return { res: e, }; } else { console.log("Add change OK"); return null; } }) .catch((e) => { console.log("Error Avis: Add cart ", e); return null; }); }, postCartVariants: function (items, t) { let cartData = "add.js"; if (shop_id === "58912800936") { cartData = "add"; } fetch("/cart/" + cartData, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(items), }) .then((e) => { if (shop_id === "58912800936" && e.status === 200) { location.href = "/cart"; } // ecomify-lite theme if ( shop_id === "62635311441" || shop_id === "87122149713" || shop_id === "87195451729" || shop_id === "86549627228" || shop_id === "90301563205" ) { window.refreshCartContents(e); } return e.json(); }) .then((e) => { if ( e && (e.status == "bad_request" || e.status == 404 || e.status == 422 || e.status == "too_many_requests") ) { console.log("Error Avis: Add cart ", e); t(e); } else { console.log("Add change OK", e); t(e); } }) .catch((e) => { console.log("Error Avis: Add cart ", e); t(e); }); }, getVariantSubmissions: function (productId) { if ( priceMod.options.skipPriceModIfVisible && $(priceMod.options.skipPriceModIfVisible).is(":visible") ) return null; var e = []; if (window.AP_POptions && window.AP_POptions.pos) for (var t in priceModAll[productId].activeVariants) e.push(priceModAll[productId].activeVariants[t]); else $.each( priceModAll[productId].variantOrdering.reverse(), function (t, n) { priceModAll[productId].activeVariants[n] && priceModAll[productId].activeVariants[n].isShow && e.push(priceModAll[productId].activeVariants[n]); } ); return priceMod.alterVariantValues(e, productId); }, alterVariantValues: function (e, productId) { return ( e && e.length && priceModAll[productId].variantSubmissionAlters.length && $.each( priceModAll[productId].variantSubmissionAlters, function (t, n) { window.AP_POptions && window.AP_POptions.pos && e.forEach(function (t, n) { (t.containerId = t.$input.closest( "[data-product-options-container-id]" ).length ? t.$input .closest("[data-product-options-container-id]") .attr("data-product-options-container-id") : ""), (e[n] = t); }), (e = n(e)), e || spLog( n, "priceMod: variantSubmissionAlter did not return any values", !0 ); } ), e ); }, listInputAddBundle: [], cartSection: document.querySelector("cart-notification") || document.querySelector("cart-drawer") || document.querySelector("product-form"), addToCart: async function (productId, e, t, n) { if (shop_id === "72770978131" || shop_id === "76880183633") { let miniCart = document.querySelector("mini-cart"); if (miniCart) priceMod.cartSection = miniCart; } if (shop_id === "78803271973") { priceMod.cartSection = document.querySelector("m-cart-drawer.m-cart-drawer"); // Khách gửi code nhờ add vào đoạn xử lý add to cart document.addEventListener("DOMContentLoaded", function () { // Function to translate date format const translateDate = (startDate, endDate, lang) => { const months = { en: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], de: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"], fr: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."], tr: ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"], }; const days = { en: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], de: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], fr: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."], tr: ["Paz", "Pzt", "Sal", "Çar", "Per", "Cum", "Cmt"], }; const startDay = days[lang]?.[startDate.getDay()] || days["en"][startDate.getDay()]; const startMonth = months[lang]?.[startDate.getMonth()] || months["en"][startDate.getMonth()]; const endDay = days[lang]?.[endDate.getDay()] || days["en"][endDate.getDay()]; const endMonth = months[lang]?.[endDate.getMonth()] || months["en"][endDate.getMonth()]; return `${startDay} ${startDate.getDate()} ${startMonth} - ${endDay} ${endDate.getDate()} ${endMonth}`; }; // Function to calculate the estimated delivery date range const calculateDeliveryDate = (startDate, businessDays) => { let date = new Date(startDate); // Adjust start date if it falls on a weekend if (date.getDay() === 6) { date.setDate(date.getDate() + 2); // Move to Monday } else if (date.getDay() === 0) { date.setDate(date.getDate() + 1); // Move to Monday } let endDate = new Date(date); let remainingDays = businessDays; // Loop until we have calculated the business days while (remainingDays > 0) { date.setDate(date.getDate() + 1); const day = date.getDay(); // Skip weekends (0 = Sunday, 6 = Saturday) if (day !== 0 && day !== 6) { remainingDays--; } } // Set the end date after business days calculation endDate = new Date(date); endDate.setDate(endDate.getDate() + 1); // Adjust to the next day for the range // If the end date falls on a weekend, adjust it to Monday if (endDate.getDay() === 0) { endDate.setDate(endDate.getDate() + 1); // Skip Sunday } else if (endDate.getDay() === 6) { endDate.setDate(endDate.getDate() + 2); // Skip Saturday } return { startDate: date, endDate: endDate }; }; // Set language and shipping time using Liquid let businessDays = 5; // Default business days if (currentCountryCode === 'fr') { businessDays = 2; // France (2-3 days estimated delivery) } else if (currentCountryCode === 'de') { businessDays = 1; // Germany (1-2 days estimated delivery) } else if (currentCountryCode === 'tr') { businessDays = 4; // Turkey (4-5 days estimated delivery) } // Add 2-3 extra days for personalized products if (personalizedProductItem === true) { businessDays += 2; // Add 2 extra business days for personalized products } console.log("Country Code:", "{{ request.locale.iso_code }}"); console.log("Business Days:", businessDays); // Calculate the delivery date range const today = new Date(); // Use current date const { startDate, endDate } = calculateDeliveryDate(today, businessDays); // Translate the date range to the selected language const translatedDate = translateDate(startDate, endDate, "{{ request.locale.iso_code }}"); // Update the DOM element const deliveryDateElement = document.querySelector(".estimated_delivery--date .date"); if (deliveryDateElement) { deliveryDateElement.innerText = translatedDate; } else { console.error("Element '.estimated_delivery--date .date' not found."); } }); } n = n ? priceMod.alterVariantValues(n, productId) : priceMod.getVariantSubmissions(productId); if (priceMod.isCloneButtonAddCart) { e.preventDefault(); e.stopImmediatePropagation(); let listPrice = {}; let listVariantBundle = []; let avisAddCartFormActive = formProductGenOptionJs[productId]; let orderId = new Date().getTime(); let formButton = e.target.closest("form"); if (formButton) avisAddCartFormActive = formButton; let variantIdsSellingPlan=[]; for (var option of n) { let value = option.value; let optionData = `${option.name}: ${value} - ${option.variantId}`; let product = priceMod.productVariantBundles.find((x) => x.variants.find( (y) => String(y.id) === String(option.variantId ?? "") ) ); if (product) { let productVariant = product.variants.find( (y) => String(y.id) === String(option.variantId ?? "") ); if (productVariant) { listPrice[`${option.name}_${value}`] = (option.isOneTime ? 1 : option.quantity) * productVariant.price; if (productVariant?.selling_plan_allocations?.length > 0) { variantIdsSellingPlan.push(productVariant.id); } } } listVariantBundle.push( option.isOneTime ? optionData : `${optionData} * ${option.quantity}` ); } if (!useAddchargeApoOption && listVariantBundle.length > 0) { if (!$('[name="properties[_apo_variants]"]').length) { var variant = $("") .attr("type", "hidden") .attr("name", `properties[_apo_variants]`) .val(listVariantBundle.join(joinAddCharge)); $(e.target).before(variant); } else { $('[name="properties[_apo_variants]"]').val( listVariantBundle.join(joinAddCharge) ); } } let mainItemCart = { id: !1, quantity: 1, properties: {}, }; if (useAddchargeApoOption && n?.length) { mainItemCart.properties["_apo_order"] = orderId; } let propertiesForAc = []; let listOptionForAc = ["Numara","İsim"]; let productIdCurrent = false; if (avisAddCartFormActive?.localName === "form") { let formData = new FormData(avisAddCartFormActive); let newFormData = formData; if (typeof formData?.forEach !== "function" && newFormData?.fd) { newFormData = newFormData.fd; } newFormData?.forEach((e, t) => { if ( ("id" == t && (mainItemCart.id = parseInt(e)), "id[]" == t && !mainItemCart.id && (mainItemCart.id = parseInt(e)), "selling_plan" == t && shop_id !== "86949036357" && (mainItemCart["selling_plan"] = parseInt(e)), "selling_plan_radio" == t && (mainItemCart["selling_plan_radio"] = parseInt(e)), "product_size" == t && (productIdCurrent = parseInt(e)), "quantity" == t && (mainItemCart.quantity = parseInt(e)), t.indexOf("properties") > -1) ) { let property = t.replace("properties[", "").replace("]", ""); let keyAC = `${property}_${e}`; if (showPriceACCart) { if (listPrice[keyAC] || listPrice[keyAC] === 0) { let formatPrice = priceMod.formatMoneyOnlyPrice( parseFloat(listPrice[keyAC]), true ); mainItemCart.properties[ property ] = `${e} ${avisFormatPrice.replace( KEY_FORMAT_PRICE, formatPrice )}`; } else if (e.indexOf(",") > -1) { let listKey = []; for (let itemData of e.split(",")) { itemData = itemData.trim(); keyAC = `${property}_${itemData}`; if (listPrice[keyAC]) { let formatPrice = priceMod.formatMoneyOnlyPrice( parseFloat(listPrice[keyAC]), true ); listKey.push( `${itemData} ${avisFormatPrice.replace( KEY_FORMAT_PRICE, formatPrice )}` ); } else listKey.push(itemData); } mainItemCart.properties[property] = listKey.join(", "); } else mainItemCart.properties[property] = e; } else { if (shop_id === "78803271973" && listOptionForAc.includes(property)) { propertiesForAc.push({key:property, value: e }); } else mainItemCart.properties[property] = e; } } }); } if (productIdCurrent && !mainItemCart.id) { mainItemCart.id = productIdCurrent; } if (!mainItemCart.id) { let idSelector = avisAddCartFormActive.querySelector( ".product-variant-id" ); if (idSelector && idSelector.value) mainItemCart.id = idSelector.value; } if (!mainItemCart.id) { let idSelector = avisAddCartFormActive.querySelector("[name=id]"); if (idSelector && idSelector.value) { mainItemCart.id = idSelector.value; } } let areaStickyAc = e?.target?.closest(".sticky-add-to-cart"); if (areaStickyAc) { let formStickyAc = areaStickyAc.querySelector("form[action*='/cart/add']"); if (formStickyAc) { let formDataStickyAc = new FormData(formStickyAc); formDataStickyAc.forEach((e, t) => { if (t === "id") mainItemCart.id = parseInt(e); if (t === "quantity") mainItemCart.quantity = parseInt(e); }); } } if ($('[name="properties[_apo_variants]"]').length > 0) { $('[name="properties[_apo_variants]"]').remove(); } let isSection = window.ap_front_settings.shop_id === "72434319636" || window.ap_front_settings.shop_id === "63532892418" || window.ap_front_settings.shop_id === "79438512462" || window.ap_front_settings.shop_id === "78469497151" || window.ap_front_settings.shop_id === "60419801166" || window.ap_front_settings.shop_id === "87849468199" || window.ap_front_settings.shop_id === "17207277" || window.ap_front_settings.shop_id === "89876267357" || window.ap_front_settings.shop_id === "87489773902" || window.ap_front_settings.shop_id === "56908120127" || window.ap_front_settings.shop_id === "56047599658" || window.ap_front_settings.shop_id === "58900512837" || window.ap_front_settings.shop_id === "89688375625" || window.ap_front_settings.shop_id === "89080103205"; let sections = priceMod.cartSection?.getSectionsToRender && typeof priceMod.cartSection?.getSectionsToRender === "function" ? priceMod.cartSection .getSectionsToRender() .map((section) => (isSection ? section.section : section.id)) : []; if (sections.length === 0 && shop_id === "83553517888") { let sectionsToBundle = ["variant-added"]; document.documentElement.dispatchEvent( new CustomEvent("cart:prepare-bundled-sections", { bubbles: !0, detail: { sections: sectionsToBundle, }, }) ); sections = sectionsToBundle; } if (sections.length === 0 && shop_id === "25604915279") { document.documentElement.dispatchEvent( new CustomEvent("theme:loading:start", { bubbles: true }) ); let sectionsToBundle = []; document.documentElement.dispatchEvent( new CustomEvent("cart:prepare-bundled-sections", { bubbles: !0, detail: { sections: sectionsToBundle, }, }) ); sections = sectionsToBundle; } if (shop_id === "63324618960") { sections = "cart-icon-bubble"; let productFormData = avisAddCartFormActive.closest("product-form"); if (productFormData?.cartDrawer) { sections += `,${productFormData.cartDrawer .closest(".shopify-section") .id.replace("shopify-section-", "")}`; } } if (shop_id === "6037953") { sections = []; document.documentElement.dispatchEvent( new CustomEvent("cart:prepare-bundled-sections", { bubbles: true, detail: { sections: sections }, }) ); } // if (shop_id === "25514049590" && window.BOOMR?.themeName === "Focal") sections = ['mini-cart']; if (!sections?.length && window.BOOMR?.themeName === "Focal") { sections = ["mini-cart"]; } if (shop_id === "79936815414") { sections = ["mini-cart","cart-icon-bubble","mobile-cart-icon-bubble"]; } if (shop_id === "68666097951") { sections = ["cart-inventory-organizer","cart-items"]; } if (window.AvisOptionsData?.cartSectionInput) sections = window.AvisOptionsData?.cartSectionInput; let sections_url = window.location.pathname; let paramCartInput = { items: [], sections: sections, sections_url: sections_url, }; var uidGen = Math.floor(Math.random() * Math.floor(1e3)); uidGen += "_1"; $.each(n, function (e, t) { let optionData = `${t.name}: ${t.value} - ${t.variantId}`; let propertiesData = { _apo_added_by: t.isOneTime ? optionData : `${optionData} * ${t.quantity ?? 1}`, }; if (useAddchargeApoOption) { optionData = `Added by: ${orderId}`; propertiesData = { _apo_option: `${t.name}: ${ mainItemCart?.properties[t.name] ?? "" }`, _apo_order: t.isOneTime ? optionData : `${optionData} * ${t.quantity ?? 1}`, }; propertiesForAc?.length > 0 && propertiesForAc.forEach((x) => { propertiesData[x.key] = x.value; }); } if (shop_id === "8502476855") { propertiesData["uid"] = uidGen; if (mainItemCart.properties) mainItemCart.properties["uid"] = uidGen; } let item = { id: parseInt(t.variantId), quantity: t.isOneTime ? 1 : mainItemCart.quantity * (t.quantity ?? 1), properties: propertiesData, }; if (isNotSyncQtyProductAc && !t.isOneTime) { item.quantity = t.quantity ?? 1; } if (!["89688375625"].includes(shop_id)) { if (variantIdsSellingPlan.includes(item.id)) { if (mainItemCart["selling_plan"]) item["selling_plan"] = mainItemCart.selling_plan; if (mainItemCart["selling_plan_radio"]) item["selling_plan_radio"] = mainItemCart.selling_plan_radio; } } paramCartInput.items.push(item); }); if (shop_id === "86235251024" || shop_id === "89148653914" || shop_id === "57037127747" || shop_id === "67441852613" || shop_id === "48947986582") { for (let option of listOptions) { if ( option.required && (!mainItemCart?.properties[option.label_cart]) ) { let findOption = document.querySelector( `[field-name='${option.label_cart}']` ); if (findOption) { if (!findOption.getAttribute("disabled")) { if (findOption.value) { if (findOption.type === "radio") { findOption = document.querySelector( `[field-name='${option.label_cart}']:checked` ); if(!mainItemCart.properties[option.label_cart]) mainItemCart.properties[option.label_cart] = findOption.value; } else { if(option.type !== "file") mainItemCart.properties[option.label_cart] = findOption.value; } } else { alert( `Please fill out "${option.label_product}" before adding this item to cart` ); if (e.currentTarget) { priceMod.removeLoadingAddCart(e.currentTarget); } return null; } } } } } } paramCartInput.items.push(mainItemCart); var r = eventApi.beforeVariantsPost({ variantValues: n, orderId: priceMod.orderId, callback: t, }); return !r && priceMod.postCartVariants(paramCartInput, t); } }, resetState: function () { (priceMod.orderId = new Date().getTime()), (priceMod.options = { appendPrice: !1, skipPriceModIfVisible: "" }), (priceMod.variantOrdering = []), (priceMod.variantSubmissionAlters = []), (priceMod.activeVariants = {}); }, buyItNow: function () { let textCustomizationCostFor = "Customization Cost for"; try { textCustomizationCostFor = customizeryConfig && customizeryConfig.text_customization_cost_for ? customizeryConfig.text_customization_cost_for : "Customization Cost for"; } catch (e) { textCustomizationCostFor = "Customization Cost for"; } let options = []; if ( customizeryConfig && customizeryConfig.optionSets && customizeryConfig.optionSets.length ) { customizeryConfig.optionSets.forEach((optionSetItem) => { if (optionSetItem.options) options = options.concat(optionSetItem.options); }); } }, init: function (e) { priceMod.resetState(), $.extend(priceMod.options, e); }, }; // 3. priceModCart AvisOptionsConfig.priceMod = priceMod; var priceModCart = { form: null, cartItems: [], options: { appendPrice: !1, }, getCart: function (e) { window.AP_POptions.$.getJSON("/cart.js", function (t) { e(t); }).fail(function (e, t, n) { }); }, listCartUpdate: {}, getCartV2: async () => fetch("/cart.json?avis=1", { method: "GET" }) .then((t) => t.json()) .then((t) => t), updateCart: (t, e) => { fetch("/cart/update.js?avis=true", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(t), }) .then((t) => t.json()) .then((t) => { t && e(t); }) .catch((t) => { console.log("Error:", t); }); }, changeCart: async (t) => { let data = await fetch("/cart/change.js", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(t), }) .then((t) => { return t.json(); }) .then((t) => { return t; }) .catch((t) => { console.log("Error:", t); return false; }); return data; }, changesCart: async (t, callback) => { let isAdd = false; for (let e = 0; e < t.length; e++) { const o = t[e]; let changeCartData = await priceModCart.changeCart(o); if (changeCartData) isAdd = true; if (e === t.length - 1 && isAdd) { callback(); } } }, postUpdateCart: async function (data) { return new Promise((n, o) => { n( fetch("/cart/update.js?avis=true", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ updates: data }), }) .then((e) => e.json()) .then((e) => { return { res: e, }; }) .catch((e) => { console.log("Error Avis: Update cart ", e); return null; }) ); }); }, postChangeCart: async function (data) { return new Promise((n, o) => { n( fetch("/cart/change.js", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }) .then((e) => e.json()) .then((e) => { console.log("res change cart:", e); return { res: e, }; }) .catch((e) => { console.log("Error Avis: Update cart ", e); return null; }) ); }); }, postAddsCart: async function (data) { return new Promise((n, o) => { n( fetch("/cart/add.js", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }) .then((e) => e.json()) .then((e) => { return { res: e, key: data.key, }; }) .catch((e) => { console.log("Error Avis: Add cart ", e); return null; }) ); }); }, postAddCart: async function (data) { return new Promise((n, o) => { n( fetch("/cart/add.js?avis=apo1", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ items: [data.item] }), }) .then((e) => e.json()) .then((e) => { return { res: e, key: data.key, }; }) .catch((e) => { console.log("Error Avis: Add cart ", e); return null; }) ); }); }, init: function (e) { priceModCart.options.appendPrice = true; // Add collections of product to cart collections (Add product in cart slider (None load page cart)) if (window.ap_front_settings.product_info.collections.length > 0) { for (var clectItem of window.ap_front_settings.product_info .collections) { window.ap_front_settings.cart_collections.push({ product_id: window.ap_front_settings.product_info.product_id, collection_id: clectItem, }); } } }, }; function conditionalLogicFactory(e) { var t = this; (t.active = !1), (t.isPreview = !1), (t.watching = {}), (t.reactions = {}), (t.timers = { running: { Change: 0, React: 0 } }), (t.intervals = []); function logCondition(e, n, i) { spLog(e, n, i || !0), t.isPreview && ((n = "AvisPlus Options preview: " + n), alert(n)); } function i_fieldHide(n, elemOptionAvisContainer, productId) { let avisAddCartFormActive = formProductGenOptionJs[productId] ? $(formProductGenOptionJs[productId]) : null; function hideControl() { if (!avisAddCartFormActive) return; let clss = 'input:not([type="checkbox"]:not([avp-data="switch"])):not([disabled]),select:not([disabled]),textarea:not([disabled]),fieldset:not([disabled]),span[data-required]:not([disabled]),div[data-required]:not([disabled])'; n.$input[0].querySelectorAll(clss).forEach((x) => { let fieldName = x.getAttribute("field-name"); if (!fieldName) fieldName = x.getAttribute("name"); let newFieldName = fieldName?.replaceAll('"', """); let inputSelector = avisAddCartFormActive[0].querySelector( `input[temp-name="${newFieldName}"]` ); if (isThemeProperty) { if (inputSelector) { inputSelector.setAttribute("disabled", "disabled"); inputSelector.setAttribute( "name", `properties[${newFieldName}]` ); } } else { if (inputSelector) { inputSelector.setAttribute("disabled", "disabled"); inputSelector.removeAttribute("name"); } x.setAttribute("disabled", "disabled"); x.removeAttribute("name"); } }), window.ap_front_settings.shop_id !== "58900512837" && n.$input[0].style.setProperty("display", "none", "important"); (n.hidden = !0), eventApi.fieldHide( { reaction: n }, elemOptionAvisContainer, productId ), t.watching[n.name] && ((t.watching[n.name].hidden = !0), l_change( elemOptionAvisContainer, productId, t.watching[n.name], 0 )); } spLog(n, "conditional logic: hiding", !0), n.$input.attr({ disabled: "disabled" }).fadeTo ? n.$input .attr({ disabled: "disabled" }) .fadeTo(100, 0, function () { hideControl(); }) : (n.$input.attr({ disabled: "disabled" })[0].animate( { opacity: 0, }, { duration: 100, easing: "linear", iterations: 1, fill: "both", } ).onfinish = function () { hideControl(); }); } function o_fieldShow(n, elemOptionAvisContainer, productId) { let avisAddCartFormActive = formProductGenOptionJs[productId] ? $(formProductGenOptionJs[productId]) : null; function showControl() { if (!avisAddCartFormActive) return; let clss = 'input:not([type="checkbox"]:not([avp-data="switch"]))[disabled],select[disabled],textarea[disabled],fieldset[disabled],span[data-required][disabled],div[data-required][disabled]'; n.$input[0].querySelectorAll(clss).forEach((x) => { let fieldName = x.getAttribute("field-name"); if (!fieldName) fieldName = x.getAttribute("name"); let newFieldName = fieldName?.replaceAll('"', """); let inputSelector = avisAddCartFormActive[0].querySelector( `input[temp-name="${newFieldName}"]` ); if (isThemeProperty) { if (inputSelector) { inputSelector.removeAttribute("disabled"); } } else { if (inputSelector) { inputSelector.setAttribute( "name", `properties[${newFieldName}]` ); if (inputSelector.value) { inputSelector.removeAttribute("disabled"); } } x.removeAttribute("disabled"); x.setAttribute("name", newFieldName); } }); n.$input.show(), (n.hidden = !1), eventApi.fieldShow( { reaction: n }, elemOptionAvisContainer, productId ), t.watching[n.name] && ((t.watching[n.name].hidden = !1), l_change( elemOptionAvisContainer, productId, t.watching[n.name], 0 )); } spLog(n, "conditional logic: showing field", !0), n.$input.removeAttr("disabled").fadeTo ? n.$input.removeAttr("disabled").fadeTo(100, 1, function () { showControl(); }) : (n.$input.removeAttr("disabled")[0].animate( { opacity: 1, }, { duration: 100, easing: "linear", iterations: 1, fill: "both", } ).onfinish = function () { showControl(); }); } function compareCondition(e, t, n) { if (t && e != "greater" && e != "less") t = t.split(" [ ")[0]; switch (e) { case "contains": return !!t && t.indexOf(n) !== -1; case "not_contain": return t && t.indexOf(n) === -1; case "starts_with": return t && t.startsWith(n); case "ends_width": return t && t.endsWith(n); case "is": return t == n; case "isnot": return t != n; case "greater": return parseFloat(t) > parseFloat(n); case "less": return parseFloat(t) < parseFloat(n); default: return ( spLog(e, "conditional logic: unknown type for rule compare", !0), !1 ); } } function checkCondition(e, t, n) { if ("greater" == e || "less" == e) { try { var i = parseFloat(t), o = parseFloat(n); if (!isNaN(i) && !isNaN(o)) return compareCondition(e, i, o); } catch (a) { spLog(a, "conditional logic: greater / less error", !0); } return !1; } return ( (t = t ? t.toLowerCase() : ""), (n = n ? n.toLowerCase() : ""), compareCondition(e, t, n) ); } t.s_check_input_variant = function ( elemOptionAvisContainer, productId, productInfo ) { let watchingVariant = t.watching[key_variant_conditional]; if (!watchingVariant) return; let variants = productInfo.variants; let variantId = ""; let checkUrl = shop_id === "1991066"; if (formProductGenOptionJs[productId]?.localName === "form") { let formData = new FormData(formProductGenOptionJs[productId]); if (!checkUrl && formData && formData.get("id")) variantId = formData.get("id"); else { const searchParams = new URLSearchParams(window.location.search); if (searchParams?.get("variant")) { variantId = searchParams?.get("variant"); } } } if (!variantId) variantId = formProductGenOptionJs[productId]?.querySelector( "[name='id']" )?.value; if (!variantId) variantId = variants[0].id.toString(); let oldVariantId = selectedVariantIdAll[productId]; if (oldVariantId !== variantId) { console.log("variant change: ", variantId); selectedVariantIdAll[productId] = variantId; const findVariant = variants.find( (variant) => variant.id.toString() === variantId ); if (findVariant && findVariant?.public_title) { let value = findVariant?.public_title?.toLowerCase(); watchingVariant.value = value; e.each(watchingVariant.reactions, function (o, r) { t.reactions[r].rules[watchingVariant.name] && t.reactions[r].rules[watchingVariant.name].length ? e.each( t.reactions[r].rules[watchingVariant.name], function (e, t) { t.doesMatch = void 0; } ) : n( { watch: watchingVariant, field: r }, "conditional logic: missing reaction, name: " + watchingVariant.name + ", field: " + r ), d_react(elemOptionAvisContainer, productId, t.reactions[r]); }); } } }; function s_check_input(elemOptionAvisContainer, productId, i) { if (!i.$input) return void logCondition( i, "conditional logic: page missing input, name: " + i.name ); var o; if (i.$input.not("[disabled]").length) switch (i.input.type) { case "radio": case "button_single": o = e("input:checked", i.$input).val(); break; case "swatch": case "swatch_single_color": case "swatch_single_image": case "swatch_multi_color": case "swatch_multi_image": case "swatch_select_image": case "swatch_select_color": o = e("input:checked", i.$input) .map(function () { return e(this).val(); }) .toArray(); break; case "checkbox": case "combo_box": case "combo_select": case "combo_color": case "combo_image": case "button_multi": o = e("input:checked", i.$input) .map(function () { return e(this).val(); }) .toArray(); break; default: o = e("input:not(.iti__search-input),select,textarea", i.$input) .not('[type="hidden"]') .first() .val(); } o != i.value && ((i.value = o), e.each(i.reactions, function (o, r) { t.reactions[r].rules[i.name] && t.reactions[r].rules[i.name].length ? e.each(t.reactions[r].rules[i.name], function (e, t) { t.doesMatch = void 0; }) : logCondition( { watch: i, field: r }, "conditional logic: missing reaction, name: " + i.name + ", field: " + r ), d_react(elemOptionAvisContainer, productId, t.reactions[r]); })); } function p_rule_logic(elemOptionAvisContainer, productId, r) { if (!r.$input && !r[key_variant_conditional]) return void logCondition( r, "conditional logic: page missing input, name: " + r.name ); var s = "all" === r.logic; e.each(r.rules, function (n, i) { e.each(i, function (i, o) { if (void 0 === o.doesMatch) { var p = t.watching[n]; if (p.hidden) { o.doesMatch = false; } else { Array.isArray(p.value) ? p.value.length ? ((o.doesMatch = !1), e.each(p.value, function (e, t) { o.doesMatch = checkCondition(o.type, t, o.value) || o.doesMatch; })) : (o.doesMatch = checkCondition(o.type, "", o.value)) : (o.doesMatch = checkCondition(o.type, p.value, o.value)); } } s = "all" === r.logic ? o.doesMatch && s : o.doesMatch || s; }); }), "hide" === r.type ? s ? !r.hidden && i_fieldHide(r, elemOptionAvisContainer, productId) : r.hidden && o_fieldShow(r, elemOptionAvisContainer, productId) : s ? r.hidden && o_fieldShow(r, elemOptionAvisContainer, productId) : !r.hidden && i_fieldHide(r, elemOptionAvisContainer, productId); createTotalAdd(elemOptionAvisContainer, productId); } t.runAfterTimeouts = function (e) { e(); // var n = setInterval(function () { // if (!t.timers.running.Change && !t.timers.running.React) { // clearInterval(n); // var i = t.intervals.indexOf(n); // i !== -1 && t.intervals.splice(i, 1), e(); // } // }, 100); // t.intervals.push(n); }; function c_timer(elemOptionAvisContainer, productId, e, n, i, o) { o(elemOptionAvisContainer, productId, e); // var r = e.name + n; // t.timers[r] || t.timers.running[n]++, // clearTimeout(t.timers[r]), // (t.timers[r] = setTimeout( // function () { // delete t.timers[r], // t.timers.running[n]--, // o(elemOptionAvisContainer, productId, e); // }, // void 0 === i ? 50 : i // )); } function l_change(elemOptionAvisContainer, productId, e, t) { c_timer( elemOptionAvisContainer, productId, e, "Change", t, s_check_input ); } function d_react(elemOptionAvisContainer, productId, e, t) { c_timer( elemOptionAvisContainer, productId, e, "React", t, p_rule_logic ); } t.register = function (elemOptionAvisContainer, productId, i, o, r) { if (t.active) { if (t.reactions[i.label_cart]) { var a = t.reactions[i.label_cart]; if (a.$input) return void logCondition( { reaction: a, input: i }, "conditional logic: duplicate input, name: " + i.label_cart + ", label: " + i.label_product ); (a.$input = o), d_react(elemOptionAvisContainer, productId, a, 50); } if (t.watching[i.label_cart]) { var p = t.watching[i.label_cart]; if (p.$input) return void logCondition( { watch: p, input: i }, "conditional logic: duplicate input, name: " + i.label_cart + ", label: " + i.label_product ); (p.input = i), (p.$input = o), e.each(r, function (t, n) { var i = e(n); i.not("fieldset,input,select,textarea").length && (i = e( "fieldset,input:not(.iti__search-input),select,textarea", i ) .not('[type="hidden"]') .first()), i.is("[type=text],[type=number],textarea") && i.on("input", function (e) { l_change(elemOptionAvisContainer, productId, p); }), i.on("change", function (e) { l_change(elemOptionAvisContainer, productId, p); }), i.is("[type=radio]") && i.on("click", function (e) { l_change(elemOptionAvisContainer, productId, p); }); }), s_check_input(elemOptionAvisContainer, productId, p); } } }; function setConditionalLogicOption(n) { if ( n.conditional_logic && n.conditional_logic.condition_items && n.conditional_logic.condition_items.length ) { (t.active = !0), "uploadery" !== n.type || n.label_cart || (n.label_cart = n.stub_input_id.$oid); var i = { name: n.label_cart, logic: n.conditional_logic.logic, type: n.conditional_logic.type, hidden: !1, $input: null, rules: {}, }; return ( e.each(n.conditional_logic.condition_items, function (e, o) { t.watching[o.field] || (t.watching[o.field] = { name: o.field, value: void 0, reactions: [], }), t.watching[o.field].reactions.indexOf(n.label_cart) === -1 && t.watching[o.field].reactions.push(n.label_cart), i.rules[o.field] || (i.rules[o.field] = []), i.rules[o.field].push({ doesMatch: void 0, type: o.type, value: o.value, }); }), (t.reactions[n.label_cart] = i), i ); } } function f(n) { var i = []; return ( e.each(n, function (e, n) { return window.AP_POptions && window.AP_POptions.pos ? void (n.$input.parent(":disabled").length || i.push(n)) : void ( (t.reactions[n.name] && t.reactions[n.name].hidden) || i.push(n) ); }), i ); } function initData() { Object.keys(t.timers) .filter(function (e) { return "running" !== e; }) .forEach(function (e) { clearTimeout(t.timers[e]); }), t.intervals.forEach(function (e) { clearInterval(e); }), (t.active = !1), (t.isPreview = !1), (t.watching = {}), (t.reactions = {}), (t.intervals = []), (t.timers.running = { Change: 0, React: 0 }); } return ( (t.init = function (n, i) { i && initData(), e.each(n, function (e, t) { setConditionalLogicOption(t); }), t.active && priceMod.variantSubmissionAlters.push(f); }), t ); } function EventApi(e) { var t = this; return ( (t.subscribe = function (e, t) { "function" == typeof t && document.addEventListener("productoptions." + e, function (e) { t(e); }); }), (t.trigger = function (e, t, n) { n = !!n && n; var i = new CustomEvent(e, { detail: t, cancelable: n }); return document.dispatchEvent(i), i; }), (t.getValue = function (t, n) { var i = n.find('[name*="properties"]'), o = ""; return ( i.is( "textarea, input[type=text], input[type=number], input[type=radio]:checked, input[type=hidden]" ) ? (o = i.val()) : i.is("select") && (o = e.isArray(i.val()) ? i.val().join(",") : i.val()), o ); }), (t.appLoad = function (e) { t.trigger("productoptions.appLoad", e); }), (t.fieldLoad = function (e, productId) { e.hasBundledProducts = !1; for (var n in priceModAll[productId].activeVariants) priceModAll[productId].activeVariants[n].label_cart && priceModAll[productId].activeVariants[n].label_cart === e.fieldConfig.label_cart && (e.hasBundledProducts = !0); (e.value = t.getValue(e.fieldConfig.label_cart, e.element)), t.trigger("productoptions.fieldLoad", e); }), (t.fieldChange = function (e) { t.trigger("productoptions.fieldChange", e); }), (t.productBundleAdd = function (e) { (e.element = e.element.closest("div")), t.trigger("productoptions.productBundleAdd", e); }), (t.productBundleRemove = function (e) { (e.element = e.element.closest("div")), t.trigger("productoptions.productBundleRemove", e); }), (t.fieldShow = function (e, elemOptionAvisContainer, productId) { var n = { name: e.reaction.name, value: t.getValue(e.reaction.name, e.reaction.$input), element: e.reaction.$input, }; t.trigger("productoptions.fieldShow", n), eventApi.fieldChange({ name: e.reaction.name, value: t.getValue(e.reaction.name, e.reaction.$input), element: e.reaction.$input, }), Object.keys(priceModAll[productId].activeVariants) .filter(function (t) { return ( // priceModAll[productId].activeVariants[t].price && // priceModAll[productId].activeVariants[t].price != "" && priceModAll[productId].activeVariants[t].name === e.reaction.name ); }) .forEach(function (t) { priceModAll[productId].activeVariants[t].isShow = true; if ( priceModAll[productId].activeVariants[t].variantId && priceModAll[productId].activeVariants[t].variantId != "" ) eventApi.productBundleAdd({ name: e.reaction.name, element: e.reaction.$input, productBundle: priceModAll[productId].activeVariants[t], }); }); findButtonAddCart(elemOptionAvisContainer, productId); createTotalAdd(elemOptionAvisContainer, productId); }), (t.fieldHide = function (e, elemOptionAvisContainer, productId) { var n = { name: e.reaction.name, value: t.getValue(e.reaction.name, e.reaction.$input), element: e.reaction.$input, }; t.trigger("productoptions.fieldHide", n), eventApi.fieldChange({ name: e.reaction.name, value: "", element: e.reaction.$input, }), Object.keys(priceModAll[productId].activeVariants) .filter(function (t) { return ( // priceModAll[productId].activeVariants[t].price && // priceModAll[productId].activeVariants[t].price != "" && priceModAll[productId].activeVariants[t].name === e.reaction.name ); }) .forEach(function (t) { if ( priceModAll[productId].activeVariants[t].variantId && priceModAll[productId].activeVariants[t].variantId != "" ) eventApi.productBundleRemove({ name: e.reaction.name, element: e.reaction.$input, productBundle: priceModAll[productId].activeVariants[t], }); priceModAll[productId].activeVariants[t].isShow = false; }); findButtonAddCart(elemOptionAvisContainer, productId); createTotalAdd(elemOptionAvisContainer, productId); }), (t.validationFail = function (e) { var n = t.trigger("productoptions.validationFail", e, !0); return n.defaultPrevented; }), (t.validationSuccess = function (e) { t.trigger("productoptions.validationSuccess", e); }), (t.productBundleCartSubmit = function (e) { var n = t.trigger("productoptions.productBundleCartSubmit", e, !0); return n.defaultPrevented; }), (t.beforeVariantPost = function (e) { var n = t.trigger("productoptions.beforeVariantPost", e, !0); return n.defaultPrevented; }), (t.beforeVariantsPost = function (e) { var n = t.trigger("productoptions.beforeVariantsPost", e, !0); return n.defaultPrevented; }), t ); } var eventApi = new EventApi(window.AP_POptions.$); function spLog(e, t, n) { var i = "IO", o = "DodgerBlue"; "function" == typeof window.spLogCallback && window.spLogCallback(i, e, t, n === !0 ? o : n); try { "on" === localStorage.getItem("spLog") && console.log([i, t, e]); } catch (r) { } } function createTotalAdd(elemOptionAvisContainer, productId) { totalPriceAdd = 0; let priceAddElem = elemOptionAvisContainer.querySelector( ".avp-productoption-total-add" ); let inputTotalAddCharge = elemOptionAvisContainer.querySelector( ".apo-total-addcharge" ); if (priceModAll[productId].activeVariants) { for (const item in priceModAll[productId].activeVariants) { let typePriceQuantity = priceModAll[productId].activeVariants[item].$input.data("quantity-price-type") let priceAdd = priceMod.formatMoneyToNumber( priceModAll[productId].activeVariants[item].price ); if ( priceModAll[productId].activeVariants[item].isShow && priceAdd != "0" ) { if (typePriceQuantity && typePriceQuantity === "any") { totalPriceAdd += parseFloat(priceAdd) } else { totalPriceAdd += parseFloat(priceAdd) * parseInt( priceModAll[productId].activeVariants[item].quantity ?? 1 ); } } } if (priceAddElem) { if (totalPriceAdd > 0) { priceAddElem.classList.remove("apo-total-addcharge-hide"); let formatPrice = priceMod.formatMoney(totalPriceAdd * 100); let priceAdd = priceAddElem.querySelector( ".avp-productoption-totalpriceadd" ); if (priceAdd) priceAdd.innerHTML = formatPrice; if (inputTotalAddCharge) inputTotalAddCharge.value = totalPriceAdd * 100; } else { priceAddElem.classList.add("apo-total-addcharge-hide"); if (inputTotalAddCharge) inputTotalAddCharge.value = 0; let formatPrice = priceMod.formatMoney(totalPriceAdd * 100); let priceAdd = priceAddElem.querySelector( ".avp-productoption-totalpriceadd" ); if (priceAdd) priceAdd.innerHTML = formatPrice; } } } if (totalPriceAdd === 0 && priceAddElem) { priceAddElem.classList.add("apo-total-addcharge-hide"); } if (inputTotalAddCharge) inputTotalAddCharge.value = totalPriceAdd * 100; } const showPopupImageSwatch = (event) => { let apoSwatchPopupClass = "apo-swatch-popup"; let apoSwatchBackdropClass = "apo-swatch-backdrop"; const remove = () => { let t = document.querySelector(`.${apoSwatchPopupClass}`), e = document.querySelector(`.${apoSwatchBackdropClass}`); t && t.remove(), e && e.remove(); }; remove(); const createPopup = () => { let n = document.createElement("div"); return ( n.classList.add(apoSwatchPopupClass), n.setAttribute("style", "display:none!important"), (n.innerHTML = `
\n ×\n
`), n ); }, backDrop = () => { let t = document.createElement("div"); return ( t.classList.add(apoSwatchBackdropClass), t.setAttribute("style", "display:none!important"), t.addEventListener("click", remove.bind(this)), t ); }; let e = createPopup(), r = backDrop(); document.body.appendChild(e), document.body.appendChild(r), e .querySelectorAll(".apo-swatch-popup-close") .forEach((t) => t.addEventListener("click", remove.bind(this))); let mainImg = event.currentTarget.querySelector(".apo-main-image"); if (mainImg && mainImg.getAttribute("src")) { let imgSrc = mainImg.getAttribute("src"); let fileName = imgSrc.split("/").pop(); let newImgSrc = imgSrc.replace(fileName, "full_" + fileName); if (document.querySelector(".apo-popup-image")) document.querySelector( ".apo-popup-image" ).innerHTML = ``; e.setAttribute("style", "display:flex!important"); r.setAttribute("style", "display:block!important"); } }; const checkOptionAddCharge = (optionType) => { return ( optionType === "quantity" || optionType === "text" || optionType === "textarea" || optionType === "number" || optionType === "date" || optionType === "color" || optionType === "switch" || optionType === "file" || optionType === "phone" || optionType === "font" || optionType === "email" ); }; function handleChangeValueByQuantity(valueElm, isValue) { if (isValue !== null) valueElm.checked = isValue; if (valueElm.type === "checkbox") { if (valueElm.closest(".combo_modal")) { valueElm.dispatchEvent(new Event("change")); } else { let fieldSetCheckbox = valueElm.closest("fieldset"); if (fieldSetCheckbox) fieldSetCheckbox.dispatchEvent(new Event("change")); } } else { valueElm.dispatchEvent(new Event("change")); } } var e = { _createTotalAdd: function (elemOptionAvisContainer, productId) { createTotalAdd(elemOptionAvisContainer, productId); }, _handleChangeQuantity: async function ( event, elemOptionAvisContainer, productId ) { let elm = event.target; let parents = $(elm).parents(".avp-value-grid"); if (isQtyDefaultZero) { if (parents.length > 0) { let buttonAdd = parents.find(".avp-qty-add"); let buttonCut = parents.find(".avp-qty-cut"); let inputValue = parents.find("[field-name]"); let min = 0; if (elm.min) min = parseInt(elm.min); if (elm.getAttribute("data-min")) min = parseInt(elm.getAttribute("data-min")); let max = 0; if (elm.max) max = parseInt(elm.max); let maxTotalQuantitySetup = 0; let totalQuantity = 0; if (inputValue.length > 0) { let quantity = $(elm).val(); if (quantity) { quantity = parseInt(quantity); if (elm.max > 0 && parseInt(quantity) >= elm.max) { quantity = elm.max; $(elm).val(quantity); if (buttonAdd) buttonAdd.attr({ disabled: "disabled" }); } if (quantity <= 0 || (min && quantity < min)) buttonCut.attr({ disabled: "disabled" }); else buttonCut.removeAttr("disabled"); } else { if (buttonCut) { buttonCut.attr({ disabled: "disabled" }); } } if (inputValue[0].type === "checkbox") { let fieldSetCheckbox = inputValue[0].closest("fieldset"); if ( fieldSetCheckbox && $(fieldSetCheckbox).data("max_total_qty") ) { maxTotalQuantitySetup = parseInt( $(fieldSetCheckbox).data("max_total_qty") ); $(fieldSetCheckbox) .find(":checked") .map(function () { let quantityInput = $(this) .parents(".avp-value-grid") .find("input.avp-qty-input"); if (quantityInput && quantityInput.length > 0) { let quantity = quantityInput.val(); if (!quantity) quantity = 0; else quantity = parseInt(quantity); totalQuantity += quantity; } }); if ( totalQuantity + quantity < maxTotalQuantitySetup && (!elm.max || quantity < parseInt(elm.max)) ) { buttonAdd.removeAttr("disabled"); } else buttonAdd.attr("disabled", "disabled"); } } if (inputValue[0].checked) { if ( !quantity || quantity < min || (maxTotalQuantitySetup && totalQuantity > maxTotalQuantitySetup) ) { handleChangeValueByQuantity(inputValue[0], false); } else { await createAvisContainerHidden( elemOptionAvisContainer, productId, inputValue.attr("field-name"), quantity, inputValue, "" ); } } else { if ( quantity && quantity >= min && (!max || quantity <= max) && (!maxTotalQuantitySetup || totalQuantity + quantity <= maxTotalQuantitySetup) ) { handleChangeValueByQuantity(inputValue[0], true); } } } e._createTotalAdd(elemOptionAvisContainer, productId); } } else { let inputValue = parents.find("[field-name]"); if (inputValue.length > 0) { let quantity = $(elm).val(); if (quantity) { if (elm.max > 0 && parseInt(quantity) > elm.max) { quantity = elm.max; } if (elm.min > 0 && parseInt(quantity) < elm.min) { quantity = elm.min; } $(elm).val(quantity); } else { quantity = elm.min > 0 ? elm.min : 1; } await createAvisContainerHidden( elemOptionAvisContainer, productId, inputValue.attr("field-name"), quantity, inputValue, "", true, elm ); } e._createTotalAdd(elemOptionAvisContainer, productId); } }, _createQuantity: function ( elemOptionAvisContainer, productId, valueElement, min, max, quantityDefault = -1 ) { if (!quantityDefault) quantityDefault = -1; let elemInput = document.createElement("INPUT"); min = min ? min : 1; elemInput.setAttribute("type", "number"); if (!isQtyDefaultZero) elemInput.setAttribute("disabled", "disabled"); elemInput.classList.add("avp-qty-input"); if (min) { min = parseInt(min); if (isQtyDefaultZero) { elemInput.setAttribute("data-min", min); } else elemInput.setAttribute("min", min); } if (max) { max = parseInt(max); elemInput.setAttribute("max", max); if (!isQtyDefaultZero && quantityDefault > max) quantityDefault = max; } elemInput.setAttribute( "value", isQtyDefaultZero ? 0 : quantityDefault > min ? quantityDefault : min ); function checkMinMaxQuantity(min, max, inputElem) { let valueInput = parseInt(inputElem.value); if (min && valueInput < min) { inputElem.value = min; inputElem.dispatchEvent(new Event('input')); } if (max && valueInput > max) { inputElem.value = max; inputElem.dispatchEvent(new Event('input')); } } elemInput.addEventListener('blur', () => checkMinMaxQuantity(min, max, elemInput)); elemInput.removeEventListener("input", (event) => { e._handleChangeQuantity(event, elemOptionAvisContainer, productId); }); elemInput.addEventListener("input", (event) => { e._handleChangeQuantity(event, elemOptionAvisContainer, productId); }); let elemInputJq = window.AP_POptions.$(elemInput); elemInputJq.on("keypress", function (e) { var t = String.fromCharCode(e.which); return Boolean(t.match(/[0-9]/)); }); // elemInputJq.on("blur", async function (e) { // let elm = e?.currentTarget; // if (!elm?.value) { // let quantity = 1; // let min = elm.getAttribute("min"); // if (min && parseInt(min) > 0) quantity = min; // elm.value = quantity; // } // }); let buttonCut = window.AP_POptions.$("") .addClass("avp-qty-button") .addClass("avp-qty-cut") .attr({ disabled: "disabled" }) .html(``); buttonCut.on("click", async function (event) { event.preventDefault(); let parents = $(this).parents(".avp-value-grid"); if (parents.length > 0) { let inputValue = parents.find("[field-name]"); if (inputValue.length > 0) { let inputQuantity = parents.find(".avp-qty-input"); if (inputQuantity.length > 0) { let quantity = inputQuantity.val(); if (!quantity) quantity = 1; quantity = parseInt(quantity) - 1; if (isQtyDefaultZero) { let isNotSelect = inputValue[0].getAttribute("data-type") !== "select" && inputValue[0].getAttribute("data-type") !== "swatch_select_color" && inputValue[0].getAttribute("data-type") !== "swatch_select_image"; // Button cut DISABLE when quantity <=0 or (<=1 is select) if (quantity <= 0 || (quantity <= 1 && !isNotSelect)) { $(this).attr({ disabled: "disabled" }); } else { $(this).removeAttr("disabled"); } if (min && quantity < min) { quantity = 0 $(this).attr({ disabled: "disabled" }); } inputQuantity.val(quantity); if (inputValue[0].checked) { if (quantity < parseInt(min) && isNotSelect) { // inputValue[0].checked = false; handleChangeValueByQuantity(inputValue[0], false); } else { await createAvisContainerHidden( elemOptionAvisContainer, productId, inputValue.attr("field-name"), quantity, inputValue, "", true ); } } else { if (quantity >= parseInt(min) && isNotSelect) { // inputValue[0].checked = true; handleChangeValueByQuantity(inputValue[0], true); } else { await createAvisContainerHidden( elemOptionAvisContainer, productId, inputValue.attr("field-name"), quantity, inputValue, "", true ); } } } else { if (quantity <= parseInt(min)) { quantity = min; $(this).attr({ disabled: "disabled" }); } inputQuantity.val(quantity); await createAvisContainerHidden( elemOptionAvisContainer, productId, inputValue.attr("field-name"), quantity, inputValue, "", true ); } } } e._createTotalAdd(elemOptionAvisContainer, productId); } }); let buttonAdd = window.AP_POptions.$("") .addClass("avp-qty-button") .addClass("avp-qty-add") .html(``); if (!isQtyDefaultZero) buttonAdd.attr({ disabled: "disabled" }); buttonAdd.on("click", async function (event) { event.preventDefault(); let parents = $(this).parents(".avp-value-grid"); if (parents.length > 0) { let inputValue = parents.find("[field-name]"); if (inputValue.length > 0) { let inputQuantity = parents.find(".avp-qty-input"); if (inputQuantity.length > 0) { let quantity = inputQuantity.val(); if (isQtyDefaultZero) { let isNotSelect = inputValue[0].getAttribute("data-type") !== "select" && inputValue[0].getAttribute("data-type") !== "swatch_select_color" && inputValue[0].getAttribute("data-type") !== "swatch_select_image"; if (!quantity) quantity = 0; quantity = parseInt(quantity) + 1; if (max && quantity >= parseInt(max)) { quantity = max; $(this).attr({ disabled: "disabled" }); } inputQuantity.val(quantity); if (quantity >= 0) { let btnCut = parents.find(".avp-qty-cut"); if (btnCut?.length) { if (quantity < min) {} else btnCut.removeAttr("disabled"); } } if ( min && quantity >= parseInt(min) && !inputValue[0].checked && isNotSelect ) { // inputValue[0].checked = true; handleChangeValueByQuantity(inputValue[0], true); } else { let isNotChangeHidden = (!inputValue[0].checked && quantity < min) || (max && quantity > max); if (!isNotChangeHidden) { await createAvisContainerHidden( elemOptionAvisContainer, productId, inputValue.attr("field-name"), quantity, inputValue, "", true ); } else { if (inputValue[0].type === "checkbox") { let fieldSetCheckbox = inputValue[0].closest("fieldset"); if ( fieldSetCheckbox && $(fieldSetCheckbox).data("max_total_qty") ) { let maxQuantity = parseInt( $(fieldSetCheckbox).data("max_total_qty") ); let totalQuantity = 0; $(fieldSetCheckbox) .find(":checked") .map(function () { let quantityInput = $(this) .parents(".avp-value-grid") .find("input.avp-qty-input"); if (quantityInput && quantityInput.length > 0) { let quantity = quantityInput.val(); if (!quantity) quantity = 0; else quantity = parseInt(quantity); totalQuantity += quantity; } }); if ( totalQuantity + quantity < maxQuantity && (!max || quantity < parseInt(max)) ) { buttonAdd.removeAttr("disabled"); } else buttonAdd.attr("disabled", "disabled"); } } } } } else { if (!quantity) quantity = 1; quantity = parseInt(quantity) + 1; if (max && quantity >= parseInt(max)) { quantity = max; $(this).attr({ disabled: "disabled" }); } inputQuantity.val(quantity); await createAvisContainerHidden( elemOptionAvisContainer, productId, inputValue.attr("field-name"), quantity, inputValue, "", true ); } } } e._createTotalAdd(elemOptionAvisContainer, productId); } }); let qtyWrapper = window.AP_POptions.$("
") .addClass("avp-qty-wrapper") .append(buttonCut) .append(elemInputJq) .append(buttonAdd); let result = window.AP_POptions.$("
") .addClass("avp-value-grid") .append( window.AP_POptions.$("
") .addClass("avp-value-grid-item") .append(valueElement) ) .append( window.AP_POptions.$("
") .addClass("avp-value-grid-item") .append(qtyWrapper) ); return result; }, _createNewSwatchImageItem: function(option, optionValue, swatchItemHtml){ let optionValueText = swatchItemHtml; let imageUrl = optionValue?.swatch?.file_image_url; let borderRadius = ""; if (option.swatch_shape === "circle") { borderRadius = "border-radius: 50% !important;"; } swatchItemHtml = ` `; let textTooltipSwatch = ""; let isShowTooltip = false; let showHoverImage = !customizeryConfig?.hide_hover_img_swatches; if (option.tooltip_display === "value") { textTooltipSwatch = optionValue.value; isShowTooltip = true; } else if (option.tooltip_display === "desc") { textTooltipSwatch = optionValue.des_value; isShowTooltip = true; } if (!isShowTooltip && option.tooltip_display && // showHoverImage && imageUrl) { isShowTooltip = true; } let tooltipSwatch = ""; let tooltipPrice = "" if(optionValue?.price > 0) { tooltipPrice = priceMod.formatMoney(parseFloat(optionValue?.price), true); } if (isShowTooltip) { if (imageUrl) tooltipSwatch = ` `; if (textTooltipSwatch) { let customTextTooltipSwatch = textTooltipSwatch if (shop_id === '65999732917' && tooltipPrice) { customTextTooltipSwatch += ` (+${tooltipPrice})` } if(shop_id ==='10278593' && tooltipPrice){ customTextTooltipSwatch += ` (${tooltipPrice})` } tooltipSwatch += `${customTextTooltipSwatch}`; } if (tooltipSwatch) { tooltipSwatch = `
${tooltipSwatch}
`; tooltipSwatch += ""; } } let hiddenHoverImg = customizeryConfig?.hide_hover_img_swatches ? " hover-img-hidden-mobile" : ""; let html = tooltipSwatch ? `
${swatchItemHtml}${tooltipSwatch}
` : swatchItemHtml; let p = window.AP_POptions.$(`
${html}${optionValueText}
`); if (isShowTooltip) { e.hoverTooltip(p[0].querySelector(".avp-productoptionswatch-box")); } return p; }, _createRadioButton: function ( elemOptionAvisContainer, productId, option, t, n, i, quantityDefault, isOnlyUrl ) { var o = priceMod.getValueText(t, option), r = window.AP_POptions.$("") .attr("type", "radio") .attr("field-name", option.label_cart) .attr( "name", isNotUseAvisHidden ? `properties[${option?.label_cart}]` : option?.label_cart ) .attr("value", o.value) .attr("autocomplete", "off") .addClass("avp-productoptiontextcolor") .addClass("avp-productoptionbackground") .on("click", async function (t, n) { if (isOnlyUrl) { t.target ?.closest("label") ?.querySelector(".apo-swatch-url") ?.click(); return; } if ( priceModAll[productId].radioInput && priceModAll[productId].radioInput[option.label_cart] && priceModAll[productId].radioInput[option.label_cart].value === t.target.value ) { let isNotUncheck = (["72549466396","87350903133","70874595579"].includes(shop_id)) && option.required if ( (window.ap_front_settings.shop_id === "67366289656" && window.ap_front_settings.shop_id === "88343970095" && (option?.type === "radio" || option?.type === "button_single")) || isNotUncheck ) { } else $(this).prop("checked", false); await createAvisContainerHidden( elemOptionAvisContainer, productId, option.label_cart, "", $(this) ); priceModAll[productId].radioInput[option.label_cart].value = ""; eventApi.fieldChange({ name: option.label_cart, value: "", element: $(this).closest("div"), }); i(t); let spanRequired = $(this).closest( "span[data-required='true']" ); if (spanRequired && spanRequired.length) { window.AP_POptions.apps.productoptions.toggleInputError( spanRequired, !0 ); } e._createTotalAdd(elemOptionAvisContainer, productId); } findButtonAddCart(elemOptionAvisContainer, productId); }) .on("change", async function (t, n) { if (isOnlyUrl) return; n || eventApi.fieldChange({ name: option.label_cart, value: t.target.value, element: $(this).closest("div"), }), i(t); if ($(this).prop("checked")) { if ( t.currentTarget.closest(".avp-productoptionswatchwrapper") && t.currentTarget.closest(".apo-custom-wrapper") ) { let imgSelector = t.currentTarget .closest(".avp-productoptionswatchwrapper") .querySelector(".avp-productoptionswatch"); if (imgSelector && imgSelector.getAttribute("data-src")) { let src = imgSelector.getAttribute("data-src"); let mainImageSelector = t.currentTarget .closest(".apo-custom-wrapper") .querySelector(".apo-main-image"); mainImageSelector.setAttribute("src", src); } } priceModAll[productId].radioInput[option.label_cart] = { value: t.target.value, }; await createAvisContainerHidden( elemOptionAvisContainer, productId, option.label_cart, t.target.value, $(this) ); } else { priceModAll[productId].radioInput[option.label_cart] = { value: "", }; await createAvisContainerHidden( elemOptionAvisContainer, productId, option.label_cart, "", $(this) ); } let spanRequired = $(this).closest("span[data-required='true']"); if (spanRequired && spanRequired.length) { window.AP_POptions.apps.productoptions.toggleInputError( spanRequired, !0 ); } e._createTotalAdd(elemOptionAvisContainer, productId); findButtonAddCart(elemOptionAvisContainer, productId); }); if (t?.soldout) { r.attr("disabled", "disabled"); } if (isNotUseAvisHidden && option.required) r.attr("required", "required"); let swatchItem = o.display; let spanValue = ["radio", "checkbox"].includes(option.type) && option.tooltip_display && t?.swatch?.file_image_url ? e._createNewSwatchImageItem(option, t, swatchItem) : swatchItem; let valueWrapper = null; if (n) { let valueElement = window.AP_POptions.$("") .addClass("avp-productoptioncheckwrapper") .addClass( `avp-productoptioncheckwrapper${customizeryConfig?.customize_options?.radio_btn?.shape === "pill" || option.type === "button_single" ? " avp-pilloptioncheckwrapper" : "" }` ) .append( priceMod.attachData( r, option.label_cart, t, o.display, option, productId ) ) .append(spanValue); if (t?.soldout) { valueElement.addClass(AVIS_CLASS.soldOutOption); valueElement.attr("title", AVIS_SOLD_OUT); } if (option.show_option_value_qty) { valueWrapper = e._createQuantity( elemOptionAvisContainer, productId, valueElement, option.min_value_qty, option.max_value_qty, quantityDefault ); } else valueWrapper = valueElement; } (customizeryConfig?.customize_options?.radio_btn?.shape === "pill" || option.type === "button_single") && r.css({ display: "none" }); return n ? valueWrapper : r; }, _createComboButton: function ( elemOptionAvisContainer, productId, option, t, n, valueDefault, quantityDefault ) { function getValueText(option) { return priceMod.getValueText(t, option); } function createCheckbox(value, labelCart, isChecked, isDisabled) { return window.AP_POptions.$("") .attr("type", "checkbox") .attr("value", value) .attr("field-name", labelCart) .attr("autocomplete", "off") .attr( "name", isNotUseAvisHidden ? `properties[${labelCart}]` : labelCart ) .addClass("avp-productoptiontextcolor avp-productoptionbackground") .prop("checked", isDisabled ? false : isChecked) .prop("disabled", isDisabled); } function createColorBox(color) { return window.AP_POptions.$("
") .addClass("option-avis-combo_color-box") .attr("style", `background-color: ${color} !important`); } function createImgBox(src) { if (src) { return window.AP_POptions.$("") .addClass("option-avis-combo_image-box") .attr("src", src); } else { return window.AP_POptions.$("
").addClass( "option-avis-combo_image-box" ); } } function updateCheckboxState(valueElement, isChecked) { let iconTick = null; if ( ["combo_color", "combo_image", "combo_select"].includes(option.type) ) { iconTick = window.AP_POptions.$("").addClass( "option-avis-checkmark" ); } if (isChecked) { if (option.show_option_value_qty) { valueElement .closest(".avp-value-grid") .addClass("option-avis-checked"); } else { valueElement.addClass("option-avis-checked"); } if ( !valueElement.find(".option-avis-checkmark").length && iconTick ) { valueElement.append(iconTick.clone()); } } else { if (option.show_option_value_qty) { valueElement .closest(".avp-value-grid") .removeClass("option-avis-checked"); } else { valueElement.removeClass("option-avis-checked"); } valueElement.find(".option-avis-checkmark")?.remove(); } } function handleCheckboxChange(o, valueElement) { o.on("change", function () { updateCheckboxState(valueElement, this.checked); }); } const valueText = getValueText(option); const checkbox = createCheckbox( valueText.value, option.label_cart, valueDefault, t?.soldout ); if ( [ "combo_color", "combo_image", "combo_select", ].includes(option.type) ) { checkbox.css({ display: "none" }); } let valueWrapper = null; if (n) { const colorBox = createColorBox( option?.option_values?.find((opt) => opt.value === valueText?.value) ?.swatch?.color || "transparent" ); const imgBox = createImgBox( option?.option_values?.find((opt) => opt.value === valueText?.value) ?.swatch?.file_image_url || "" ); const valueElement = window.AP_POptions.$("") .addClass("avp-productoptioncheckwrapper") .addClass( option.type !== "combo_box" ? " avp-pilloptioncheckwrapper" : "" ) .append( priceMod.attachData( checkbox, option.label_cart, t, valueText.display, option, productId ) ) .append( option.type === "combo_image" ? imgBox : "", option.type === "combo_color" ? colorBox : "", valueText.display ); if ( [ "combo_select", "combo_image", "combo_color", "combo_box", ].includes(option.type) ) { valueElement.css("cursor", "pointer"); updateCheckboxState(valueElement, checkbox.is(":checked")); handleCheckboxChange(checkbox, valueElement); } valueWrapper = option.show_option_value_qty ? e._createQuantity( elemOptionAvisContainer, productId, valueElement, option.min_value_qty, option.max_value_qty, quantityDefault ) : valueElement; let gridValue = valueElement.closest(".avp-value-grid"); gridValue.on("click", function () { handleCheckboxChange(checkbox, valueElement); }); gridValue.find(".avp-qty-wrapper").on("click", function (event) { event.stopPropagation(); }); } return n ? valueWrapper : checkbox; }, _createCheckboxButton: function ( elemOptionAvisContainer, productId, option, t, n, valueDefault, quantityDefault ) { var i = priceMod.getValueText(t, option), o = window.AP_POptions.$("") .attr("type", "checkbox") .attr("value", i.value) .attr("field-name", option.label_cart) .attr("autocomplete", "off") .attr( "name", isNotUseAvisHidden ? `properties[${option?.label_cart}]` : option?.label_cart ) .addClass("avp-productoptiontextcolor") .addClass("avp-productoptionbackground"); if (t?.soldout) { o.attr("disabled", "disabled"); } else if (valueDefault) o.attr("checked", "checked"); (customizeryConfig?.customize_options?.checkbox?.shape === "pill" || option.type === "button_multi") && o.css({ display: "none" }); let swatchItem = i.display; let spanValue = ["radio", "checkbox"].includes(option.type) && option.tooltip_display && t?.swatch?.file_image_url ? e._createNewSwatchImageItem(option, t, swatchItem) : swatchItem; let valueWrapper = null; if (n) { let valueElement = window.AP_POptions.$("") .addClass("avp-productoptioncheckwrapper") .addClass( `avp-productoptioncheckwrapper${customizeryConfig?.customize_options?.checkbox?.shape === "pill" || option.type === "button_multi" ? " avp-pilloptioncheckwrapper" : "" }` ) .append( priceMod.attachData( o, option.label_cart, t, i.display, option, productId ) ) .append(spanValue); if (t?.soldout) { valueElement.addClass(AVIS_CLASS.soldOutOption); valueElement.attr("title", AVIS_SOLD_OUT); } if (option.show_option_value_qty) { valueWrapper = e._createQuantity( elemOptionAvisContainer, productId, valueElement, option.min_value_qty, option.max_value_qty, quantityDefault ); } else valueWrapper = valueElement; } return n ? valueWrapper : o; }, _createSelectMenu: function ( elemOptionAvisContainer, productId, t, n, i, o, r, optionDefaultValues, option ) { var a = window.AP_POptions.$('
'), result = null, s = window.AP_POptions.$( '' ) .attr("id", r) .attr("name", isNotUseAvisHidden ? `properties[${t}]` : t) .attr("autocomplete", "off") .attr("field-name", t) .attr("data-type", option?.type); let isOnlyUrl = option.option_url === OPTION_URL.group || option.option_url === OPTION_URL.only; if ((o && s.attr("required", "required"), void 0 !== i && "" !== i)) { if ( navigator.userAgent.toLowerCase().indexOf("firefox") > -1 && !e.ffCssFix ) { var p = ".avp-select select:invalid { box-shadow: none; }", c = document.head || document.getElementsByTagName("head")[0], l = document.createElement("style"); (l.type = "text/css"), l.styleSheet ? (l.styleSheet.cssText = p) : l.appendChild(document.createTextNode(p)), c.appendChild(l), (e.ffCssFix = !0); } s.append( window.AP_POptions.$("") .attr("value", i.value) .attr("apo-url", valueUrl && isOnlyUrl ? valueUrl : "") .html(i.display); if (n?.soldout) { o.attr("disabled", "true"); } else if (valueDefault) optionDefaultSelected = o; let handle = valueUrl?.split("/")?.pop(); if ( isOnlyUrl && handle === window.ap_front_settings?.product_info?.product?.handle ) { o.attr("selected", true); isOptionUrlSelected = true; } s.append( priceMod.attachData(o, t, n, i.display, option, productId) ); } }), !isOptionUrlSelected && optionDefaultSelected ? optionDefaultSelected.attr("selected", true) : "", // s.prop("field-name", t), // s.prop("name", t), s.on("change", async function (event, n) { if (isOnlyUrl) { let urlHref = event?.target?.selectedOptions[0]?.getAttribute("apo-url"); if (urlHref) { let handle = urlHref?.split("/")?.pop(); if ( handle !== window.ap_front_settings?.product_info?.product?.handle ) { location.href = urlHref; } } return; } window.AP_POptions.apps.productoptions.toggleInputError(s, !0), n || eventApi.fieldChange({ name: t, value: event.target.value, element: $(this).closest("div:not(.avp-select)"), }); var i = $("option", s); priceMod.variantChange(t, i, productId); await createAvisContainerHidden( elemOptionAvisContainer, productId, t, event.target.value, s ); e._createTotalAdd(elemOptionAvisContainer, productId); findButtonAddCart(elemOptionAvisContainer, productId); })), a.append(s), (result = option.show_option_value_qty ? e._createQuantity( elemOptionAvisContainer, productId, a, option.min_value_qty, option.max_value_qty ) : a), s.trigger("change", ["onLoad"]), result ); }, _createSelectSwatch: function ( elemOptionAvisContainer, productId, option ) { let fieldName = option?.label_cart; let quantityDefault = 1; let isOnlyUrl = option.option_url === OPTION_URL.group || option.option_url === OPTION_URL.only; function genValuesHtml() { let valuesHtml = ""; if (option?.option_values && option?.option_values.length > 0) { let index = 0; let existDefault = false; let isFirstValueDefault = false; let firstValuesHtml = ""; for (let optionValue of option?.option_values) { let isColor = option.type === "swatch_select_color"; let colorSwatch = ""; let imgSwatch = ""; if (isColor) colorSwatch = optionValue?.swatch?.color; else imgSwatch = optionValue?.swatch?.file_image_url; let styleBox = isColor ? `background:${optionValue.swatch.color};` : "background-image: url('" + (optionValue.swatch.file_image_url ? optionValue.swatch.file_image_url : optionValue.url_image) + "');"; let classHiddenSwatchTitle = priceMod.classHiddenSwatchTitle( priceMod.isHiddenSwatchTitle(option) ); var valueText = priceMod.getValueText(optionValue, option); let isDefault = false; if (option?.is_option_default_value) { let optionDefaultValue = option?.option_default_value; if (optionDefaultValue?.indexOf(optionValue.value_id) > -1) { isDefault = true; existDefault = true; if (index === 0) isFirstValueDefault = true; } else if (optionDefaultValue) { let arrValue = optionDefaultValue.split(" * "); let newValue = arrValue[0].trim(); if (optionValue.value.trim() === newValue) { isDefault = true; existDefault = true; if (index === 0) isFirstValueDefault = true; if (arrValue.length > 1) quantityDefault = parseInt(arrValue[1]); } } } if(isOnlyUrl && optionValue.url) { let currentUrl = decodeURIComponent(window.location.pathname)?.split('/')?.pop(); let newUrl = decodeURIComponent(optionValue.url)?.split('/')?.pop(); if (newUrl && newUrl?.split("?")[0].toLowerCase() === currentUrl.toLowerCase()) { existDefault = true; isDefault = true; } } if (optionValue?.soldout) { if (isDefault) { existDefault = false; isFirstValueDefault = false; } isDefault = false; } let swatchValueItem = `
 
${typeof valueText?.display === "string" ? valueText?.display : valueText?.display[0]?.innerHTML }
`; let valueUrl = ""; if (isOnlyUrl) { valueUrl = optionValue?.url?.trim(); if (valueUrl && isOnlyUrl) { swatchValueItem = `${swatchValueItem}`; } } if (index === 0) { firstValuesHtml = `
  • `; } else { valuesHtml += `
  • `; } if (index === option.option_values.length - 1) { if (option?.placeholder) { firstValuesHtml = firstValuesHtml.replace("@@checked@@", existDefault && isFirstValueDefault ? "checked" : ""); valuesHtml = `
  • ${firstValuesHtml} ${valuesHtml}`; } else { firstValuesHtml = firstValuesHtml.replace( "@@checked@@", existDefault && !isFirstValueDefault ? "" : optionValue?.soldout ? "" : "checked" ); valuesHtml = `${firstValuesHtml} ${valuesHtml}`; } } index++; } } return valuesHtml; } let wrapperSelector = document.createElement("div"); wrapperSelector.classList.add("option-avis-dropdown-inner"); let html = `
    ${option?.placeholder ? option?.placeholder : "" }
    `; wrapperSelector.innerHTML = html; let selectedSelector = wrapperSelector.querySelector( ".option-avis-swatch-drop-down" ); let ulSelector = wrapperSelector.querySelector( "ul.option-avis-dropdown-values" ); document.addEventListener("click", function () { if ("block" == getComputedStyle(ulSelector).display) { Object(priceMod.toggleSelector)(ulSelector); } }); selectedSelector.addEventListener("click", function (e) { e.preventDefault(), e.stopPropagation(), Object(priceMod.toggleSelector)( selectedSelector.nextElementSibling ); }); if (isOnlyUrl) { let currentSelected = ulSelector.querySelector("li.option-avis-value input[type='radio']:checked"); if (currentSelected) { currentSelected.addEventListener("change", async function (event) { event.preventDefault(); event.stopPropagation(); let spanRequired = $(this).closest("div[data-required='true']"); if (spanRequired && spanRequired.length) { window.AP_POptions.apps.productoptions.toggleInputError( spanRequired, !0 ); } let listInput = []; ulSelector .querySelectorAll("li.option-avis-value input") .forEach((item) => { listInput.push($(item)); }); let selectedText = wrapperSelector.querySelector( ".option-avis-dropdown-view-value .option-avis-swatch-value-title" ); let selectedBox = wrapperSelector.querySelector( ".option-avis-dropdown-view-value .option-avis-swatch-value-box" ); let liSelector = event.target.closest(".option-avis-value"); if (liSelector) { if (selectedText) { selectedText.innerHTML = liSelector.querySelector( ".option-avis-swatch-value-title" )?.innerHTML; } if (selectedBox) { selectedBox.setAttribute( "style", liSelector.querySelector(".option-avis-swatch-value-box") ?.dataset?.style ); } } }); currentSelected.dispatchEvent(new CustomEvent("change")); } } !isOnlyUrl && ulSelector .querySelectorAll("li.option-avis-value") .forEach(function (t) { t.addEventListener("click", function (e) { e.preventDefault(); e.stopPropagation(); Object(priceMod.toggleSelector)(ulSelector); if ( t .querySelector('input[type="radio"]') .getAttribute("disabled") ) return; t.querySelector('input[type="radio"]').checked = true; t.querySelector('input[type="radio"]').dispatchEvent( new CustomEvent("change") ); }); let inputSelector = t.querySelector("input"); inputSelector.addEventListener("change", async function (event) { event.preventDefault(); event.stopPropagation(); let spanRequired = $(this).closest("div[data-required='true']"); if (spanRequired && spanRequired.length) { window.AP_POptions.apps.productoptions.toggleInputError( spanRequired, !0 ); } let listInput = []; ulSelector .querySelectorAll("li.option-avis-value input") .forEach((item) => { listInput.push($(item)); }); let selectedText = wrapperSelector.querySelector( ".option-avis-dropdown-view-value .option-avis-swatch-value-title" ); let selectedBox = wrapperSelector.querySelector( ".option-avis-dropdown-view-value .option-avis-swatch-value-box" ); let liSelector = event.target.closest(".option-avis-value"); if (liSelector) { if (selectedText) { selectedText.innerHTML = liSelector.querySelector( ".option-avis-swatch-value-title" )?.innerHTML; } if (selectedBox) { selectedBox.setAttribute( "style", liSelector.querySelector(".option-avis-swatch-value-box") ?.dataset?.style ); } } if (isOnlyUrl) { return; } priceMod.variantChange(fieldName, listInput, productId); await createAvisContainerHidden( elemOptionAvisContainer, productId, fieldName, event.target.value, $(this) ); e._createTotalAdd(elemOptionAvisContainer, productId); }); if ( inputSelector.dataset.index > -1 && inputSelector.dataset.index < option.option_values.length ) { let textSelector = t.querySelector( ".option-avis-swatch-value-title" ); priceMod.attachData( inputSelector, fieldName, option.option_values[inputSelector.dataset.index], textSelector.innerHTML, option, productId ); } }); let result = $(wrapperSelector); if (option.show_option_value_qty) { result = e._createQuantity( elemOptionAvisContainer, productId, $(wrapperSelector), option.min_value_qty, option.max_value_qty, quantityDefault ); } if (isOnlyUrl) { for (let inputSelector of ulSelector.querySelectorAll( "li.option-avis-value input[data-apo-url]" )) { let urlHref = inputSelector?.getAttribute("data-apo-url"); if (urlHref) { let handle = urlHref?.split("/")?.pop(); if ( handle === window.ap_front_settings?.product_info?.product?.handle ) { let selectedText = wrapperSelector.querySelector( ".option-avis-dropdown-view-value .option-avis-swatch-value-title" ); let selectedBox = wrapperSelector.querySelector( ".option-avis-dropdown-view-value .option-avis-swatch-value-box" ); let liSelector = inputSelector.closest(".option-avis-value"); if (liSelector) { if (selectedText) { selectedText.innerHTML = liSelector.querySelector( ".option-avis-swatch-value-title" )?.innerHTML; } if (selectedBox) { selectedBox.setAttribute( "style", liSelector.querySelector(".option-avis-swatch-value-box") ?.dataset?.style ); } } inputSelector.checked = true; break; } } } } else { let inputChecked = wrapperSelector.querySelector(":checked"); if (inputChecked) { inputChecked.dispatchEvent(new CustomEvent("change")); } } return result; }, _createHiddenInput: function ( elemOptionAvisContainer, productId, e, isProperty = false ) { let newFieldName = e?.replaceAll('"', """); var t = window.AP_POptions.$("") .attr("type", "hidden") .attr("name", isProperty ? "properties[" + e + "]" : e); if (!isProperty) { t.attr("field-name", e); } else t.attr("temp-name", newFieldName); if (!isProperty) { createAvisContainerHidden(elemOptionAvisContainer, productId, e, ""); } return t; }, hoverTooltip: function (optionValueSelector) { optionValueSelector.addEventListener("mouseover", function (event) { let bodyTooltip = document.querySelector(".avis-body-tooltip"); if (bodyTooltip) { let findTooltip = optionValueSelector.querySelector(".apo-swatch-tooltip"); let findArrowTooltip = optionValueSelector.querySelector(".apo-swatch-arrow"); let swatchPositionData = optionValueSelector.getBoundingClientRect(); let arrowAppend = true; if (findTooltip) { if (!bodyTooltip.querySelector(".apo-swatch-tooltip")) { let cloneFindTooltip = findTooltip.cloneNode(true); bodyTooltip.appendChild(cloneFindTooltip); let findTooltipPosition = cloneFindTooltip.getBoundingClientRect(); let top = swatchPositionData.top + window.scrollY - findTooltipPosition.height - 8; let left = swatchPositionData.left + window.scrollX + (swatchPositionData.width/2) - (findTooltipPosition.width/2) ; let maxRight = window.innerWidth; if (left < window.scrollX) left = window.scrollX; if (left + findTooltipPosition.width > maxRight) { left = maxRight - findTooltipPosition.width - 10; } if (top - window.scrollY < 0) { top = swatchPositionData.top + window.scrollY + swatchPositionData.height; arrowAppend = false; } bodyTooltip.setAttribute("style", `top: ${top}px; left:${left}px;`); document.body.classList.add("avis-add-tooltip"); } if (findArrowTooltip) { if (!bodyTooltip.querySelector(".apo-swatch-arrow")) { let clonefindArrowTooltip = findArrowTooltip.cloneNode(true); if (arrowAppend) { clonefindArrowTooltip.classList.add("apo-swatch-arrow-top"); clonefindArrowTooltip.classList.remove("apo-swatch-arrow-bottom"); bodyTooltip.appendChild(clonefindArrowTooltip); } else { clonefindArrowTooltip.classList.remove("apo-swatch-arrow-top"); clonefindArrowTooltip.classList.add("apo-swatch-arrow-bottom"); bodyTooltip.prepend(clonefindArrowTooltip); } } } } } let avisContainerSelector = optionValueSelector.closest( `.${container_AP_POptions}` ), avisPosition = avisContainerSelector.getBoundingClientRect(); // t let swatchPosition = optionValueSelector.getBoundingClientRect(); let tooltipSelector = optionValueSelector.querySelector( ".apo-swatch-tooltip" ); let tooltipArrowSelector = optionValueSelector.querySelector(".apo-swatch-arrow"); let arrowHeight = tooltipArrowSelector?.getBoundingClientRect()?.height || 0; if (tooltipSelector) { let tooltipPosition = tooltipSelector.getBoundingClientRect(); if (swatchPosition.left < avisPosition.left) { tooltipSelector.setAttribute("style","left: 50%"); return; } let positionRight = window.innerWidth - avisPosition.right; let swatchRight = window.innerWidth - swatchPosition.right; let swatchHaft = swatchPosition.width / 2; let tooltipHaft = tooltipPosition.width / 2; let calPositionLeft = swatchPosition.left - avisPosition.left + swatchHaft; if (shop_id === "70071189821" && window.innerWidth > 700) { tooltipSelector.setAttribute("style","left: 50% !important"); } else { if (calPositionLeft < tooltipHaft) { tooltipSelector.setAttribute("style", `left: calc(50% + ${ tooltipHaft - (swatchPosition.left - avisPosition.left + swatchHaft) }px) !important;`); } else { calPositionLeft = swatchRight - positionRight + swatchHaft; if (calPositionLeft < tooltipHaft) { tooltipSelector.setAttribute("style", `left: calc(50% - ${ tooltipHaft - (swatchRight - positionRight + swatchHaft) }px) !important;`); } else tooltipSelector.setAttribute("style","left: 50%"); } } let tooltipHeight = tooltipPosition.height; let calTop = swatchPosition.top - arrowHeight; if (tooltipHeight > calTop) { tooltipSelector.classList.remove("apo-swatch-tooltip-top"); tooltipSelector.classList.add("apo-swatch-tooltip-bottom"); tooltipArrowSelector.classList.remove("apo-swatch-arrow-top"); tooltipArrowSelector.classList.add("apo-swatch-arrow-bottom"); } else { tooltipSelector.classList.remove("apo-swatch-tooltip-bottom"); tooltipSelector.classList.add("apo-swatch-tooltip-top"); tooltipArrowSelector.classList.remove("apo-swatch-arrow-bottom"); tooltipArrowSelector.classList.add("apo-swatch-arrow-top"); } } }); optionValueSelector.addEventListener("mouseout", function(event){ let bodyTooltip = document.querySelector(".avis-body-tooltip"); if (bodyTooltip) { bodyTooltip.innerHTML = ""; document.body.classList.remove("avis-add-tooltip"); } }); }, handleChangeElement: function ( elemOptionAvisContainer, productId, event, maxLength, minLength, textTransform ) { event.preventDefault(); var elm = event.target; var config = window.AP_POptions.apps.productoptions; var allowValue = elm.getAttribute("data-allow-value"); var labelCart = elm.getAttribute("field-name"); var value = elm.value; maxLength && value.length > maxLength && ((value = value.substr(0, maxLength)), (elm.value = value)); minLength && value.length < minLength && ((value = value.substr(0, minLength)), (elm.value = value)); if (allowValue && value) { if ( allowValue == "only_letters" && config.allowedValueLetterRegex.test(value) ) { } else if ( allowValue == "only_letters_and_numbers" && config.allowedValueLetterNumberRegex.test(value) ) { } else config.toggleInputError($(elm), !0); } else config.toggleInputError($(elm), !0); if (value && textTransform && textTransform === "Uppercase") { value = value.toLocaleUpperCase(); elm.value = value; } if (value && textTransform && textTransform === "Lowercase") { value = value.toLocaleLowerCase(); elm.value = value; } if (value && textTransform && textTransform === "Capitalize") { let words = value.split(" "); for (let index in words) { words[index] = words[index][0].toUpperCase() + words[index].substr(1); } value = words.join(" "); elm.value = value; } var parent = elm.closest(".apo-text-field"); if (parent) { let counterLetter = parent.querySelector(".apo-counter-input"); if (counterLetter) { counterLetter.innerText = value.length; } priceMod.variantChange( labelCart, [$(parent)], productId, elemOptionAvisContainer ); } else { priceMod.variantChange( labelCart, [$(elm)], productId, elemOptionAvisContainer ); } createAvisContainerHidden( elemOptionAvisContainer, productId, labelCart, value ); findButtonAddCart(elemOptionAvisContainer, productId); }, handleChangeQuantity: function ( elemOptionAvisContainer, productId, event, ) { event.preventDefault(); var elm = event.target; var labelCart = elm.getAttribute("field-name"); var value = elm.value; var parent = elm.closest(".apo-text-field"); if (parent) { priceMod.variantChange( labelCart, [$(parent)], productId, elemOptionAvisContainer ); } else { priceMod.variantChange( labelCart, [$(elm)], productId, elemOptionAvisContainer ); } createAvisContainerHidden( elemOptionAvisContainer, productId, labelCart, value ); findButtonAddCart(elemOptionAvisContainer, productId); }, handleChangeElementPhone: function ( elemOptionAvisContainer, productId, event ) { const elm = event.target; const labelCart = elm.getAttribute("field-name"); const input = document.getElementById(elm.id); const phoneInput = window.apoPhoneInputGlobals .getInstance(input) .getNumber(); var parent = elm.closest(".apo-text-field"); if (parent) { priceMod.variantChange( labelCart, [$(parent)], productId, elemOptionAvisContainer ); } else { priceMod.variantChange( labelCart, [$(elm)], productId, elemOptionAvisContainer ); } createAvisContainerHidden( elemOptionAvisContainer, productId, elm.getAttribute("field-name"), phoneInput ); findButtonAddCart(elemOptionAvisContainer, productId); }, _createTextInput: function ( elemOptionAvisContainer, productId, labelCart, valueDefault, placeholder, maxLength, minLength, required, id, option ) { let textTransform = option["text_transform"]; let allowValue = option["allow_value"]; maxLength = maxLength && parseInt(maxLength, 10) > 0 ? parseInt(maxLength, 10) : 0; minLength = minLength && parseInt(minLength, 10) > 0 ? parseInt(minLength, 10) : 0; var elemInput = document.createElement("INPUT"); elemInput.setAttribute("type", "text"); elemInput.setAttribute("field-name", labelCart); elemInput.setAttribute( "name", isNotUseAvisHidden ? `properties[${labelCart}]` : labelCart ); elemInput.setAttribute("id", id); elemInput.setAttribute("autocomplete", "off"); elemInput.classList.add("avp-productdescfont"); elemInput.classList.add("avp-productoptiontextcolor"); elemInput.classList.add("avp-productoptionbackground"); if (textTransform && textTransform === "Uppercase") elemInput.classList.add("avp-text-transform-uppercase"); if (textTransform && textTransform === "Lowercase") elemInput.classList.add("avp-text-transform-lowercase"); if (textTransform && textTransform === "Capitalize") elemInput.classList.add("avp-text-transform-capitalize"); elemInput.removeEventListener("input", (event) => e.handleChangeElement( elemOptionAvisContainer, productId, event, maxLength, minLength, textTransform ) ); elemInput.addEventListener("input", (event) => { e.handleChangeElement( elemOptionAvisContainer, productId, event, maxLength, minLength, textTransform ); }); if (shop_id === "77859357001") { elemInput.addEventListener("change", (event) => { e.handleChangeElement( elemOptionAvisContainer, productId, event, maxLength, minLength, textTransform ); }); } var textField = document.createElement("span"); textField.classList.add("apo-text-field"); textField.appendChild(elemInput); if (maxLength && maxLength > 0) { const counterLetter = document.createElement("span"); counterLetter.classList.add("apo-counter-letter"); var countText = valueDefault ? valueDefault.length : elemInput.value.length; counterLetter.innerHTML = `${countText}/${maxLength}`; textField.appendChild(counterLetter); elemInput.style.paddingRight = "60px"; } if (minLength && minLength > 0) { const minLetter = document.createElement("span"); minLetter.classList.add("apo-min-letter"); minLetter.innerHTML = customizeryConfig?.text_customization_notification_min_characters ? customizeryConfig?.text_customization_notification_min_characters.replace( "{min_length}", minLength ) : `Type at least ${minLength} characters`; textField.appendChild(minLetter); } let elemInputJq = window.AP_POptions.$(elemInput); return ( void 0 !== placeholder && "" !== placeholder && elemInputJq.prop("placeholder", placeholder), maxLength && elemInputJq.prop({ maxlength: maxLength, size: maxLength }), minLength && elemInputJq.prop({ minLength: minLength }), required && elemInputJq.attr("required", "required"), allowValue && allowValue != "default" && elemInputJq.attr("data-allow-value", allowValue), void 0 !== valueDefault && "" !== valueDefault && elemInputJq.val(valueDefault), createAvisContainerHidden( elemOptionAvisContainer, productId, labelCart, valueDefault ), $(textField) ); }, _createQuantityInput: function ( elemOptionAvisContainer, productId, labelCart, valueDefault, placeholder, id, quantity_label, min_value_qty, max_value_qty, add_price_quantity_type, hide_price, option_show_price, price, required ) { var elemInput = document.createElement("input"); elemInput.setAttribute("type", "number"); elemInput.setAttribute("min", min_value_qty ?? "1"); elemInput.setAttribute("max", max_value_qty ?? ""); elemInput.setAttribute("field-name", labelCart); elemInput.setAttribute( "name", isNotUseAvisHidden ? `properties[${labelCart}]` : labelCart ); elemInput.setAttribute("id", id); elemInput.setAttribute("autocomplete", "off"); elemInput.classList.add("avp-productdescfont"); elemInput.classList.add("avp-productoptiontextcolor"); elemInput.classList.add("avp-productoptionbackground"); elemInput.classList.add("avp-quantity-input"); elemInput.removeEventListener("input", (event) => e.handleChangeQuantity( elemOptionAvisContainer, productId, event, ) ); elemInput.addEventListener("input", (event) => { e.handleChangeQuantity( elemOptionAvisContainer, productId, event, ); }); function checkMinMaxQuantity(min, max, inputElem) { let valueInput = parseInt(inputElem.value); if (min && valueInput < min) { inputElem.value = min; inputElem.dispatchEvent(new Event('input')); } if (max && valueInput > max) { inputElem.value = max; inputElem.dispatchEvent(new Event('input')); } } elemInput.addEventListener('blur', () => checkMinMaxQuantity(min_value_qty, max_value_qty, elemInput)); let titleSpan = document.createElement("span"); titleSpan.classList.add("avp-quantity-title") if (!hide_price && option_show_price !== "only_label" && parseFloat(price)) { titleSpan.innerHTML = `${quantity_label ?? ""} ${priceMod.priceMarkup(parseFloat(price))}`; } else { titleSpan.innerHTML = quantity_label ?? "" } let quantityContainer = document.createElement("div"); quantityContainer.classList.add("apo-text-field") add_price_quantity_type && quantityContainer.setAttribute("data-quantity-price-type", add_price_quantity_type); quantityContainer.append(titleSpan, elemInput) let elemInputJq = window.AP_POptions.$(elemInput); return ( void 0 !== placeholder && "" !== placeholder && elemInputJq.prop("placeholder", placeholder), void 0 !== valueDefault && "" !== valueDefault && elemInputJq.val(valueDefault), required && elemInputJq.prop("required", required), createAvisContainerHidden( elemOptionAvisContainer, productId, labelCart, valueDefault ), $(quantityContainer) ); }, _createPhoneInput: function ( elemOptionAvisContainer, productId, labelCart, valueDefault, placeholder, isRequired, valueCountry, id ) { var elemInput = document.createElement("INPUT"); elemInput.setAttribute("type", "text"); elemInput.setAttribute("field-name", labelCart); elemInput.setAttribute( "name", isNotUseAvisHidden ? `properties[${labelCart}]` : labelCart ); elemInput.setAttribute("id", id); elemInput.setAttribute("autocomplete", "off"); elemInput.classList.add("avp-productdescfont"); elemInput.classList.add("avp-productoptiontextcolor"); elemInput.classList.add("avp-productoptionbackground"); if (isRequired) elemInput.setAttribute("required", isRequired); elemInput.removeEventListener("input", (event) => e.handleChangeElementPhone(elemOptionAvisContainer, productId, event) ); elemInput.addEventListener("input", (event) => { e.handleChangeElementPhone(elemOptionAvisContainer, productId, event); }); var textField = document.createElement("span"); textField.classList.add("apo-text-field"); textField.appendChild(elemInput); let phoneInput = window.apoPhoneInput(elemInput, { initialCountry: valueCountry ? valueCountry.toLocaleLowerCase().trim() : "us", utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@21.0.8/build/js/utils.js", showSelectedDialCode: true, customPlaceholder: function (selectedCountryPlaceholder) { return placeholder ? placeholder : selectedCountryPlaceholder; }, }); elemInput.addEventListener("keyup", () => { let isValid = phoneInput.isValidNumberPrecise(); if (isValid) { elemInput.classList.remove("invalid-phone-number"); } else { elemInput.classList.add("invalid-phone-number"); } }); elemInput.addEventListener("keydown", function (event) { // Allow backspace, delete, tab, escape, enter, and arrow keys const allowedKeys = [ "Backspace", "Delete", "Tab", "Escape", "Enter", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Decimal", ]; if ( allowedKeys.includes(event.key) || // Allow shortcuts: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X, Command+A/C/V/X ((event.key === "a" || event.key === "c" || event.key === "v" || event.key === "x") && (event.ctrlKey || event.metaKey)) ) { // Let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if (!event.key.match(/^\d$/)) { event.preventDefault(); } }); return ( createAvisContainerHidden( elemOptionAvisContainer, productId, labelCart, valueDefault ), $(textField) ); }, _createTextArea: function ( elemOptionAvisContainer, productId, labelCart, t, n, maxLength, o, r, allowValue, textTransform, minLength ) { maxLength = maxLength && parseInt(maxLength, 10) > 0 ? parseInt(maxLength, 10) : 0; minLength = minLength && parseInt(minLength, 10) > 0 ? parseInt(minLength, 10) : 0; var a = window.AP_POptions.$("