var Smartcustomizer = function () { this.scready = false; this.appName = 'smartcustomizer'; this.baseUri = 'https://app.smartcustomizer.com/v2/'; this.scWrapper = null; this.scIfrm = null; this.scLoaderScreen = null; this.scLink = null; this.scLinks = null; this.variantId = null; this.addToCartBtn = null; this.embedConfig = {"active":"1","form_selector":"","button_selector":"","button_html":"","button_position":"replace"}; this.translations = {}; this.variantSelector = null; this.productForm = null; this.productQuantity = null; this.scContainer = null; this.scOptionsContainer = null; this.scPriceContainer = null; this.priceContainer = null; this.scPriceField = null; this.productIds = {"45013694841026":"4132"}; this.modelId = null; this.productOptions = {"4132":{"id":4132,"name":"Customized Ceramic Mug - 3D","sku":"","price":0,"custom_pricing":true,"options":{"4133":{"name":"Print","type":"opt_type_print","style":"1","class":"sc-select-type-img sc-select-style-circle","rule":"1","options":{"4134":{"name":"Print Front","hex":null,"price":0,"thumb":"https:\/\/app.smartcustomizer.com\/uploads\/bGwwOXQyR1Q2dFBqUDRuZnBnQ0dlUT09\/img\/catalog\/12\/4134_thumb_en.jpg"}}}},"variations":[{"name":"Variation 1","ids":["45013694841026"],"options":{"4133":["4134"]}}]}}; this.variantOptions = {}; this.selectedProductOptions = {}; this.priceFormat = '$[0.00]'; this.productBasePrice = 0; this.variantPrices = {}; this.cartUpdateTimer = null; this.ssid = null; this.replaceAddToCartButton = false; this.lng = window.Shopify && window.Shopify.locale ? window.Shopify.locale.substring(0, 2) : 'en'; this.buttonTitles = { customize: 'Customize product', edit: 'Edit Design' }; this.customDesignLabel = 'Custom Design ID:'; this.cdOption = 'Custom Design ID:'; this.customPricingActive = false; } Smartcustomizer.prototype = { initApp: function () { this.initMessageListener(); this.initTranslations(); }, changeVariant: function (event) { console.log("changeVariant"); // smartcustomizer-option if (Smartcustomizer.scLink == null) { return; } if (event && Smartcustomizer.scContainer && Smartcustomizer.scContainer.contains(event.target)) { console.log('SC option changed'); return; } setTimeout(function () { if (Smartcustomizer.addToCartBtn.disabled || Object.keys(Smartcustomizer.productIds).length === 0 || Smartcustomizer.productIds[Smartcustomizer.variantSelector.value] == undefined) { Smartcustomizer.scLink.classList.add('hide'); Smartcustomizer.scContainer.classList.add('hide'); Smartcustomizer.scPriceContainer.classList.add('hide'); if (Smartcustomizer.priceContainer !== null) { Smartcustomizer.priceContainer.classList.remove('hide'); } if (Smartcustomizer.replaceAddToCartButton) { Smartcustomizer.addToCartBtn.style.display = ''; } //console.log('add hide'); Smartcustomizer.variantId = Smartcustomizer.modelId = null; } else { if (Smartcustomizer.replaceAddToCartButton) { Smartcustomizer.addToCartBtn.style.setProperty('display', 'none', 'important'); } //console.log('remove hide'); Smartcustomizer.scLink.classList.remove("hide"); Smartcustomizer.scContainer.classList.remove('hide'); Smartcustomizer.scPriceContainer.classList.remove('hide'); if (Smartcustomizer.priceContainer !== null) { Smartcustomizer.priceContainer.classList.add('hide'); } Smartcustomizer.variantId = Smartcustomizer.variantSelector.value; Smartcustomizer.modelId = (Smartcustomizer.variantId && Smartcustomizer.productIds[Smartcustomizer.variantId]) || null; Smartcustomizer.renderProductOptions(); } }, 700); }, setVariantPrices: function () { var productConnected = false; for (let i = 0; i < Object.keys(meta.product.variants).length; i++) { let variantId = meta.product.variants[i].id; //console.log(variantId); if (Smartcustomizer.productIds[variantId]) { Smartcustomizer.modelId = Smartcustomizer.productIds[variantId]; productConnected = true; } var price = meta.product.variants[i].price; if (price > 0) { price = price / 100; } Smartcustomizer.variantPrices[variantId] = price; }; // console.log(Smartcustomizer.variantPrices); return productConnected; }, logError: function (message) { console.log('Smartcustomizer error: ' + message); }, setProductFormElements: function () { console.log('setProductFormElements'); if (this.embedConfig.form_selector != undefined && this.embedConfig.form_selector.length > 0) { this.productForm = document.querySelector(this.embedConfig.form_selector); } if (this.productForm == null) { this.productForm = document.querySelector("form[action*='/cart/add']:not(.product-form-nojs):not(.installment)"); } if (this.productForm == null) { this.logError('Form element not found.'); return false; } this.productQuantity = document.querySelector('input[name="quantity"]'); if (this.embedConfig.button_selector != undefined && this.embedConfig.button_selector.length > 0) { this.addToCartBtn = this.productForm.querySelector(this.embedConfig.button_selector); // console.log(this.addToCartBtn); } if (this.addToCartBtn == null) { this.addToCartBtn = this.productForm.querySelectorAll("*[type='submit'][name='add']"); if (this.addToCartBtn.length == 0) { this.addToCartBtn = this.productForm.querySelectorAll("*[type='submit']"); } if (this.addToCartBtn.length == 0) { this.addToCartBtn = this.productForm.querySelectorAll("*[type='button']"); } if (this.addToCartBtn.length == 0) { this.logError('Add to cart button element not found.'); return false; } this.addToCartBtn = this.addToCartBtn[this.addToCartBtn.length - 1]; } var variantIdElements = this.productForm.querySelectorAll("*[name='id']"); if (variantIdElements.length === 1) { this.variantSelector = variantIdElements[0]; } else { variantIdElements = document.getElementsByName('id'); this.variantSelector = variantIdElements[0]; if (variantIdElements.length > 1) { var selectIdsElement = document.querySelector("select[name='id']"); if (selectIdsElement) { this.variantSelector = selectIdsElement; } } } if (!this.variantSelector) { this.logError('Variant ID element not found.'); return false; } this.productForm.addEventListener('change', this.changeVariant, false); return true; }, renderProductElements: function () { console.log('renderProductElements'); if (!this.setVariantPrices() || !this.setProductFormElements()) { return; } if (this.embedConfig.button_html != undefined) { var linkElement = document.createElement('div'); linkElement.innerHTML = this.embedConfig.button_html.trim(); this.scLink = linkElement.firstChild; // console.log(this.scLink); } if (this.scLink == null) { this.scLink = document.createElement('button'); this.scLink.appendChild(document.createTextNode(this.buttonTitles.customize)); this.scLink.id = this.appName + '-link'; this.scLink.className = this.addToCartBtn.className + ' ' + this.scLink.id; } this.scLink.innerHTML += ''; this.scLink.style.display = 'none'; if (this.embedConfig.button_position != undefined && this.embedConfig.button_position !== 'bottom') { this.addToCartBtn.parentNode.insertBefore(this.scLink, this.addToCartBtn); if (this.embedConfig.button_position === 'replace') { this.replaceAddToCartButton = true; } } else { this.addToCartBtn.parentNode.appendChild(this.scLink); } var smartcustomizerContainer = '
\
\
\
\

\
\
\
'; this.scLink.insertAdjacentHTML('beforebegin', smartcustomizerContainer); this.scContainer = document.getElementById('smartcustomizer-container'); this.scOptionsContainer = document.getElementById('smartcustomizer-options'); this.scPriceContainer = document.getElementById('smartcustomizer-price-container'); this.scPriceField = document.getElementById('smartcustomizer-price'); // this.embedConfig.options_selector = 'variant-radios'; if (this.embedConfig.options_selector != undefined && this.embedConfig.options_selector.length > 0) { var optionElement = document.querySelector(this.embedConfig.options_selector); if (optionElement !== null) { optionElement.parentNode.insertBefore(this.scContainer, optionElement.nextSibling); } else { this.logError('Options element not found.'); } } if (this.embedConfig.price_selector != undefined && this.embedConfig.price_selector.length > 0) { this.priceContainer = document.querySelector(this.embedConfig.price_selector); if (this.priceContainer !== null) { this.priceContainer.parentNode.insertBefore(this.scPriceContainer, this.priceContainer.nextSibling); } else { this.logError('Price element not found.'); } } var scLinkEl = this.scLink; setTimeout(function () { scLinkEl.style.display = ''; }, 1000); this.scLink.addEventListener('click', function (event) { event.preventDefault(); var params = 'mid.' + Smartcustomizer.modelId + ',pid.' + meta.product.id + ',pvid.' + Smartcustomizer.variantId + ',lng.' + Smartcustomizer.lng; Smartcustomizer.scLink.setAttribute('data-params', params); Smartcustomizer.openSC(); }, false); this.renderAppElements(); this.changeVariant(); }, renderStyleLinks: function () { var headElement = document.getElementsByTagName('head')[0]; if (!document.getElementById('google-fonts')) { headElement.insertAdjacentHTML('beforeend', '\ \ '); } var styles = ['variations']; for (let i = 0; i < styles.length; i++) { let styleElement = document.getElementById('smartcustomizer-' + styles[i] + '-css'); if (styleElement) { continue; } var ss = document.createElement("link"); ss.type = 'text/css'; ss.rel = 'stylesheet'; ss.id = 'smartcustomizer-' + styles[i] + '-css'; ss.href = this.baseUri + 'assets/styles/' + styles[i] + '.css?v=2000'; headElement.appendChild(ss); } }, initProductOptions: function () { }, updateSelectedOptions: function () { var groups = this.scOptionsContainer.querySelectorAll('fieldset'); Smartcustomizer.selectedProductOptions = {}; var price = parseFloat(this.productBasePrice); groups.forEach(function (group) { var groupId = group.getAttribute('data-id'); Smartcustomizer.selectedProductOptions[groupId] = []; var selectedOptions = group.querySelectorAll('input:checked, select'); selectedOptions.forEach(function (option) { Smartcustomizer.selectedProductOptions[groupId].push(option.value); var optionItem = Smartcustomizer.variantOptions[groupId]['options'][option.value]; // console.log(optionItem); if (optionItem['price']) { price += parseFloat(optionItem['price']); } }); }); if (!this.scPriceContainer || !this.scPriceField) { return; } if (price > 0) { this.scPriceField.innerHTML = this.parsePrice(price); } this.scPriceContainer.classList.toggle('hide', price === 0); }, getVariantPrice: function () { return parseFloat(this.variantPrices[this.variantId]); }, renderProductOptions: function () { if (this.scOptionsContainer.length === 0) { return; } var renderedProductOptions = this.scOptionsContainer.querySelectorAll('input, select'); renderedProductOptions.forEach(function (option) { option.removeEventListener('change', Smartcustomizer.changeProductOption, false); }); console.log('Model ID: ' + this.modelId); this.scOptionsContainer.innerHTML = ''; var html = ''; var productItem = this.productOptions[this.modelId]; var variantId = this.variantId.toString(); Smartcustomizer.customPricingActive = false; if (productItem.custom_pricing){ this.productBasePrice = this.getVariantPrice() + parseFloat(productItem.price); Smartcustomizer.customPricingActive = true; } else if (Smartcustomizer.priceContainer !== null) { Smartcustomizer.priceContainer.classList.remove('hide'); } var variationItem = null; for (let i = 0; i < Object.keys(productItem.variations).length; i++) { if (productItem.variations[i].ids.indexOf(variantId) >= 0) { variationItem = productItem.variations[i]; break; } } if (!variationItem) { console.log('changeContainersVisibility false'); this.changeContainersVisibility(false); return; } Smartcustomizer.variantOptions = {}; Object.keys(variationItem.options).forEach(function (groupId) { Smartcustomizer.variantOptions[groupId] = JSON.parse(JSON.stringify(productItem.options[groupId])); Smartcustomizer.variantOptions[groupId].options = {}; var optionIds = variationItem.options[groupId]; optionIds.forEach(function (optionId) { Smartcustomizer.variantOptions[groupId].options[optionId] = productItem.options[groupId].options[optionId]; }) }); var hasActiveSelectableOptions = false; Object.keys(Smartcustomizer.variantOptions).forEach(function (groupId) { var optionData = Smartcustomizer.variantOptions[groupId]; var options = optionData['options']; var addClass = optionData['rule'] == '1' && Object.keys(options).length === 1 && optionData['type'] !== 'opt_type_custom' ? ' hide' : ''; if (addClass !== ' hide'){ hasActiveSelectableOptions = true; } html += '
'; html += '' + optionData['name'] + ''; var firstItem = true; if (optionData.style !== '7') { // console.log(options); Object.keys(options).forEach(function (optionId) { var option = options[optionId]; var checked = firstItem && (optionData['rule'] == '1' || optionData['type'] === 'opt_type_print') ? 'checked' : ''; firstItem = false; html += ''; var style = ''; if (['1', '2', '3', '4'].indexOf(optionData.style) >= 0) { if (option['thumb']) { style = 'style="background: center center / cover url(\'' + option['thumb'] + '\');"'; } else if (option['hex']) { style = 'style="background-color: ' + option['hex'] + ';"'; } } html += ''; }); } else { html += '
'; html += ''; html += '
'; document.body.appendChild(this.scWrapper); this.scLoaderScreen = document.getElementById(this.appName + '-loader-screen'); this.scAppLoader = document.getElementById(this.appName + '-app-loader'); this.scIfrm = document.getElementById(this.appName + "-iframe"); this.scIfrm.addEventListener("load", this.loadSC); }, initMessageListener: function () { window.addEventListener('message', function (event) { if (event.origin + '/' !== this.baseUri) { // return false; } var data = event.data; switch (data.action) { case 'close_sc': Smartcustomizer.closeSC(); break; case 'hide_app': Smartcustomizer.hideApp(data.screenUrl); break; case 'show_app': Smartcustomizer.showApp(); break; case 'add_to_cart': Smartcustomizer.addToCart(data); break; case 'reload': Smartcustomizer.reload(); break; case 'redirect': Smartcustomizer.redirect(data.link); break; case 'send_ajax_request': Smartcustomizer.sendAjaxRequest(data.afterAction, data.uri, data.data, data.type, data.headers, data.params, event.source, event.origin); break; case 'set_cookie': Smartcustomizer.setCookie(data.name, data.value, data.days); break; case 'get_cookie': Smartcustomizer.getCookieIframe(data.name, event.origin); break; default: } }, false); }, initTranslations: function () { if (!this.translations[this.lng]) { return; } for (key in this.buttonTitles) { var tr = this.translations[this.lng]['app_button_' + key]; if (tr) { this.buttonTitles[key] = tr; } } tr = this.translations[this.lng]['custom_design_id']; if (tr) { this.customDesignLabel = tr; } }, getUriParams: function (param) { var urlParams = {}; var match, pl = /\+/g, search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = window.location.search.substring(1); while (match = search.exec(query)) { urlParams[decode(match[1])] = decode(match[2]); } return (param) ? ((urlParams[param]) ? urlParams[param] : null) : urlParams; }, openSC: function () { var addUriParams = ',shop.' + Shopify.shop + ',p.' + Smartcustomizer.uniqueId() + ',init.1'; if (this.ssid) { addUriParams += ',ssid.' + this.ssid; } var action = this.scLink.getAttribute('data-action'); if (action) { addUriParams += ',action.' + action; } var params = this.scLink.getAttribute('data-params'); if (params) { addUriParams += ',' + params; } if (Object.keys(Smartcustomizer.selectedProductOptions).length > 0){ var selectedProductOptions = JSON.stringify(Smartcustomizer.selectedProductOptions); selectedProductOptions = btoa(selectedProductOptions) addUriParams += ',opts.' + selectedProductOptions; } Smartcustomizer.scready = true; this.scIfrm.src = this.scIfrm.getAttribute('data-src') + addUriParams; if (Smartcustomizer.scready) { this.scAppLoader.classList.remove("hide"); Smartcustomizer.scWrapper.classList.add('active'); document.getElementsByTagName("body")[0].classList.add('modal-open'); if (document.getElementById('shopify-section-header')) { document.getElementById('shopify-section-header').style.display = "none"; } } }, closeSC: function () { setTimeout(function () { Smartcustomizer.scWrapper.classList.remove("active"); document.getElementsByTagName("body")[0].classList.remove("modal-open"); if (document.getElementById('shopify-section-header')) { document.getElementById('shopify-section-header').style.display = "block"; } }, 0); }, hideApp: function (screenUrl) { this.scLoaderScreen.setAttribute('src', screenUrl); this.scWrapper.classList.add('loading'); }, showApp: function () { this.scWrapper.classList.remove('loading'); }, reload: function () { location.reload(true); }, redirect: function (link) { window.location = link; }, loadSC: function () { Smartcustomizer.scAppLoader.classList.add("hide"); }, sendAjaxRequest: function (afterAction, uri, data, type, headers, params, source, origin) { headers = headers || {}; // console.log(uri); var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); var async = false; if (params) { if (params.async) { async = true; } } xhr.open(type || 'GET', uri, async); xhr.onreadystatechange = function () { if (xhr.readyState > 3 && xhr.status == 200) { var contentType = xhr.getResponseHeader("Content-Type"); var responseData = (contentType == 'application/json') ? JSON.parse(xhr.responseText) : xhr.responseText; //Smartcustomizer.scIfrm.contentWindow.sc.processAjaxResponse({data: responseData, action: 'process_ajax_response', afterAction: afterAction}); if (data && data.render_image_only != undefined) { responseData.render_image_only = data.render_image_only; } if (afterAction) { if (afterAction !== 'process_cart_items') { Smartcustomizer.scIfrm.contentWindow.postMessage({ data: responseData, action: 'process_ajax_response', afterAction: afterAction }, origin); } else { Smartcustomizer.processCartItems(responseData); } } } }; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); if (headers) { Object.keys(headers).forEach(function (header) { xhr.setRequestHeader(header, headers[header]); }); } //xhr.withCredentials = true; var sendData = null; if (data) { // sendData = JSON.stringify(data); // sendData = window.btoa(unescape(encodeURIComponent(sendData))); var sendData = typeof data == 'string' ? data : Object.keys(data).map( function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) } ).join('&'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } xhr.send(sendData); }, uniqueId: function () { return Math.floor(Date.now() / 1000); }, addToCart: function (data) { if (!data.properties || !data.properties.props) { return; } var properties = {}; for (key in data.properties.props) { properties[key] = data.properties.props[key]; } var quantity = this.productQuantity ? this.productQuantity.value : 1; var formData = { 'items': [{ 'id': data.properties.variationId, 'properties': properties, 'quantity': quantity }] }; setTimeout(function () { fetch(window.Shopify.routes.root + 'cart/add.js', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }) .then(response => { console.log(response.json()); if (response.ok) { window.location.href = '/cart'; } // return response.json(); }) .catch((error) => { console.error('Error:', error); }); }, 2000); }, renderCartElements: function () { console.log('renderCartElements'); var shopifyTemplateVersion = 1; var cartItems = document.querySelectorAll('.cart__row'); if (cartItems.length === 0) { var cartItems = document.querySelectorAll('.cart-item'); shopifyTemplateVersion = 2; } if (cartItems.length == 0) { return; } var customDesignIds = []; for (var i = 0; i < cartItems.length; i++) { var cid = shopifyTemplateVersion === 2 ? Smartcustomizer.renderV2TemplateCartItem(cartItems[i]) : Smartcustomizer.renderV1TemplateCartItem(cartItems[i]); if (cid) { customDesignIds.push(cid); } } if (customDesignIds.length == 0) { return; } this.renderAppElements(); this.scLinks = document.getElementsByClassName("sc-link"); for (var i = 0; i < this.scLinks.length; i++) { this.scLinks[i].removeEventListener('click', Smartcustomizer.openApp, false); this.scLinks[i].addEventListener('click', Smartcustomizer.openApp, false); } var data = { shop: Shopify.shop, ids: customDesignIds }; data = JSON.stringify(data); data = window.btoa(unescape(encodeURIComponent(data))); Smartcustomizer.sendAjaxRequest('process_cart_items', this.baseUri + ',action.designs_getimagesbyids,ajax.1', { data }, 'POST', [], null); Smartcustomizer.cartUpdateTimer = setInterval(function(){ //console.log('cartUpdateTimer'); if (Smartcustomizer.scLinks.length === 0){ clearInterval(Smartcustomizer.cartUpdateTimer); Smartcustomizer.renderCartElements(); } }, 2000); }, openApp: function (event) { Smartcustomizer.scLink = this; event.preventDefault(); Smartcustomizer.openSC(); }, removeSCProductLink: function(cid) { var item = document.querySelector('.sc-item[sc-id="' + cid + '"]'); if (!item){ return; } var links = item.querySelectorAll('a[href*="/products/"][href*="?variant="]'); links.forEach(link => { if (link.hasAttribute('href')) { link.removeAttribute('href'); } }); }, getSCLinkUpdateParams: function (cid) { return 'cid.' + cid + ',sa.order_update,lng.' + Smartcustomizer.lng; }, setCustomDesignLabel(cartItem) { if (this.cdOption === this.customDesignLabel) { return; } cartItem.innerHTML = cartItem.innerHTML.replace(this.cdOption, this.customDesignLabel); }, renderV2TemplateCartItem: function (cartItem) { var productOptions = cartItem.getElementsByClassName("product-option"); for (var i = 0; i < productOptions.length; i++) { var scOption = productOptions[i].textContent.split(this.cdOption); if (scOption.length !== 2) { continue; } var cid = scOption[1].replace(/\D/g, '').trim(); cartItem.setAttribute('sc-id', cid); this.setCustomDesignLabel(cartItem); cartItem.classList.add('sc-item'); var scLink = document.createElement('a'); scLink.className = "product-option sc-link"; scLink.setAttribute('href', '#'); scLink.setAttribute('data-params', Smartcustomizer.getSCLinkUpdateParams(cid)); scLink.innerHTML = Smartcustomizer.buttonTitles.edit; productOptions[i].parentNode.appendChild(scLink); return cid; break; } return null; }, renderV1TemplateCartItem: function (cartItem) { var cartItemText = cartItem.textContent; if (cartItemText.indexOf(this.cdOption) == -1) { return null; } var links = cartItem.getElementsByTagName('a'); var itemWrapper = null; var itemRemove = null; for (var i2 = 0; i2 < links.length; i2++) { if (links[i2].href.indexOf('/cart/change') != -1) { itemRemove = links[i2]; itemWrapper = links[i2].parentNode.parentNode; break; } } var metaData = itemWrapper.innerHTML.split(this.cdOption); if (metaData.length != 2) { return null; } var metaDataText = itemWrapper.innerText.split(this.cdOption); var cid = metaDataText[1].replace(/\D/g, '').trim(); cartItem.setAttribute('sc-id', cid); this.setCustomDesignLabel(cartItem); cartItem.classList.add('sc-item'); var scLink = document.createElement('a'); var actionElementClasses = itemRemove.className; scLink.className = actionElementClasses + " sc-link"; scLink.setAttribute('data-params', Smartcustomizer.getSCLinkUpdateParams(cid)); scLink.setAttribute('href', '#'); scLink.innerHTML = Smartcustomizer.buttonTitles.edit; metaData[0] += this.cdOption; var cidEnd = metaData[1].indexOf(cid) + cid.length; metaData[1] = metaData[1].slice(0, cidEnd) + "
" + scLink.outerHTML + metaData[1].slice(cidEnd); itemWrapper.innerHTML = metaData.join(''); return cid; }, processCartItems: function (images) { if (Object.keys(images).length === 0) { return; } for (cdid in images) { var linkParams = Smartcustomizer.getSCLinkUpdateParams(cdid); var editLink = document.querySelector(".sc-link[data-params='" + linkParams + "']"); if (editLink !== null) { //console.log(editLink); editLink.setAttribute('data-params', editLink.getAttribute('data-params') + ',hash.' + images[cdid].hash); } var imageElements = document.querySelectorAll(".sc-item[sc-id='" + cdid + "'] img"); if (imageElements.length > 0) { for (var i = 0; i < imageElements.length; i++) { imageElements[i].src = images[cdid].image + '?p=' + Smartcustomizer.uniqueId(); imageElements[i].removeAttribute('srcset'); } } if (!images[cdid].spv2){ Smartcustomizer.removeSCProductLink(cdid); } } }, setCookie: function (name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 3600000)); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + escape(value) + expires + "; path=/"; }, getCookie: function (name) { var nameEQ = name + "="; var parts = document.cookie.split(';'); var l = parts.length; for (var i = 0; i < l; i++) { var part = parts[i]; while (part.charAt(0) == ' ') { part = part.substring(1, part.length); } if (part.indexOf(nameEQ) == 0) { return unescape(part.substring(nameEQ.length, part.length)); } } return null; }, removeCookie: function (name) { setCookie(name, "", -1); }, getCookieIframe: function (name, origin) { Smartcustomizer.scIfrm.contentWindow.postMessage({ name, value: this.getCookie(name), action: 'process_get_cookie' }, origin); }, generateHash: function (length) { length = length || 40; var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }, parsePrice: function (inputPrice) { if (typeof inputPrice !== 'number') { throw new Error('Input price must be a number'); } const decimalMatch = this.priceFormat.match(/\[(0+)(?:\.(0+))?\]/); if (!decimalMatch) { throw new Error('Invalid price format'); } const integerPartLength = decimalMatch[1].length; const decimalPlaces = decimalMatch[2] ? decimalMatch[2].length : 0; const formattedPrice = inputPrice.toFixed(decimalPlaces); const formattedString = this.priceFormat.replace(/\[(0+)(?:\.(0+))?\]/, formattedPrice); return formattedString; }, getFormattedOptionPrice: function (price) { price = parseFloat(price); return price > 0 ? ' (+' + this.parsePrice(price) + ')' : ''; } }; if (meta.page.pageType == 'product' || meta.page.pageType == 'cart') { Smartcustomizer = new Smartcustomizer(); Smartcustomizer.initApp(); if (meta.page.pageType == 'product') { Smartcustomizer.renderProductElements(); document.addEventListener('trackingConsentAccepted', function () { console.log('trackingConsentAccepted event fired'); }); if (window.Shopify.loadFeatures) { console.log('loadFeatures'); window.Shopify.loadFeatures([ { name: 'consent-tracking-api', version: '0.1', } ], function (error) { if (error) { throw error; } const userCanBeTracked = window.Shopify.customerPrivacy.userCanBeTracked(); const userTrackingConsent = window.Shopify.customerPrivacy.getTrackingConsent(); }); } } else { Smartcustomizer.renderCartElements(); } } document.addEventListener("DOMContentLoaded", function () { });