console.log('widebundle loaded'); if(typeof wideBundle == 'undefined' && Shopify && Shopify.shop == 'berg2026.myshopify.com'){ var wideBundle = wideBundle || {}; wideBundle.settings = {"id":"94601","shop":"berg2026.myshopify.com","charge_id":"26528448586","status":"active","price":"14.99","currency":"\u20ac{{amount}}","currency_format":"mix","option1_title":"Select your offer:","atc_background":"#699e04","hover_color":"#699e04","atc_color":"#ffffff","atc_text":"IN DEN WARENKORB LEGEN","atc_font_size":"1.2em","atc_font":"auto","atc_radius":"10px","atc_size":"medium","atc_animation":"no","border_color":"#699e04","border_size":"2px","unselected_border_size":"2px","border_radius":"5px","unselected_border_radius":"5px","option_select_color":"#000000","option_select_background":"#ffffff","option_select_default_settings":"0","background_color":"#d8f5a3","price_color":"#699e04","price_compared_color":"#3a3a3a","price_size":"0.9em","unselected_price_fontsize":"0.9em","unselected_compare_price_fontsize":"0.9em","selected_price_fontsize":"0.9em","selected_compare_price_fontsize":"0.9em","offer_color":"#3a3a3a","title_best":"Best Offer!","color_best":"#cb3600","link_choice":"cart","installed":"1","affiliate_id":"0","ref":null,"onboarding":"{\"steps\":{\"1\":1,\"2\":1,\"3\":1,\"4\":1,\"5\":0}}","notifications":"0","economic_color":"#3a3a3a","economic_text":"","economic_display":"0","selected_savings_fontsize":"0.9em","unselected_savings_fontsize":"0.9em","option_color":"#000000","option_fontsize":"0.8em","rtl":"0","enabled":"1","review":"0","onboarding_guided":"1","ask_referal":"1","price_separator":".","form_id":"form[action='\/cart\/add']","price_id":":not(.wb_hidden_prices_element) .price","select_id":"0","email_given":"0","email_perso":null,"before_code":"","after_code":"","trustbadge":"","offer_selected_color":"#3a3a3a","best_selected_color":"#cb3600","message_border_size":"0px","unselected_message_border_size":"0px","message_border_color":"#000000","unselected_message_border_color":"#000000","message_border_radius":"0px","unselected_message_border_radius":"0px","message_background_color":"#ffffff","unselected_message_background_color":"#ffffff","message_background_transparency":"00","unselected_message_background_transparency":"00","unselected_free_gift_text_color":"#000000","unselected_free_gift_text_style":"none","unselected_free_gift_background_color":"#f4f4f4","unselected_free_gift_icon_color":"#000000","selected_free_gift_text_color":"#000000","selected_free_gift_text_style":"none","selected_free_gift_background_color":"#f4f4f4","selected_free_gift_icon_color":"#000000","price_selected_color":"#699e04","price_compared_selected_color":"#3a3a3a","economic_selected_color":"#000000","update_price":"1","design_code":"0","svg_number":"0","svg_size":"1.2em","display_quantity":"0","bg_button_quantity":"#ffffff","color_button_quantity":"#000000","bg_input_quantity":"#ffffff","color_input_quantity":"#000000","style_blinking":"none","style_title":"none","style_economic":"none","style_price":"none","style_compared_price":"none","style_variants_selected":"bold","style_blinking_selected":"bold","style_title_selected":"bold","selected_title_fontsize":"1.2em","unselected_title_fontsize":"1.2em","style_economic_selected":"bold","style_price_selected":"bold","preview_heading_color":"#000000","preview_heading_position":"left","preview_heading_font_size":"0.9em","preview_heading_font_style":"none","heading_line_color":"#000000","heading_line_size":"2px","heading_line_display":"0","style_compared_price_selected":"bold","offers_heading_font_size":"0.9em","auto_round":"0","country_code":"US","shopify_plan":"shopify_plus","no_decimal":"0","add_pixel":"1","utm_source":"","custom_css":"p.title-variant {\n font-size: 1em !important;\n}\n#ProductSection-product-template > div > div:nth-child(2) > div.product-single__meta > ul {\ndisplay: none !important;\n}","currency_code":"EUR","shop_creation":"2026-01-10 12:19:46","shop_id":"68769513546","referer":"Used before","plan":"incremental","partner_test_store":"0","thumbnail_size":"m","thumbnail_color":"#e9e9e9","unselected_thumbnail_size":"m","unselected_thumbnail_color":"#e9e9e9","unselected_border_color":"#c6c6c6","unselected_background_color":"#ffffff","unselected_background_transparency":"00","font_unselected_custom_sentence":"auto","font_selected_custom_sentence":"auto","selected_custom_fontsize":"0.9em","unselected_custom_fontsize":"0.9em","unselected_title_text_color":"#000000","unselected_title_text_bg":"#ffffff","unselected_title_text_size":"0.6em","unselected_title_text_border":"#000000","unselected_title_text_radius":"0px","unselected_title_text_style":"none","unselected_title_text_font":"auto","selected_title_text_color":"#000000","selected_title_text_bg":"#ffffff","selected_title_text_size":"0.6em","selected_title_text_border":"#000000","selected_title_text_radius":"0px","selected_title_text_style":"none","selected_title_text_font":"auto","atc_content_text":"Ausverkauft","enable_atc_button":"0","current_amount":"0","current_additional_usd":"0.00","legacy_additional_usd":"0.00","billing_cycle":"2026-03-25","current_sales":"1340","legacy_amount":null,"priority_support":"0","advanced_price":null,"priority_price":null,"color_best_banner":"#cb3600","best_selected_color_banner":"#cb3600","js_code":null,"onboarding_closing":"0","widereview_closing":"0","integrations_closing":"0","scopes":"read_themes,read_products,write_products,read_orders,write_discounts,read_inventory,write_inventory,read_shipping,read_locations,read_locales,unauthenticated_read_product_listings,unauthenticated_read_product_inventory","banners_closing":"0","shopify_discount_id":"0","discount_label":"product_offer","translations":null,"notification_closing":"0","unselected_free_gift_text_fontsize":"1em","selected_free_gift_text_fontsize":"1em","round_prices_automatic":"0","is_hook_collection_delete":"1","design_info_closing":"0","first_bundle_sale":"0","storefront_token":"cd96ed5bb88b273ce5fec3438b14b2e6","dg_choose_btn_text":"W\u00e4hlen Sie ein Produkt","dg_popup_heading_text":"W\u00e4hlen Sie das Produkt, das Sie in diesem Bundle m\u00f6chten"}; wideBundle.domain = 'https://widebundle.com/'; wideBundle.shop = wideBundle.settings.shop; wideBundle.templates = []; wideBundle.templates = Object.keys(wideBundle.templates).map(key => wideBundle.templates[key]); wideBundle.ipHash = 856939341; wideBundle.targetProductSearch = {"batch":4,"index":222,"product":{"id":"gid:\/\/shopify\/Product\/8125740122186","legacyResourceId":"8125740122186","handle":"alpaca-barfussschuh-stroeer","title":"Alpaca - ergonomischer, wasserdichter Leder-Barfu\u00dfschuh"}}; console.log('WB targetProductSearch:', wideBundle.targetProductSearch); //Get the position of word in url function posInUrl(text, subStrings) { var positions = {}; subStrings.forEach(subString => { positions[subString] = text.indexOf(encodeURI(subString)); }); return positions; } //Check if a child is descendant of a parent function isDescendant(parent, child){ if(!parent){ return false; } let node = child.parentNode; while (node != null) { if (node === parent) { return true; } node = node.parentNode; } return false; }; //Get closest parent form function getClosestParentForm(child){ let node = child.parentNode; while (node) { if (node.tagName === "FORM") { return node; } node = node.parentNode; } return null; } //Add some style to the page function addStyleToPage(styles, attribute = ''){ var wbAttribute = 'wb-default-style'; if (attribute !== '') { wbAttribute = 'wb-' + attribute + '-style'; } var css = document.createElement('style'); css.setAttribute(wbAttribute, ''); css.type = 'text/css'; if (css.styleSheet) css.styleSheet.cssText = styles; else css.appendChild(document.createTextNode(styles)); if (!document.querySelector(`[${wbAttribute}]`)) { document.getElementsByTagName("head")[0].appendChild(css); } } //Check if string is json function isJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } //Get SVG codes function AddSVG(){ var size = wideBundle.settings.svg_size; var color = wideBundle.settings.atc_color; var svg = wideBundle.settings.svg_number; if(svg == 1){ svgCode = ''; return svgCode; } else if(svg == 2){ svgCode = ' '; return svgCode; } else if(svg == 3){ svgCode = ' '; return svgCode; } else if(svg == 4){ svgCode = ' '; return svgCode; } else if(svg == 5){ svgCode = ''; return svgCode; } else{ return ''; } } //Get base URL function getShopifyBaseUrl() { if (Shopify?.routes?.root) { return Shopify.routes.root; } return "/"; } //Compare 2 arrays function arraysEqual(_arr1, _arr2) { if (!Array.isArray(_arr1) || ! Array.isArray(_arr2) || _arr1.length !== _arr2.length) return false; var arr1 = _arr1.concat().sort(); var arr2 = _arr2.concat().sort(); for (var i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) return false; } return true; } //Check if a text contains only numbers function containsOnlyNumbers(text) { return /^\d+$/.test(text); } function wbHtmlentities(rawStr) { return rawStr.toString().replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } function wbEscapeSwatchValue(rawStr) { if (typeof rawStr !== 'string') { return rawStr; } // Escape special characters for use in attribute selectors return rawStr .replace(/\\/g, '\\\\') // Escape backslashes first .replace(/"/g, '\\"') // Escape double quotes .replace(/'/g, "\\'") // Escape single quotes .replace(/\//g, '\\/') // Escape forward slashes .replace(/\[/g, '\\[') // Escape opening square brackets .replace(/\]/g, '\\]') // Escape closing square brackets .replace(/\^/g, '\\^') // Escape caret .replace(/\$/g, '\\$') // Escape dollar sign .replace(/\*/g, '\\*') // Escape asterisk .replace(/\(/g, '\\(') // Escape opening parenthesis .replace(/\)/g, '\\)') // Escape closing parenthesis .replace(/\s/g, '\\ '); // Escape spaces } //Send the event change on element function fireChangeEvent(node){ if('createEvent' in document){ var evt = document.createEvent('HTMLEvents'); evt.initEvent('change', false, true); node.dispatchEvent(evt); } else{ node.fireEvent('onchange'); } setTimeout(function() { if('createEvent' in document){ var evt = document.createEvent('HTMLEvents'); evt.initEvent('change', false, true); node.dispatchEvent(evt); } else{ node.fireEvent('onchange'); } }, 100); } //Trigger mouse event function triggerMouseEvent (node, eventType) { var clickEvent = document.createEvent ('MouseEvents'); clickEvent.initEvent (eventType, true, true); node.dispatchEvent (clickEvent); } //Dispatch click event function dispatchClick(node){ if('createEvent' in document){ var evt = document.createEvent('HTMLEvents'); evt.initEvent('click', false, true); node.dispatchEvent(evt); } else{ node.fireEvent('click'); } setTimeout(function() { if('createEvent' in document){ var evt = document.createEvent('HTMLEvents'); evt.initEvent('click', false, true); node.dispatchEvent(evt); } else{ node.fireEvent('click'); } }, 100); } //Frire un event function eventFire(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } //Some shops are using this function even if we don't need it anymore at least it won't send an error function showAndReduceForm() { return; } //Copy style from an element to another function copyStyle(sourceElement, targetElement) { const sourceStyle = window.getComputedStyle(sourceElement); for (let i = 0; i < sourceStyle.length; i++) { const styleProperty = sourceStyle[i]; targetElement.style[styleProperty] = sourceStyle.getPropertyValue(styleProperty); } const styleSheets = document.styleSheets; //For hover for (const styleSheet of styleSheets) { let cssRules; try { cssRules = styleSheet.cssRules; } catch (e) { // Skip CORS protected stylesheets continue; } for (const cssRule of cssRules) { if (cssRule.selectorText && cssRule.selectorText.includes(':hover')) { const sourceSelector = cssRule.selectorText.replace(':hover', '').trim(); if (sourceElement.matches(sourceSelector)) { const targetSelector = sourceSelector + '[data-copied-style="true"]'; const hoverStyle = cssRule.cssText.replace(cssRule.selectorText, targetSelector); const styleElement = document.createElement('style'); styleElement.innerHTML = hoverStyle; document.head.appendChild(styleElement); targetElement.setAttribute('data-copied-style', 'true'); break; } } } } } function AddGoogleFont(fontFamily) { if (!document.querySelector(`link[data-wb-font="${fontFamily}"]`)) { const link = document.createElement("link"); link.setAttribute("data-wb-font", fontFamily); link.rel = "stylesheet"; link.type = "text/css"; link.href = `https://fonts.googleapis.com/css2?family=${fontFamily.replace(/\s/g, "+")}:ital,wght@0,400;0,700;1,400;1,700&display=swap`; document.head.appendChild(link); } } function GetLoadingGifBase64() { return "data:image/gif;base64,R0lGODlhPAA8APMAAOjo6NPT09fX19vb29/f3+Dg4Ofn5+jo6Ozs7PLy8vn5+QAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQJCgAAACH/C0ltYWdlTWFnaWNrDmdhbW1hPTAuNDU0NTQ1ACH+KU9wdGltaXplZCB3aXRoIGh0dHBzOi8vZXpnaWYuY29tL29wdGltaXplACwAAAAAPAA8AAAE/xDISau9OOvNu/9glyRhaU7jeK5emrKskrkqhsCZousXTVqIg/CGq+x4Ft9FyCwaj7KKssJsOifQKGVKqQqv2KyURvUSwQDxljwJetEUtYQL8B7gcTnXzTzj01AobHVvMEcYWVFTdn4UBgUFBhxyeYcAi4UVj5CQkjmJWmGHSoyam5yRG6ChgJYuEnZdp6gFdxqrSBKBF3y2ErO0npO4ujsafb+0qMIfxCbKnAa+Ic4gwJ3MJ6Al19mGu9bLeJbcnX/nzbi5MAQD7u/wAwQW6pQlBO3x+vLzovXr9/YJ7FfsH8AQ+QTGI9jKIIuECt8xbKgOB8SBBdBpVHXQwwABAp3+2OvwEaSAAWC2hRAQwCRIlDhWlWDp0mQMmSVK1nxZomLBW7l2uoTZwSdFROR0CiX6SWVBYw2frlN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NDU0NQAsAAAAADwAPACDAAAA19fX29vb39/f4ODg5+fn6Ojo7Ozs8vLy9fX1+fn5/Pz8AAAAAAAAAAAAAAAABP8QyEmrvTjrzbv/YHccYWlORmqcrHeoBtmySaa+8rXOGOIjNctomKMYCMgCz/LzXYijC3K6rDSdFVjMUpgiq5QrwqItSrxfsCQhzkIrXa9SLWkb3xT0nA5gXylEWxNoBHxhV0EAQyk5cVN7hgB2ijA5hDwKmQo9dmUSjkkYA6OFG5kLC5kXnZVnaFICsbGlGJqpthV+TZQ3AKAEkAAEA7ICxLS1CqiaylZ/ijiujxXEsdXHpsq3p6mHPxigFNXGxcYey8y3C2vfGXE74+XmINvazCfE8dbIIMz+6yH0kRuAyV+zgPlkEQRjsES8hXTumRg1gF+kixrSoZPIg6LHjxDyJygzyM0WwBMCAqhcybJlhZEk6x080bJmSwEUUMnUWe+kCZtAVebkqU6nvxYpg7YMCYCkUx7yos7DSDWDzhOaImlbVqIhw1Ngu5ZUVZCkWKNZWaA9KnYr235u33LNkLbpWo4cTPIk2xQmho0i//HsoHGZT69GJWzcFLiwzwsy6zZOi05xPQsGb2mIfCEd47WKbTF+6ZUuXgpeU+8djfp0MtMcS682zePuBMPdLL81NPv23tauvxIFPleC3sdfuZG2R3own9KT+YoEHHG3cet2g8/AbndbZ+0tuMf9Ljn5X+qYpVf17X09XPDuk6mPT7/+jAgAOw=="; } // Pre-calculate the CRC32 lookup table once function wbMakeCRCTable() { let c; const crcTable = []; for (let n = 0; n < 256; n++) { c = n; for (let k = 0; k < 8; k++) { // PHP's crc32 uses the reflected polynomial (0xEDB88320) and reflected input/output // JavaScript's bitwise right shift (>>>) is necessary for unsigned operations c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1); } crcTable[n] = c; } return crcTable; } /** * Calculates a CRC32 checksum compatible with PHP's crc32() function. * Note: PHP's crc32() works on bytes, so the input string should be treated as bytes (e.g., UTF-8 encoded). * @param {string} str - The input string (treated as UTF-8 byte sequence). * @returns {number} - The unsigned 32-bit integer CRC32 checksum. */ function wb_php_crc32(str) { // 1. Convert the string to a Uint8Array (UTF-8 byte representation) const bytes = new TextEncoder().encode(str); // 2. Initialize CRC value to 0xFFFFFFFF (inverted initial value) // The -1 trick in JS is a compact way to get 0xFFFFFFFF as a signed 32-bit integer let crc = -1; for (let i = 0; i < bytes.length; i++) { // 3. XOR the current CRC byte with the next data byte // Bitwise AND 0xFF is to ensure we only use the lower 8 bits of the byte const byte = bytes[i] & 0xFF; // 4. Update the CRC value using the lookup table crc = (crc >>> 8) ^ wbCRCTable[(crc ^ byte) & 0xFF]; } // 5. Final XOR with 0xFFFFFFFF and convert to unsigned 32-bit integer // The >>> 0 converts the result from a signed 32-bit integer to its unsigned 32-bit representation (a positive number). return (crc ^ (-1)) >>> 0; } const wbCRCTable = wbMakeCRCTable(); //Function to create tags for all used Google fonts wideBundle.loadGoogleFonts = function(){ const settingsKeys = ["atc_font", "font_unselected_custom_sentence", "font_selected_custom_sentence"]; settingsKeys.forEach(function (key) { if (wideBundle.settings[key] != "auto") { AddGoogleFont(wideBundle.settings[key]); } }); }; //Function to get the Add To Cart Button wideBundle.getAddToCartButton = function(){ //Add to cart button selectors in the form var submitButtons = [ "gp-product-button button", ".bettercart_checkout.elm_pos_0", ".bettercart_checkout", ".add-to-cart-first", ".add_to_cart", ".button--add-to-cart", ".shg-btn", "button[data-pf-type='ProductATC2']", "input[type='submit']", ".smart-wrapper .add-to-cart-btn#AddToCartDesk", ".btn--add-to-cart", ".product-form__item--submit .product-form__cart-submit", ".gt_product-button", ".add", "button#addToCartCopy", 'button[data-name="Product Button"]', ".paymentButtonsWrapper button[type='submit']", "button[type='submit']", ".gf_add-to-cart", "button[data-pf-type=\"ProductATC\"]", "button.add-to-cart", ".product-form__submit", "button.single_add_to_cart_button", '.tt-wrapper .btn-addtocart', '#AddToCart', 'button.product-submit', '.button--addToCart', '.product__buy .product__add-to-cart', "button[class*='f-buy-buttons']", ".product-buy-buttons--cta", 'button[data-replo-repeated-index][role="button"]', ".form-actions button[data-product-add].button.button-secondary", "button[data-replo-add-product-variant-to-cart]", ".product-form__buttons #submitProduct[name='add']", "a#add-to-cart-btn.product--addtocart", "x-buy-button.x-product-buy-button[type='submit']", "button[id*='buy_group_add_to_cart_template--'].smi-button-wrapper", ".mm-main-product-CTA-container .mm-btn-secondary", "product-buy-buttons-element button.product-buy-buttons--primary" ]; //exceptions var buttonsExceptions = [ ".spr-button", "#judgeme_product_reviews" ]; if(wideBundle.formInfo.element){ findButton: for(i=0; i elements var selsWB = [ ".single-option-selector", ".variant__input-product-template:not(input[type=\"radio\"])", ".single-option-selector-product-template", ".single-option-selector__radio.product-form__input", ".shg-product-variant-select", ".product-form__single-selector", "gp-product-variants select", ".AddToCartForm .gf_variants", ".product-form__controls-group .product-form__option select", ".option-selectors .selector-wrapper select", "select.pf-variant-select", ".product-form__input select.select__select", "div[data-product-options-container] .form-field-select-wrapper .form-field-select", ".variants-ui__input-select.form-field-input.form-field-select", ".product-options.grid .js", 'options-selection select', "variant-select select", '.zpa-single-option-selector', '.prd-block_options .prd-block_select select', '.product-page-info__variants select', 'product-variants select', '.dynamic-variant-input', '.product-options select', "variant-selector select", "fieldset[data-node-type='add-to-cart-option'] [data-node-type='add-to-cart-option-select']", '.js-product-option-input', '.product__variants select', "gp-product-variants select", "variant-selects fieldset select", '.product__option-select-wrapper select', 'select[data-replo-repeated-index][role="listbox"]', 'variant-selects select.field__input', ".product__option .select-wrapper select.input", "select[data-replo-variant-select-dropdown]", ".product__block.product__variant-select select", "select.original-selector[name='id']", "div[data-product-option] select[data-product-option-selector]", ".product__form-block .selector-wrapper select", "variant-dropdown .product-variant__option__item select", "x-variant-picker.x-variant-picker .x-variant-picker__field-wrapper select", "product-selector.main-product__selector .select select", "f-variant-picker .f\\:variant-picker__field-wrapper select", ".wb-custom-variants-selector select", "loess-variant-picker loess-variant-selects select", '.variant-picker__form .variant-option__select-wrapper select.variant-option__select', "variant-selects .select__select", ".shopify-product-form .product-variants.product-variants--only select" ]; //Selectors for console.log("fieldsets selects"); wideBundle.updateSelect(element.querySelector('select'), valuesToTest); } else if (element.querySelector('button')) { //If fieldsets are
 
`; const overlay = popup.querySelector(".js-dg-overlay"); const submit = popup.querySelector(".js-dg-submit-btn"); const close = popup.querySelector(".js-dg-close-btn"); document.body.appendChild(popup); popup.addEventListener("change", () => submit.disabled = false); overlay.addEventListener("click", () => closeDynamicGroupPopup(submit.dataset.uuid, null)); close.addEventListener("click", () => closeDynamicGroupPopup(submit.dataset.uuid, null)); submit.addEventListener("click", (event) => { const parent = event.target.closest("#wb-dynamic-group-popup"); const parentRadio = parent.querySelector(".js-dg-products .wb-dg-popup-product__input:checked"); const uuid = submit.dataset.uuid; const choice = parentRadio.value; submit.disabled = true; submit.textContent = "Loading..."; closeDynamicGroupPopup(uuid, choice); }); } async function openDynamicGroupPopup(inputDynamicGroup, selected = false) { const dynamicGroupButton = wideBundle.activeWidget.querySelector(`.js-wb-dynamic-group[data-uuid="${inputDynamicGroup.uuid}"]`); if (dynamicGroupButton) { dynamicGroupButton.disabled = false; dynamicGroupButton.innerHTML = /* html */ ` ${!selected ? `
` : `
`}
${wbHtmlentities(wideBundle.settings.dg_choose_btn_text)}
`; } const dynamicGroup = await fetchDynamicGroupData(inputDynamicGroup); ensureDynamicGroupPopup(); if (dynamicGroupButton) { dynamicGroupButton.disabled = false; dynamicGroupButton.innerHTML = /* html */ ` ${!selected ? '
?
' : `
`}
${wbHtmlentities(wideBundle.settings.dg_choose_btn_text)}
`; } const popup = document.querySelector("#wb-dynamic-group-popup"); const popupProducts = popup.querySelector(".js-dg-products"); const submitBtn = popup.querySelector(".js-dg-submit-btn"); popupProducts.innerHTML = ""; dynamicGroup.options.forEach((option) => { let thumbnailUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; if (option.thumbnail?.url?.length > 0) { thumbnailUrl = new URL(option.thumbnail?.url ?? ""); // 1. Link has _123x suffix, which we need to remove // 2. Link has _x123 suffix, which we need to remove // 3. Find file extension at the end of url and append _200x200 to get resized image from CDN thumbnailUrl.pathname = thumbnailUrl.pathname.replace(/_(\d+)x(\d+)(\.\w+)$/, "$3"); thumbnailUrl.pathname = thumbnailUrl.pathname.replace(/_x(\d+)(\.\w+)$/, "$2"); thumbnailUrl.pathname = thumbnailUrl.pathname.replace(/\.(jpg|jpeg|png|webp|avif|gif|heic)$/, "_200x200.$1"); thumbnailUrl = thumbnailUrl.toString(); } popupProducts.insertAdjacentHTML("beforeend", /* html */ `
  • `); }); submitBtn.dataset.uuid = dynamicGroup.uuid; popup.style.display = "flex"; document.body.style.overflow = "hidden"; document.body.style.overscrollBehavior = "none"; } async function closeDynamicGroupPopup(uuid, choice = null) { const popup = document.querySelector("#wb-dynamic-group-popup"); if (choice === null) { wideBundle.updateDynamicGroupProduct(uuid, null); const submit = popup.querySelector(".js-dg-submit-btn"); submit.disabled = true; popup.style.display = "none"; document.body.style.overflow = null; document.body.style.overscrollBehavior = null; return; } const selectedOffer = wideBundle.getSelectedOffer(); const dynamicGroup = selectedOffer.dynamicGroups.find((group) => group.uuid === uuid); const selectedOption = dynamicGroup.options.find((option) => option.id === Number(choice)); const productData = await fetchDynamicProductData(selectedOption); wideBundle.updateDynamicGroupProduct(uuid, productData); setTimeout(() => { const submit = popup.querySelector(".js-dg-submit-btn"); submit.disabled = true; submit.textContent = wideBundle.settings.dg_choose_btn_text; popup.style.display = "none"; document.body.style.overflow = null; document.body.style.overscrollBehavior = null; }, 0); } function defaultSelect(offer, contentRight, i, j, optionsLabels, offersPointer, productPointer, swatchId, offerContainer) { let giftWrapper = document.createElement('div'); giftWrapper.classList.add('wb-gift-product-wrapper'); var selectContainer = document.createElement('div'); selectContainer.id = `div-second-select-${offer.variants[0].id}-${i}__${offersPointer}_${productPointer}`; selectContainer.classList.add(`div-second-select-${offer.variants[0].id}-${i}__${offersPointer}_${productPointer}`, `div-select2`); if(wideBundle.settings.plan !== "monthly" && (offer.option4_is_color === "1" || offer.option3_is_color === "1" || offer.option2_is_color === "1")) { selectContainer.classList.add('wb-swatch-container'); } if(offer.automatic_discount){ selectContainer.classList.add(`div-discount-system`); } selectContainer.setAttribute('data-id', offer.variants[0].id); selectContainer.setAttribute('data-product-id', offer.product_id); selectContainer.setAttribute('data-offers-pointer', offersPointer); selectContainer.setAttribute('data-product-pointer', productPointer); if (offer.dynamicGroupUuid !== null && offer.dynamicGroupSelected !== null && wideBundle.settings.design_code != 1) { selectContainer.style.marginLeft = "92px"; } const maxDepth = offer.options_number - 1; let initialOptions = [offer.option2_values[0]]; if (maxDepth > 0 && offer.option3_values?.[0]) initialOptions.push(offer.option3_values[0]); if (maxDepth > 1 && offer.option4_values?.[0]) initialOptions.push(offer.option4_values[0]); const optionAvailability = wideBundle.calcOptionsAvailability( initialOptions, [ offer.option2_values, offer.option3_values, offer.option4_values, ], offer.variants, ); if(offer.options_number == 3){ //If we have a 3rd option we add the `; for(var k = 0; k${wbHtmlentities(wideBundle.getTranslatedText(value))}`; } selectForThirdOptionHtml += ``; if(offer.option3_is_color === "1" && wideBundle.settings.plan !== "monthly") { selectForThirdOptionHtml += `
    `; for(var k = 0; k
    `; } selectForThirdOptionHtml += `
    `; } } else{ var selectForThirdOptionHtml = ''; } //Add the select for the 2nd option with the options values let selectForSecondOptionHtml = offer.automatic_discount ? (offer.options_number !== 3 && !offer.product_is_gift ? `

    #${i+1}

    ` : "") : `

    ${wideBundle.getTranslatedText(optionsLabels[i])}

    `; selectForSecondOptionHtml += `
    `; //Add the selects into a div for the display flex selectForSecondOptionHtml += ``; if (offer.options_number == 2 && offer.automatic_discount) { selectForSecondOptionHtml += `

    `; } if(offer.option2_is_color === "1" && wideBundle.settings.plan !== "monthly") { selectForSecondOptionHtml += `
    `; for (var k = 0; k < offer.option2_values.length; k++) { const disabled = wideBundle.isAutomaticDiscount ? !optionAvailability[0][k] : false; var color_hex = offer.options_color_values[offer.option2_values[k]]; var style = /^#(?:[0-9a-f]{3}){1,2}$/i.test(color_hex) ? `background-color: ${color_hex}` : `background-image: url(${color_hex})`; selectForSecondOptionHtml += ``; } selectForSecondOptionHtml += `
    `; } selectForSecondOptionHtml += `${selectForThirdOptionHtml}${offer.automatic_discount ? '' : '

    '}`; //Hide the container if there is 1 option value or less for both options if(offer.option2_values.length <= 1 && offer.option3_values.length <= 1){ selectContainer.classList.add('hide-bloc-wb'); } if (offer.automatic_discount && offer.options_number == 3) { //Add the select for the 1st option with the options values selectForSecondOptionHtml = !offer.product_is_gift ? (`

    #${i+1}

    ` + selectForSecondOptionHtml) : selectForSecondOptionHtml; var selectForFirstOptionHtml = ``; if(offer.option4_is_color === "1" && wideBundle.settings.plan !== "monthly") { selectForFirstOptionHtml += `
    `; for (var k = 0; k < offer.option4_values.length; k++) { const disabled = wideBundle.isAutomaticDiscount ? !optionAvailability[2][k] : false; var color_hex = offer.options_color_values[offer.option4_values[k]]; var style = /^#(?:[0-9a-f]{3}){1,2}$/i.test(color_hex) ? `background-color: ${color_hex}` : `background-image: url(${color_hex})`; selectForFirstOptionHtml += ``; } selectForFirstOptionHtml += `
    `; } selectForSecondOptionHtml += selectForFirstOptionHtml; selectForSecondOptionHtml += `

    `; selectContainer.innerHTML = selectForSecondOptionHtml; } selectContainer.innerHTML = selectForSecondOptionHtml; if (offer.product_is_gift) { giftLeftContainer = document.createElement("div"); giftLeftContainer.classList.add("gift-left-container"); giftLeftSubContainer = document.createElement("div"); giftLeftSubContainer.classList.add("gift-left-sub-container"); offerContainer.classList.add(`offer-free-gift`); if (offer.gift_image !== null && offer.gift_image.length > 0) { const giftImage = document.createElement("img"); giftImage.width = 27; giftImage.height = 27; giftImage.src = offer.gift_image; giftLeftContainer.appendChild(giftImage); } if (offer.gift_text !== null && offer.gift_text.length > 0) { const giftText = document.createElement("p"); giftText.textContent = wideBundle.getTranslatedText(offer.gift_text); giftText.classList.add("free-gift-text"); giftLeftSubContainer.appendChild(giftText); } // Add option titles using the same system const optionsName = [2, 3, 4] .map(i => offer[`option${i}_values`]?.length > 1 ? wideBundle.getTranslatedText(offer[`option${i}_title`]) : null) .filter(title => title && title.trim()) .join(', '); if (optionsName) { let labelDropdowns = document.createElement('p'); labelDropdowns.classList.add("general_option_label_wb"); if (offer.dynamicGroupSelected !== null) { labelDropdowns.innerHTML = /* html */ ` ${wbHtmlentities(optionsName)} `; } else { labelDropdowns.textContent = `${wbHtmlentities(optionsName)}`; } giftLeftSubContainer.appendChild(labelDropdowns); } selectContainer.innerHTML = selectForSecondOptionHtml; giftLeftSubContainer.appendChild(selectContainer); giftLeftContainer.appendChild(giftLeftSubContainer); // Add price display for gift product const priceElement = document.createElement('p'); priceElement.classList.add('gift-price-new-form'); var variantId = offer.variants[0].id; var price = document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantId}"]`).innerHTML; var compareAtPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantId}"]`).innerHTML; var priceToShow = compareAtPrice && compareAtPrice !== "" ? compareAtPrice : price; var priceHtml = ` ${wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator("0.00"))))} ${wideBundle.replaceCurrencyForMarket(priceToShow)} `; priceElement.innerHTML = priceHtml; const plusCircle = document.createElement('div'); plusCircle.className = 'plus-circle'; const svgPlus = ` `; plusCircle.innerHTML = svgPlus; giftWrapper.appendChild(plusCircle); giftWrapper.appendChild(giftLeftContainer); giftWrapper.appendChild(priceElement); giftWrapper.dataset.gOffersPointer = offersPointer; giftWrapper.dataset.gProductPointer = productPointer; giftWrapper.dataset.gProductId = offer.product_id; offerContainer.appendChild(giftWrapper); } else if (offer.product_is_upsell) { let upsellWrapper = document.createElement('div'); upsellWrapper.classList.add('wb-gift-product-wrapper'); upsellWrapper.classList.add('wb-gift-product-wrapper--upsell'); let upsellLeftContainer = document.createElement("div"); upsellLeftContainer.classList.add("gift-left-container"); let upsellLeftSubContainer = document.createElement("div"); upsellLeftSubContainer.classList.add("gift-left-sub-container"); offerContainer.classList.add(`offer-free-gift`); // Add product image if available (similar to gift) if (offer.upsell_image !== null && offer.upsell_image.length > 0) { const upsellImage = document.createElement("img"); upsellImage.width = 27; upsellImage.height = 27; upsellImage.src = offer.upsell_image; upsellLeftContainer.appendChild(upsellImage); } // Add product title or upsell text const upsellText = document.createElement("p"); upsellText.textContent = wideBundle.getTranslatedText(offer.upsell_text || "Upsell Product"); upsellText.classList.add("free-gift-text"); // Reuse gift text class upsellLeftSubContainer.appendChild(upsellText); // Add option titles using the same system const optionsName = [2, 3, 4] .map(i => offer[`option${i}_values`]?.length > 1 ? wideBundle.getTranslatedText(offer[`option${i}_title`]) : null) .filter(title => title && title.trim()) .join(', '); if (optionsName) { let labelDropdowns = document.createElement('p'); labelDropdowns.classList.add("general_option_label_wb"); labelDropdowns.textContent = `${wbHtmlentities(optionsName)}`; upsellLeftSubContainer.appendChild(labelDropdowns); } selectContainer.innerHTML = selectForSecondOptionHtml; upsellLeftSubContainer.appendChild(selectContainer); upsellLeftContainer.appendChild(upsellLeftSubContainer); // Add price display for upsell product const priceElement = document.createElement('p'); priceElement.classList.add('gift-price-new-form'); // Reuse gift price class priceElement.classList.add('upsell-price-new-form'); const variantId = offer.variants[0].id; const totalPrice = wideBundle.getAmountFromPrice(document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantId}"]`)?.innerHTML ?? "").replace(",", "."); const price = Math.max(0, totalPrice - ((totalPrice / 100) * offer.upsell_discount)).toFixed(2); const compareAtPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantId}"]`)?.innerHTML ?? ""; const formattedPrice = wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(price)))); const formattedCompareAtPrice = compareAtPrice?.length > 0 ? wideBundle.replaceCurrencyForMarket(compareAtPrice) : wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(totalPrice)))); let priceHtml = ` ${formattedPrice} `; let compareAtPriceHtml = ` ${formattedCompareAtPrice} `; if ( Number(wideBundle.getAmountFromPrice(formattedPrice) ?? 0).toFixed(2) === Number(wideBundle.getAmountFromPrice(formattedCompareAtPrice) ?? 0).toFixed(2) ) { compareAtPriceHtml = ''; } priceElement.innerHTML = priceHtml + compareAtPriceHtml; // Create checkbox for upsell const upsellCheckbox = document.createElement('input'); upsellCheckbox.type = 'checkbox'; upsellCheckbox.classList.add('wb-upsell-checkbox'); upsellCheckbox.checked = false; // Unchecked by default upsellCheckbox.setAttribute('data-offers-pointer', offersPointer); upsellCheckbox.setAttribute('data-product-pointer', productPointer); upsellCheckbox.setAttribute('data-product-id', offer.product_id); upsellCheckbox.setAttribute('data-upsell-id', offer.offer_uuid); upsellWrapper.appendChild(upsellCheckbox); upsellWrapper.appendChild(upsellLeftContainer); upsellWrapper.appendChild(priceElement); upsellWrapper.dataset.gOffersPointer = offersPointer; upsellWrapper.dataset.gProductPointer = productPointer; upsellWrapper.dataset.gProductId = offer.product_id; offerContainer.appendChild(upsellWrapper); } else { contentRight.appendChild(selectContainer); } } //Display the saving text if it's enabled wideBundle.createSavingText = function(offer, contentRight, offerContainer){ let variantsString = offer.variants[0].id; if (wideBundle.isAutomaticDiscount) { const variantIdsSelected = wideBundle.offers[offer.offersPointer].filter((offer) => !offer.product_is_upsell).reduce((ids, offer) => { const variantId = offer.variants[0].id; return [...ids, ...(new Array(offer.product_qty).fill(variantId))]; }, []); variantsString = offer.offersPointer + "@" + variantIdsSelected.join("+"); } if(wideBundle.settings.economic_display == 1){ var priceEl = document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantsString}"]`); var compareAtPriceEl = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantsString}"]`); const price = priceEl ? priceEl.innerHTML : ""; const compareAtPrice = compareAtPriceEl ? compareAtPriceEl.innerHTML : ""; if (price.trim() === compareAtPrice.trim()) return; if (price.trim() === "") return; if (compareAtPrice.trim() === "") return; difference = getAmountDifference(price, compareAtPrice); if(wideBundle.settings.no_decimal == 1){ //If they enabled the feature to remove decimal difference.amount = wideBundle.removeDecimal(difference.amount); } var currencyAlone = price.replace(/\d+.\d+/g,'{{amount}}').replace(/\d+/g,'{{amount}}') var priceDifference = wideBundle.updatePriceSeparator(currencyAlone.replace('{{amount}}', difference.amount)); var savingTextContent = wideBundle.getTranslatedText(wideBundle.settings.economic_text); savingTextContent = savingTextContent.replace("{{percent}}", `${difference.percent}`); savingTextContent = savingTextContent.replace("{{amount}}", `${wideBundle.updatePriceSeparator(priceDifference)}`); var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); var yyyy = today.getFullYear(); today = dd + '/' + mm + '/' + yyyy; savingTextContent = savingTextContent.replace('{{today}}', today); var savingText = document.createElement('p'); savingText.innerHTML = savingTextContent; savingText.classList.add('economic-wb'); contentRight.appendChild(savingText); offerContainer.classList.add('with-economic-text'); } } //Create a custom sentence if the user added one wideBundle.createCustomSentence = function(message, effect, contentParent, titleElement = null, position = null){ if(message){ customSentence = document.createElement('span'); customSentence.classList.add('best-title', 'best-title-new'); customSentence.innerHTML = wideBundle.getTranslatedText(message); if(effect == 1){ //If blinking enabled customSentence.classList.add('best-title-blink'); } contentParent.classList.add('with-message'); if (titleElement && position == 4) { titleElement.innerHTML = `${wideBundle.getTranslatedText(titleElement.innerHTML)} ${wideBundle.getTranslatedText(message)}`; } else { contentParent.appendChild(customSentence); } } } //Add the quantity widget if it's enabled wideBundle.createQuantityWidget = function(offerContainer){ if(wideBundle.settings.display_quantity == 1){ var quantityContainer = document.createElement('div'); quantityContainer.classList.add('spinWB'); quantityHTML = ` + `; quantityContainer.innerHTML = quantityHTML; offerContainer.append(quantityContainer); //Add the event listeners quantityContainer.querySelector('.quantity-wb-less').addEventListener('click', function(){ var value = Math.max(1, document.querySelector('.selectedWB .quantity-wb-input').value -1); wideBundle.updateQuantityInputs(value); wideBundle.updateQuantityDisabled(value); }); quantityContainer.querySelector('.quantity-wb-more').addEventListener('click', function(){ var value = Math.max(1, parseInt(document.querySelector('.selectedWB .quantity-wb-input').value)+1); wideBundle.updateQuantityInputs(value); wideBundle.updateQuantityDisabled(value); }); offerContainer.querySelector('.quantity-wb-input').addEventListener('change', function(){ if(isNaN(this.value.replace(',', '.'))){ wideBundle.updateQuantityInputs(1); wideBundle.updateQuantityDisabled(1); } else{ wideBundle.updateQuantityInputs(Math.round(this.value.replace(',', '.'))); wideBundle.updateQuantityDisabled(Math.round(this.value.replace(',', '.'))); } }); } } //Update the quantity inputs values in the page wideBundle.updateQuantityInputs = function(value){ //For quantity inputs in the offers var quantityInputs = document.querySelectorAll('.quantity-wb-input'); for(var i = 0; i 0) { increaseButton.click(); difference--; if (difference > 0) { setTimeout(adjustQuantity, 100); // Adjust the timeout as necessary } } else if (difference < 0) { decreaseButton.click(); difference++; if (difference < 0) { setTimeout(adjustQuantity, 100); // Adjust the timeout as necessary } } } adjustQuantity(); } } //Update the selects in all the WideBundle widgets to change the selected values wideBundle.updateSelectsInOffers = function(elementUpdated){ var valueOfElement = elementUpdated.value; var classSelectors = Array.from(elementUpdated.classList); var classOfElement = '.' + classSelectors.join('.'); for(var i=0; i= 40){ clearInterval(checkCurrentWidget); } }, 200); } } //Add the product to the cart (function called immediately after the click on the button) wideBundle.addToCart = function(){ //Add the loading gif wideBundle.displayLoadingOnATC(); wideBundle.showErrorIfNonExistingVariant(); //Show error if the variant doesn't exist on Shopify console.log('clicked on the button'); //Get currency name currencyName = typeof window.ShopifyAnalytics !== "undefined" ? window.ShopifyAnalytics.meta.currency : typeof window.Shopify.currency !== "undefined" ? Shopify.currency.active : wideBundle.setting.currency_code; //Get infos about the variant to add var selectedOffer = wideBundle.getSelectedOffer(); var selectedVariantId = wideBundle.getSelectedVariantId(true)[0]; var quantityVariant = document.querySelector('.selectedWB .quantity-wb-input'); var quantityVariantValue = quantityVariant ? Number(quantityVariant.value) : 1; var itemsToAddToCart = {items: [{quantity: quantityVariantValue, id: selectedVariantId}]}; //test variable (apply sideCart without theme) let firstCartItem; if (selectedOffer.automatic_discount) { const offerGroup = wideBundle.offers[selectedOffer.offersPointer]; const variantIds = wideBundle.getSelectedVariantId(true).slice(); const giftVariantIds = wideBundle.getGiftVariantIds().slice(); const abTestVariant = wideBundle.retrieveAbTestVariant(); wideBundle.abTestEnabled && wideBundle.reportAbTestAddToCart(selectedOffer, abTestVariant); itemsToAddToCart.items = []; const userTextWrapper = wideBundle.activeWidget.querySelector(".selectedWB .wb-user-text-wrapper"); const userTextInput = wideBundle.activeWidget.querySelector(".selectedWB .input-user-text"); let userTextProperty = null; let userTextValue = null; if (offerGroup[0].user_text_enabled && userTextInput) { userTextProperty = offerGroup[0].user_text_property; if (offerGroup[0].user_text_required && !userTextInput.reportValidity()) { userTextValue = null; userTextWrapper?.classList?.add("wb-user-text-wrapper--has-error"); wideBundle.removeLoadingOnATC(); return; } else { userTextValue = userTextInput.value.trim(); userTextInput.value = ""; userTextWrapper?.classList?.remove("wb-user-text-wrapper--has-error"); } } offerGroup.forEach((currentOffer, currentOfferIndex) => { for (let i = 0; i < currentOffer.product_qty; i++) { // Upsell checkbox logic const upsellCheckbox = wideBundle.activeWidget.querySelector(`input[type="checkbox"][data-upsell-id="${currentOffer.offer_uuid}"]`); if (currentOffer.product_is_upsell && upsellCheckbox && !upsellCheckbox.checked) { wideBundle.removeLoadingOnATC(); return; // Skip this item if upsell checkbox is unchecked } const id = Number(variantIds.shift()); const quantity = quantityVariantValue; const properties = {}; if (wideBundle.abTestEnabled) { properties["__wide-bundle-excl-offers"] = wideBundle.abTestExcludeOffers.join(","); properties["__wide-bundle-variant"] = `${abTestVariant}:${currentOffer.offer_db_id}:${currentOffer.index}`; } if (currentOfferIndex > 0 && ( (giftVariantIds.includes(id) && currentOffer.product_is_gift) || currentOffer.product_is_upsell )) { properties["__wide-bundle-gift-variant"] = id; } if (currentOffer.dynamicGroupSelected !== null) { properties["__wide-bundle-dyn-group"] = "dyn/" + currentOffer.dynamicGroupUuid; } if (userTextProperty !== null && userTextValue !== null) { properties[userTextProperty] = userTextValue; } itemsToAddToCart.items.push({ id, quantity, properties, }); } }); //validation, if we send all prods using fetch and one add manually to sideCart if (wideBundle.settings.link_choice == "form" && itemsToAddToCart.items.length > 1) { firstCartItem = itemsToAddToCart.items.shift(); } } const atcButtons = Array.from(document.querySelectorAll('.new-form-atc')); //Disable click atcButtons.forEach(function (atcButton) { atcButton.style.pointerEvents = 'none'; }); wideBundle.updateQuantityDisabled(quantityVariantValue).then(function (continueAddToCart) { if (!continueAddToCart) { return; } if(wideBundle.settings.link_choice == "form"){ //If the user selected "side cart" redirection wideBundle.showErrorIfSideCart(); //Show error if the user didn't add add-to-cart button and variants selector if (selectedOffer.automatic_discount) { // Convert theme's native variant id input into array-like field wideBundle.convertHiddenIdInputToArray(); } wideBundle.updateVariantIdSelector(selectedVariantId); //Update the in the form with name = id wideBundle.addToCartAjax(itemsToAddToCart) .then(function(responseText) { //Manage an upsell app to open the app after the product was added to the cart if(typeof initiateRaidFunnelByVariant !== 'undefined'){ if(initiateRaidFunnelByVariant(selectedVariantId) == true){ return Promise.resolve(); } } //Manage an upsell app to open the app after the product was added to the cart else if(typeof app !== 'undefined' && typeof app.showModal !== 'undefined'){ app.showModal = true; app.configs[0].value=app.getThemeQuantity(); app.isCart=false; //Put back WideBundle button text wideBundle.removeLoadingOnATC(); } document.body.click(); if(addToCartButton.element.disabled){ addToCartButton.element.disabled = false; } addToCartButton.element.click(); wideBundle.handleSlideCartApp; //Open slide cart app if (selectedOffer.automatic_discount) { // Convert theme's native variant id input back to field wideBundle.convertHiddenIdInputToField(); } //Put back WideBundle button text wideBundle.removeLoadingOnATC(); return Promise.resolve(); }) .catch(function(error) { console.error(error); if (error.cause && error.cause == 422) { const atcButtons = Array.from(document.querySelectorAll('.new-form-atc')); atcButtons.forEach(function (atcButton) { atcButton.classList.add('new-form-atc--out-of-stock'); atcButton.innerHTML = wideBundle.getTranslatedText(wideBundle.settings.atc_content_text); atcButton.style.pointerEvents = 'none'; }); return Promise.resolve(); } else { return Promise.reject(error); } }); } else { document.body.click(); if(addToCartButton.element.disabled){ addToCartButton.element.disabled = false; } addToCartButton.element.click(); wideBundle.handleSlideCartApp; //Open slide cart app if (selectedOffer.automatic_discount) { // Convert theme's native variant id input back to field wideBundle.convertHiddenIdInputToField(); } //Put back WideBundle button text wideBundle.removeLoadingOnATC(); } } } else{ //If the user selected "checkout" or "cart" redirection var redirectionUrl = getShopifyBaseUrl() + wideBundle.settings.link_choice; wideBundle.managePixels(currencyName); //Manage pixels (Facebook, Google, etc) wideBundle.addToCartAjax(itemsToAddToCart) .then(function(responseText) { //Manage an upsell app to open the app after the product was added to the cart if(typeof initiateRaidFunnelByVariant !== 'undefined'){ if(initiateRaidFunnelByVariant(selectedVariantId) == true){ return; } } //Manage an upsell app to open the app after the product was added to the cart else if(typeof app !== 'undefined' && typeof app.showModal !== 'undefined'){ app.showModal = true; app.configs[0].value=app.getThemeQuantity(); app.isCart=false; //Put back WideBundle button text wideBundle.removeLoadingOnATC(); } //If the user redirects to checkout else if(wideBundle.settings.link_choice == "checkout"){ if(document.querySelector('#checkout-xx-aa')){ document.body.click(); //Manage the double click problem on some themes document.querySelector('#checkout-xx-aa').click(); //Put back WideBundle button text wideBundle.removeLoadingOnATC(); } } //If the user redirects to cart else if(wideBundle.settings.link_choice == "cart"){ if (typeof _transcy !== 'undefined' && typeof _transcy.variants.localeCurrent !== 'undefined' && typeof _transcy.variants.localeDefault !== 'undefined' && _transcy.variants.localeCurrent !== _transcy.variants.localeDefault && _transcy.variants.localeDefault !== '') { credirectionUrl = `/${_transcy.variants.localeCurrent}/cart`; } //Put back WideBundle button text wideBundle.removeLoadingOnATC(); window.location = redirectionUrl; } return Promise.resolve(); }) .catch(function(error) { console.error(error); if (error.cause && error.cause == 422) { const atcButtons = Array.from(document.querySelectorAll('.new-form-atc')); atcButtons.forEach(function (atcButton) { atcButton.classList.add('new-form-atc--out-of-stock'); atcButton.innerHTML = wideBundle.getTranslatedText(wideBundle.settings.atc_content_text); atcButton.style.pointerEvents = 'none'; }); return Promise.resolve(); } else { return Promise.reject(error); } }); } }); } function wbCheckVariantsInventoryAvailability() { return new Promise((resolve, reject) => { const checkInterval = setInterval(() => { if (wideBundle.variantsInventory !== undefined && Object.keys(wideBundle.variantsInventory).length > 0) { clearInterval(checkInterval); resolve(wideBundle.variantsInventory); } }, 100); setTimeout(() => { clearInterval(checkInterval); reject(new Error(`Variants inventory was not found within the time limit.`)); }, 10000); }); } wideBundle.reportAbTestAddToCart = function(offer, variant) { const fetchUrl = new URL(wideBundle.domain + 'abTest.php'); fetchUrl.searchParams.set('id', offer.offer_db_id); fetchUrl.searchParams.set('index', offer.index); fetchUrl.searchParams.set('abTestVariant', variant); window.originalFetch(fetchUrl.toString(), { mode: 'cors', }).then(response => { if (response.ok) { return response.text(); } else { throw new Error(response.statusCode, { cause: response.status }); } }).then(data => { console.log('A/B report response:', data); }).catch(error => { throw error; }); } //Create the button out of stock if enabled and if the variant is out of stock wideBundle.updateQuantityDisabled = async function(quantity = 1, showSpinner = true) { if (Number(wideBundle.settings.enable_atc_button) !== 1 && wideBundle.isAutomaticDiscount == false) { return true; } if(!wideBundle.isAutomaticDiscount){ showSpinner = true; } try { showSpinner && wideBundle.displayLoadingOnATC(); const selectedVariantIds = wideBundle.isAutomaticDiscount ? wideBundle.getSelectedVariantId(true) : [wideBundle.getSelectedVariantId(true)[0]]; const bundleQuantities = selectedVariantIds.reduce((variants, variantId) => { if (variants[variantId]) { variants[variantId] += quantity; return variants; } return { ...variants, [variantId]: quantity, }; }, {}); const atcButtons = Array.from(document.querySelectorAll('.new-form-atc')); let data = { inventory_quantity: 0, add_to_cart_btn_enable: 0, }; if (wideBundle.isAutomaticDiscount) { let variantsInventory = {}; if (window.hasOwnProperty("wideBundlePreviewMode") && window?.wideBundlePreviewMode === true) { selectedVariantIds.forEach(variant_id => { variantsInventory[variant_id] = { inventory_quantity: 999999, add_to_cart_btn_enable: '1' }; }); } else { variantsInventory = await wbCheckVariantsInventoryAvailability(); } for (let i = 0; i < selectedVariantIds.length; i++) { const variantId = selectedVariantIds[i]; const inventoryQuantity = Number(variantsInventory?.[variantId]?.inventory_quantity ?? 0); const addToCartBtnEnable = Number(variantsInventory?.[variantId]?.add_to_cart_btn_enable ?? 0); if (bundleQuantities[variantId] > inventoryQuantity || addToCartBtnEnable === 0) { data.inventory_quantity = 0; data.add_to_cart_btn_enable = 0; break; } else { data.inventory_quantity += inventoryQuantity; data.add_to_cart_btn_enable = 1; } } } else { const fetchUrl = new URL(wideBundle.domain + 'storefront/getvariantinventory'); fetchUrl.searchParams.set('variant_ids', selectedVariantIds[0]); const response = await window.originalFetch(fetchUrl.toString(), { mode: 'cors' }); const fetchData = await response.json(); data = fetchData; } // Revert original buttons state atcButtons.forEach(function (atcButton) { atcButton.classList.remove('new-form-atc--out-of-stock'); var atcText = wideBundle.getTranslatedText(wideBundle.settings.atc_text); if(atcText && (atcText.includes('{{price}}') || atcText.includes('{{compare-price}}'))){ var priceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.first-price-WB') : null; var comparePriceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.second-price-WB') : null; var price = priceEl ? priceEl.outerHTML : ''; var comparePrice = comparePriceEl ? comparePriceEl.outerHTML : ''; atcText = atcText.replace(/{{price}}/g, price); atcText = atcText.replace(/{{compare-price}}/g, comparePrice); } atcButton.innerHTML = AddSVG()+atcText; atcButton.style.pointerEvents = 'auto'; }); if (data === false) { return false; } let enableButton = Number(data.add_to_cart_btn_enable) === 1; let continueSelling = true; if (Number(quantity) > 1 && Number(quantity) > Number(data.inventory_quantity)) { continueSelling = false; } let selectedOffer = wideBundle.getSelectedOffer(); let hasAllGroups = wideBundle.offers[selectedOffer.offersPointer].reduce((a, p) => a + (p.dynamicGroupSelected !== null ? 1 : 0), 0) === selectedOffer.dynamicGroups.length; if (enableButton && continueSelling && hasAllGroups) { return true; } else { atcButtons.forEach(function (atcButton) { atcButton.classList.add('new-form-atc--out-of-stock'); atcButton.style.pointerEvents = 'none'; if (!hasAllGroups) { atcButton.innerHTML = wideBundle.getTranslatedText(wideBundle.settings.atc_text); } else { atcButton.innerHTML = wideBundle.getTranslatedText(wideBundle.settings.atc_content_text); } }); return false; } } catch (error) { console.error(error); return false; } } //Open the side cart of the app Slide Cart wideBundle.handleSlideCartApp = function(){ try{ if(typeof window.SLIDECART_UPDATE != "undefined"){ setTimeout(() => { if(!window.SLIDECART_STATE().open){ window.SLIDECART_UPDATE(); window.SLIDECART_OPEN(); } }, 600); } }catch(error){ console.error(error); } } // Cache target product variant IDs wideBundle.getTargetVariantIds = function() { if (!wideBundle._targetVariantIds) { wideBundle._targetVariantIds = new Set( wideBundle.data .filter(v => v.handle === wideBundle.currentHandle) .map(v => v.variant_id) ); } return wideBundle._targetVariantIds; } /** * Get cart items with their properties for automatic discount bundles. * Returns an array of cart items including variant IDs and associated properties * (A/B test, gifts, dynamic groups, etc.) * * @returns {Array<{id: number, quantity: number, properties: Object}>} - Array of cart items with properties */ wideBundle.getAutomaticDiscountCartItems = function() { const selectedOffer = wideBundle.getSelectedOffer(); // Only works for automatic discount bundles if (!selectedOffer || !selectedOffer.automatic_discount) { return []; } // Get quantity from DOM const quantityInput = document.querySelector('.selectedWB .quantity-wb-input'); const quantity = quantityInput ? Number(quantityInput.value) : 1; const offerGroup = wideBundle.offers[selectedOffer.offersPointer]; const variantIds = wideBundle.getSelectedVariantId(true).slice(); const giftVariantIds = wideBundle.getGiftVariantIds().slice(); const abTestVariant = wideBundle.retrieveAbTestVariant(); const cartItems = []; offerGroup.forEach((currentOffer, currentOfferIndex) => { for (let i = 0; i < currentOffer.product_qty; i++) { const id = Number(variantIds.shift()); const properties = {}; // A/B test properties if (wideBundle.abTestEnabled) { properties["__wide-bundle-excl-offers"] = wideBundle.abTestExcludeOffers.join(","); properties["__wide-bundle-variant"] = `${abTestVariant}:${currentOffer.offer_db_id}:${currentOffer.index}`; } // Gift variant properties if (currentOfferIndex > 0 && giftVariantIds.includes(id) && currentOffer.product_is_gift) { properties["__wide-bundle-gift-variant"] = id; } // Dynamic group properties if (currentOffer.dynamicGroupSelected !== null) { properties["__wide-bundle-dyn-group"] = "dyn/" + currentOffer.dynamicGroupUuid; } cartItems.push({ id, quantity, properties, }); } }); return cartItems; } // Check for Recurpay subscription wideBundle.getRecurpaySubscription = function() { const groupMain = document.querySelector('[name="recurpay__group_main"]'); if (!groupMain || !groupMain.checked || groupMain.value !== "subscription") { return null; } const selectedOption = document.querySelector('[name="recurpay-input"]').selectedOptions[0]; if (!selectedOption) return null; return { selling_plan: selectedOption.dataset.sellingPlan, planName: selectedOption.dataset.planName }; } // Apply subscription to cart item if it's from target product wideBundle.applySubscriptionToItem = function(item, subscription) { if (!subscription || !wideBundle.getTargetVariantIds().has(item.id)) { return item; } return { ...item, selling_plan: subscription.selling_plan, properties: { Plan: subscription.planName, _PlanId: subscription.selling_plan, } }; } // Modified addToCartAjax to handle subscriptions wideBundle.addToCartAjax = function(itemsToAddToCart) { const subscription = wideBundle.getRecurpaySubscription(); const selectedOffer = wideBundle.getSelectedOffer(); if (subscription && selectedOffer.automatic_discount) { itemsToAddToCart.items = itemsToAddToCart.items.map(item => wideBundle.applySubscriptionToItem(item, subscription) ); } return window.originalFetch("/cart/add.js", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(itemsToAddToCart) }).then(response => { if (response.ok) { return response.text(); } else { throw new Error(response.statusCode, { cause: response.status }); } }).catch(error => { throw error; }); } //Handle Ecom Solid Side cart wideBundle.manageEcomSolidSideCart = function(itemsToAddToCart){ if(typeof window.SOLID != 'undefined'){ isGemPages = wideBundle.formInfo.element.closest('[class^=\'gt_section-\'][data-name], [class^=\'gf_section-\'][data-name], [class^=\'gt_widget-\'][data-name], [class^=\'gt_element-\'][data-name]'); if(isGemPages){ wideBundle.managePixels(); wideBundle.addToCartAjax(itemsToAddToCart) .then(async function(responseText) { await window.SOLID.cart.GetCart(); window.SOLID.store.dispatch('addToCartSuccess'); window.SOLID.store.dispatch('openCartPopup', 'cart_drawer'); return Promise.resolve(); }) .catch(function(error) { console.error(error); return Promise.reject(error); }); } } } //Send pixel events to Facebook, Google, etc wideBundle.managePixels = function(currencyName){ let priceAmount; const selectedOffer = wideBundle.getSelectedOffer(); const selectedVariantIds = wideBundle.getSelectedVariantId(true); if (selectedOffer.automatic_discount) { // For automatic discount bundles, look for the calculated price const variantIdsString = selectedVariantIds.join('+'); const calculatedPriceElement = document.querySelector( `.wb_hidden_prices .wb_hidden_prices_element[data-calculated] .wb_hidden_price[variant-id="${selectedOffer.offersPointer}@${variantIdsString}"]` ); if (calculatedPriceElement) { priceAmount = parseFloat( wideBundle.getAmountFromPrice(calculatedPriceElement.innerHTML) ).toFixed(2); } } else { // Legacy single variant system const priceElement = document.querySelector( `.wb_hidden_prices .wb_hidden_price[variant-id="${selectedVariantIds[0]}"]` ); if (priceElement) { priceAmount = parseFloat( wideBundle.getAmountFromPrice(priceElement.innerHTML) ).toFixed(2); } } if(wideBundle.settings.add_pixel){ //Facebook Pixel if(typeof window.fbq !== 'undefined'){ if(typeof meta != "undefined" && typeof meta.product !== 'undefined'){ for(var metaVariant in meta.product.variants){ if(meta.product.variants[metaVariant].id == wideBundle.getSelectedVariantId(true)[0]){ priceAmount = meta.product.variants[metaVariant].price / 100; window.fbq('track', 'AddToCart', { value: priceAmount.toFixed(2), currency: currencyName }); } } } else{ price = document.querySelector('.wb_hidden_prices .wb_hidden_price[variant-id="'+wideBundle.getSelectedVariantId(true)[0]+'"]'); window.fbq('track', 'AddToCart', { value: priceAmount, currency: currencyName }); } } //Pinterest Pixel if(typeof window.pintrk !== 'undefined'){ console.log('pinterest pixel found'); pintrk('track', 'addtocart', { value: priceAmount, currency: currencyName }); } } //Snap pixel if(typeof window.snaptr !== 'undefined'){ snaptr('track', 'ADD_CART', {'currency': currencyName, 'price': priceAmount, 'item_category': '', 'item_ids': [] }); } //Tiktok Pixel if(typeof window.ttq !== 'undefined'){ ttq.track('AddToCart'); } //Outbrain pixel if(typeof window.obApi !== 'undefined'){ obApi('track', 'Add To Cart'); } //Taboola Pixel if(typeof _tfa !== 'undefined'){ _tfa.push({notify: 'event', name: 'add_to_cart'}); } //Klaviyo if(typeof _learnq != "undefined"){ fetch(`${window.location.origin}/cart.js`) .then(res => res.clone().json().then(data => { var cart = { total_price: data.total_price/100, $value: data.total_price/100, total_discount: data.total_discount, original_total_price: data.original_total_price/100, items: data.items } if (typeof item != 'undefined') { cart = Object.assign(cart, item) } console.log(cart); _learnq.push(['track', 'Added to Cart', cart]); })) } } //Show the loading gif on the add to cart button wideBundle.displayLoadingOnATC = function(){ loadingHTML = ``; if(document.querySelector('#new-form-atc')){ document.querySelector('#new-form-atc').innerHTML = loadingHTML; } for(var i=0; i { UploadKitElementInForm.remove(); }); elementsInUploadKit = document.querySelectorAll('#new-form .upload-container *'); elementsInUploadKit.forEach(elementInUploadKit => { if(typeof elementInUploadKit != "undefined" && typeof elementInUploadKit.getAttribute != "undefined" && elementInUploadKit.getAttribute("name") != null && elementInUploadKit.getAttribute("name").indexOf('properties') == 0){ newNode = elementInUploadKit.cloneNode(); newNode.style.display = "none"; newNode.classList.add('wb-uploadlift'); wideBundle.formInfo.element.append(newNode); } }); } } } //Update the