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","price_selector":"","options_selector":""}; this.variantSelector = null; this.productForm = null; this.productQuantity = null; this.scContainer = null; this.scOptionsContainer = null; this.scPriceContainer = null; this.priceContainer = null; this.priceParseContainer = null; this.scPriceField = null; this.productIds = {"3570":"14187","3571":"14201"}; this.modelId = null; this.productOptions = {"14187":{"id":14187,"name":"Mug personnalis\u00e9 - 3D","sku":"","price":0,"custom_pricing":false,"options":{"14188":{"name":"Print","type":"opt_type_print","style":"1","class":"sc-select-type-img sc-select-style-circle","rule":"1","options":[{"id":"14189","name":"Print Front","hex":null,"price":0,"thumb":"https:\/\/app.smartcustomizer.com\/uploads\/ZEo3Q1FhNmEwVENKdVUramRhQThUdz09\/img\/catalog\/12\/14189_thumb_en.jpg"}]}},"variations":[{"name":"Variation 1","ids":["3570"],"options":{"14188":["14189"]}}],"app_types":["design_customize","design_upload"]},"14201":{"id":14201,"name":"Personnalis\u00e9 T-Shirt - 3D","sku":"","price":0,"custom_pricing":true,"options":{"14202":{"name":"Print","type":"opt_type_print","style":"5","class":"sc-select-type-txt","rule":"1","options":[{"id":"14203","name":"Impression devant","hex":null,"price":0},{"id":"14204","name":"Impression arri\u00e8re","hex":null,"price":0},{"id":"14207","name":" Impression avant et Arri\u00e8re ","hex":null,"price":5},{"id":"14205","name":"Impression \u00e9paule gauche","hex":null,"price":5},{"id":"14206","name":"Impression Multiple","hex":null,"price":10},{"id":"14208","name":"Impression \u00e9paule droite","hex":null,"price":5}]},"14209":{"name":"Size","type":"opt_type_size","style":"6","class":"sc-select-type-pills","rule":"1","options":[{"id":"14210","name":"S","hex":null,"price":0},{"id":"14211","name":"M","hex":null,"price":0},{"id":"14212","name":"L","hex":null,"price":0},{"id":"14219","name":"XL","hex":null,"price":0}]},"14213":{"name":"Color","type":"opt_type_color","style":"1","class":"sc-select-type-img sc-select-style-circle","rule":"1","options":[{"id":"14214","name":"Blanc","hex":"#f7f7f7","price":0},{"id":"14215","name":"Noir","hex":"#000000","price":0}]}},"variations":[{"name":"Variation 1","ids":["3571"],"options":{"14202":["14203","14204","14205","14206","14207","14208"],"14209":["14210","14211","14212","14219"],"14213":["14214","14215"]}}],"app_types":["design_customize","design_upload"]}}; this.variantOptions = {}; this.variationItems = {}; this.selectedProductOptions = {}; this.priceFormat = '€[0.00]'; this.productBasePrice = 0; this.cartUpdateTimer = null; this.ssid = null; this.replaceAddToCartButton = false; this.params = ''; this.renderCartElementsRendered = false; this.customPricingActive = false; this.lng = 'en'; this.translations = {"fr":{"app_button_design":"Cr\u00e9er en ligne","app_button_upload":"Importer un fichier de cr\u00e9ation","custom_design_id":"Identifiant de cr\u00e9ation personnalis\u00e9e :","app_button_customize":"Personnaliser le produit","app_button_edit":"Modifier le design"}}; this.buttonTitles = { customize: 'Customize product', edit: 'Edit Design', design: 'Design online', upload: 'Upload Design file' }; this.cssConfig = {}; } Smartcustomizer.prototype = { initApp: function () { this.initMessageListener(); this.initTranslations(); }, initTranslations: function(){ let currentLang = document.documentElement.lang; if (currentLang){ this.lng = currentLang.split('-')[0]; } if (this.translations[this.lng] == undefined) { return; } for (key in this.buttonTitles) { var tr = this.translations[this.lng]['app_button_' + key]; if (tr) { this.buttonTitles[key] = tr; } } }, createCustomizerDropdown: function(selector) { const button = document.querySelector(selector); if (!button || button.closest('.smartcustomizer-dropdown-container')) return; const wrapper = document.createElement('div'); wrapper.className = 'smartcustomizer-dropdown-container'; button.before(wrapper); wrapper.appendChild(button); button.classList.add('smartcustomizer-dropdown-button'); const dropdown = document.createElement('div'); dropdown.className = 'smartcustomizer-dropdown'; dropdown.innerHTML = ` ` + this.buttonTitles.design + ` ` + this.buttonTitles.upload + ` `; wrapper.appendChild(dropdown); // Toggle dropdown button.addEventListener('click', function (e) { e.preventDefault(); dropdown.classList.toggle('show'); button.classList.toggle('active'); }); document.addEventListener('click', function (e) { if (!wrapper.contains(e.target)) { dropdown.classList.remove('show'); button.classList.remove('active'); } }); }, renderAppBaseElements: function(){ if (Smartcustomizer.replaceAddToCartButton){ Smartcustomizer.addToCartBtn.style.display = 'none'; } this.scLink = this.renderCustomizeButton(this.addToCartBtn); var modelId = Smartcustomizer.productIds?.[Smartcustomizer.variantSelector?.value]; var appTypes = Smartcustomizer.productOptions[modelId]?.app_types; if (appTypes && appTypes.length == 2){ this.createCustomizerDropdown('.smartcustomizer-link'); } if (appTypes && appTypes.length == 1 && appTypes[0] === 'design_upload'){ this.scLink.classList.add('upload-design'); } this.scLinks = document.getElementsByClassName('smartcustomizer-link'); for (var i = 0; i < this.scLinks.length; i++) { this.scLinks[i].addEventListener('click', function (event) { event.preventDefault(); if (this.classList.contains('disabled') || this.classList.contains('smartcustomizer-dropdown-button')) { return; } var params = 'mid.' + Smartcustomizer.modelId + ',pid.' + Smartcustomizer.productId + ',pvid.' + Smartcustomizer.variantId + ',lng.' + Smartcustomizer.lng; if (this.classList.contains('upload-design')) { params += ',app_type.upload'; } this.setAttribute('data-params', params); Smartcustomizer.scLink = this; Smartcustomizer.openSC(); }, false); } this.renderProductOptionElements(); this.renderAppElements(); // this.changeVariant(); }, changeVariant: function () { console.log('changeVariant'); setTimeout(function () { var scLinks = document.getElementsByClassName("smartcustomizer-link"); const value = Smartcustomizer.productIds?.[Smartcustomizer.variantSelector?.value]; if (value && value !== '0' && scLinks.length == 0) { console.log('renderAppBaseElements'); Smartcustomizer.renderAppBaseElements(); } if (scLinks.length === 0){ return; } if (Smartcustomizer.addToCartBtn.disabled || Object.keys(Smartcustomizer.productIds).length === 0 || Smartcustomizer.productIds[Smartcustomizer.variantSelector.value] == undefined) { for (var i = 0; i < scLinks.length; i++) { scLinks[i].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 { for (var i = 0; i < scLinks.length; i++) { scLinks[i].classList.remove('hide'); } 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); }, getItemById: function(arr, id) { return arr.find(item => item.id === id); }, 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.getItemById(Smartcustomizer.variantOptions[groupId]['options'], option.value); if (optionItem && 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); }, contains: function(selector, text) { const elements = document.querySelectorAll(selector) return [].filter.call(elements, (element) => { return RegExp(text).test(element.textContent) }) }, logError: function (message) { console.log('Smartcustomizer error: ' + message); }, setupDesignLinks: function (){ Smartcustomizer.scLinks = document.getElementsByClassName("smartcustomizer-link-edit"); if (Smartcustomizer.scLinks.length == 0){ return; } Smartcustomizer.renderAppElements(); for (var i = 0; i < Smartcustomizer.scLinks.length; i++) { Smartcustomizer.scLinks[i].addEventListener('click', function (event) { Smartcustomizer.scLink = this; event.preventDefault(); Smartcustomizer.openSC(); }, false); } }, renderCartElements: function () { if (!document.body.classList.contains('woocommerce-cart') && !document.body.classList.contains('woocommerce-checkout')) { return; } console.log('renderCartElements'); if (typeof window.wc == "undefined" || typeof window.wc.blocksCheckout == "undefined"){ Smartcustomizer.setupDesignLinks(); return; } // Smartcustomizer.scCartItemKeys = []; Smartcustomizer.scCartItemData = {}; const { registerCheckoutFilters } = window.wc.blocksCheckout; const modifyCartItemClass = ( defaultValue, extensions, args ) => { if (Smartcustomizer.renderCartElementsRendered){ return defaultValue; } // Smartcustomizer.renderCartElementsRendered = true; // return defaultValue; const pageType = args?.context; const addCardItemClass = pageType === 'cart' || pageType === 'summary'; if (!addCardItemClass){ return defaultValue; } if (args.cartItem.length === 0 || typeof args.cartItem == "undefined" || typeof args.cartItem.item_data == "undefined" || args.cartItem.item_data.length === 0){ if (Smartcustomizer.scCartItemData[args.cartItem.key]){ args.cartItem.images[0].src = args.cartItem.images[0].thumbnail = Smartcustomizer.scCartItemData[args.cartItem.key].image; args.cartItem.item_data = Smartcustomizer.scCartItemData[args.cartItem.key].data; } else{ return defaultValue; } } var scDesignId = null; var isUploadedDesign = false; for (var i = 0; i < args.cartItem.item_data.length; i++) { if (!args.cartItem.item_data[i]['key'] || args.cartItem.item_data[i]['key'] !== 'smartcustomizer-design-id'){ continue; } scDesignId = args.cartItem.item_data[i]['value']; if (args.cartItem.item_data[i]['uploaded_design']){ isUploadedDesign = true; } console.log(args.cartItem.item_data[i]); args.cartItem.images[0].src = args.cartItem.images[0].thumbnail = args.cartItem.item_data[i].image; Smartcustomizer.scCartItemData[args.cartItem.key] = {data: args.cartItem.item_data, image: args.cartItem.images[0].src}; } var scDesignMetaClassName = 'wc-block-components-product-details__smartcustomizer-design-id'; /* var scDesignMetaItems = document.getElementsByClassName(scDesignMetaClassName); if (scDesignMetaItems.length > 0){ scDesignMetaItems[0].style.display = 'none'; } */ setTimeout(function () { var scDesignCartItem = Smartcustomizer.contains('.smartcustomizer-cart-item', scDesignId); if (scDesignCartItem.length === 0){ return; } var scDesignMetaItem = scDesignCartItem[0].getElementsByClassName(scDesignMetaClassName); console.log('scDesignMetaItem length: ' + scDesignMetaItem.length); if (scDesignMetaItem.length === 0){ return; } if (pageType === 'summary'){ scDesignMetaItem[0].remove(); return; } addParams = isUploadedDesign ? ',app_type.upload' : ''; scDesignMetaItem[0].innerHTML = '' + Smartcustomizer.buttonTitles.edit + ''; scDesignMetaItem[0].className = 'smartcustomizer-link-wrapper'; //scDesignMetaItem[0].style.display = ''; if (document.getElementsByClassName(scDesignMetaClassName).length > 0){ return; } Smartcustomizer.setupDesignLinks(); }, 100); return 'smartcustomizer-cart-item'; }; registerCheckoutFilters( 'example-extension', { cartItemClass: modifyCartItemClass, } ); function updateCartView() { if (!document.body.classList.contains('woocommerce-cart')){ return false; } // var pageClass = document.body.classList.contains('woocommerce-cart') ? 'wc-block-cart-items' : 'wc-block-checkout'; var itemWrapper = document.querySelector('.wc-block-cart-items'); if (!itemWrapper) { return false; } if (itemWrapper.textContent.includes('smartcustomizer-design-id')) { let buttons = itemWrapper.querySelectorAll("button"); var minusBnt = null; for (let btn of buttons) { if (btn.textContent.trim() === "+" && minusBnt) { btn.click(); minusBnt.click(); break; } if (btn.textContent.trim() === "-") { minusBnt = btn; } } return true; } else { return false; } } setTimeout(() => { updateCartView(); /* if (updateCartView ()){ var amountPlus = document.querySelector('.wc-block-components-quantity-selector__button--plus'); if (amountPlus){ // amountPlus.click(); } var amountMinus = document.querySelector('.wc-block-components-quantity-selector__button--minus'); if (amountMinus){ // amountMinus.click(); } }; */ }, 3000); }, renderCustomizeButton: function(addToCartBtn){ var scLink = null; if (this.embedConfig.button_html != undefined){ var linkEl = document.createElement('div'); linkEl.innerHTML = this.embedConfig.button_html.trim(); scLink = linkEl.firstChild; } if (scLink == null){ scLink = document.createElement(addToCartBtn.nodeName); scLink.className = addToCartBtn.className + ' ' + this.appName + '-link'; scLink.id = this.appName + '-link'; scLink.appendChild(document.createTextNode(this.buttonTitles.customize)); } // scLink.innerHTML += ''; scLink.style.setProperty('display', 'none', 'important'); if (this.embedConfig.button_position != undefined && this.embedConfig.button_position !== 'bottom') { addToCartBtn.parentNode.insertBefore(scLink, addToCartBtn); if (this.embedConfig.button_position === 'replace') { this.replaceAddToCartButton = true; } } else { addToCartBtn.parentNode.appendChild(scLink); } setTimeout(function () { scLink.style.display = ''; }, 1000); return scLink; }, renderProductFormElements: function () { console.log('renderProductFormElements'); 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.cart"); } if (this.productForm == null) { this.logError('Form element not found.'); return false; } var addToCart = this.productForm.querySelector('[name="add-to-cart"]'); this.productId = this.variantId = addToCart ? addToCart.value : null; // this.variantId = this.productForm.dataset.product_id; if (!this.productId){ return; } // console.log(this.productId); // console.log(Smartcustomizer.productIds); if (Smartcustomizer.productIds[this.productId]) { Smartcustomizer.modelId = Smartcustomizer.productIds[this.productId]; } /* fetch('/wp-admin/admin-ajax.php?action=wc-ajax_get_variation', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ product_id: 15, // optional: attributes can be sent here }) }) .then(res => res.json()) .then(data => { console.log('Variation response:', data); }); */ /* let variationsData = this.productForm.dataset.product_variations; console.log(variationsData); if (variationsData && variationsData != 'false') { variationsData = JSON.parse(variationsData); this.variationItems = variationsData.reduce((result, variation) => { let variantId = variation.variation_id.toString(); // result[variantId] = variation.display_price; if (Smartcustomizer.productIds[variantId]) { Smartcustomizer.modelId = Smartcustomizer.productIds[variantId]; } return result; }, {}); } else{ /* jQuery(this.productForm).on( 'wc_variation_form', function() { console.log( 'wc_variation_form' ) console.log( jQuery(this).data( 'product_variations' ) ) } ); jQuery(this.productForm).on('woocommerce_variation_has_changed', console.log('woocommerce_variation_has_changed') ); } if (!this.modelId){ // return; } */ 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); } if (this.addToCartBtn == null){ this.addToCartBtn = this.productForm.querySelector("button[type='submit']"); } if (this.addToCartBtn.length == 0) { this.logError('Add to cart button element not found.'); return false; } this.variantSelector = document.getElementsByName('variation_id')[0] || addToCart; jQuery(this.productForm).on('found_variation', function(event, variation) { console.log('Active variation:', variation); Smartcustomizer.changeVariant(); }); /* jQuery(this.productForm).on('woocommerce_variation_has_changed', this.changeVariant); */ return true; }, renderProductElements: function () { if (Object.keys(Smartcustomizer.productIds).length === 0){ return; } if (this.renderProductFormElements() && Smartcustomizer.modelId){ this.changeVariant(); } }, renderProductOptionElements: function(){ 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'); 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 = this.priceParseContainer = 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.'); } } /* if (!this.priceParseContainer){ this.priceParseContainer = document.querySelector('.woocommerce-variation-price'); if (!this.priceParseContainer){ this.priceParseContainer = document.querySelector('[data-block-name="woocommerce/product-price"]') } } */ /* Product without variants */ /* if (Object.keys(this.variationItems).length === 0){ this.variationItems[this.productId] = this.parseFinalPrice(); } */ }, parseFinalPrice: function() { let finalPrice = null; const variationPrice = document.querySelector('.woocommerce-variation-price .price'); if (variationPrice) { finalPrice = this.parseWCPrice(variationPrice); console.log('Final price from selected variation:', finalPrice); return finalPrice; } const mainPrice = document.querySelector('[data-block-name="woocommerce/product-price"]'); if (mainPrice) { finalPrice = this.parseWCPrice(mainPrice); console.log('Final price for simple product:', finalPrice); return finalPrice; } console.warn('Final price could not be determined.'); return finalPrice; }, parseWCPrice: function(priceElement) { if (!priceElement) return null; const insPrice = priceElement.querySelector('ins .woocommerce-Price-amount'); const delPrice = priceElement.querySelector('del .woocommerce-Price-amount'); const basePrice = priceElement.querySelector('.woocommerce-Price-amount'); if (insPrice) { return this.extractPriceValue(insPrice.textContent); } if (basePrice) { return this.extractPriceValue(basePrice.textContent); } else if (delPrice) { return this.extractPriceValue(delPrice.textContent); } return null; }, extractPriceValue: function(priceText) { const cleanPrice = priceText.replace(/[^\d.,]/g, '').replace(',', '.'); return parseFloat(cleanPrice); }, renderStyleLinks: function () { var styleElement = document.getElementById('smartcustomizer-css'); if (styleElement) { return; } var headElement = document.getElementsByTagName('head')[0]; if (!document.getElementById('google-fonts')) { headElement.insertAdjacentHTML('beforeend', '\ \ '); } var styles = ['wc.smartcustomizer']; for (let i = 0; i < styles.length; i++) { var ss = document.createElement("link"); ss.type = 'text/css'; ss.rel = 'stylesheet'; ss.id = 'smartcustomizer-css'; ss.href = this.baseUri + 'assets/styles/' + styles[i] + '.css?v=2000'; headElement.appendChild(ss); } }, 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); }); this.scOptionsContainer.innerHTML = ''; var html = ''; var productItem = this.productOptions[this.modelId]; var variantId = this.variantId.toString(); Smartcustomizer.customPricingActive = false; if (productItem.custom_pricing){ if (Smartcustomizer.variationItems[Smartcustomizer.variantId] ==undefined){ Smartcustomizer.variationItems[Smartcustomizer.variantId] = Smartcustomizer.parseFinalPrice(); } this.productBasePrice = parseFloat(Smartcustomizer.variationItems[Smartcustomizer.variantId]) + 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]; productItem.options[groupId].options.forEach(function (optionItem) { if (optionIds.indexOf(optionItem.id) != -1){ Smartcustomizer.variantOptions[groupId].options.push(optionItem); } }); }); 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' : ''; console.log(optionData); console.log(addClass); if (addClass !== ' hide'){ hasActiveSelectableOptions = true; } html += '
'; html += '' + optionData['name'] + ''; var firstItem = true; if (optionData.style !== '7') { options.forEach(function (option) { 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 += '
'; this.scWrapper.innerHTML = '
'; if (this.cssConfig){ this.scWrapper.innerHTML = '' + this.scWrapper.innerHTML; } 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); }, 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.' + btoa(sc_config.site_url) + ',init.1,pc.wc'; if (this.ssid){ addUriParams += ',ssid.' + this.ssid; } if (this.params){ addUriParams += ',' + this.params; } var action = this.scLink.getAttribute('data-action'); if (action) { addUriParams += ',action.' + action; } var params = this.scLink.getAttribute('data-params'); if (params) { addUriParams += ',' + params; } var queryParams = []; if (Object.keys(Smartcustomizer.selectedProductOptions).length > 0) { var selectedProductOptions = btoa(JSON.stringify(Smartcustomizer.selectedProductOptions)); queryParams.push('opts=' + encodeURIComponent(selectedProductOptions)); } $recentDesignsData = this.getCookie('recent_designs_data'); if ($recentDesignsData) { queryParams.push('rd=' + encodeURIComponent($recentDesignsData)); } queryParams.push('p=' + Smartcustomizer.uniqueId()); Smartcustomizer.scready = true; var separator = this.scIfrm.getAttribute('data-src').indexOf('?') !== -1 ? '&' : '?'; this.scIfrm.src = this.scIfrm.getAttribute('data-src') + addUriParams + (queryParams.length ? separator + queryParams.join('&') : ''); if (Smartcustomizer.scready) { this.scAppLoader.classList.remove("hide"); Smartcustomizer.scWrapper.classList.add('active'); } }, closeSC: function () { setTimeout(function () { Smartcustomizer.scWrapper.classList.remove("active"); }, 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){ Smartcustomizer.scIfrm.contentWindow.postMessage({data: responseData, action: 'process_ajax_response', afterAction: afterAction}, origin); } } }; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); if (headers){ Object.keys(headers).forEach( function (header) { xhr.setRequestHeader(header, headers[header]); }); } var sendData = null; if (data){ 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) { return; } var addToCartUrl = this.scLink.getAttribute('data-url'); if (addToCartUrl){ addToCartUrl = sc_config.shop_url + addToCartUrl; for (key in data.properties) { addToCartUrl += '&' + key + '=' + data.properties[key]; } window.location = addToCartUrl; } else{ //if (document.getElementsByName('add-to-cart').length === 0){ data.properties['add-to-cart'] = this.productId; //} for (const key in data.properties) { if (key != 'design_options'){ const property = document.createElement('input'); property.type = 'hidden'; property.name = key; property.value = data.properties[key]; this.productForm.appendChild(property); } else{ const designOptions = data.properties[key]; for (const key2 in designOptions) { const input = document.createElement('input'); input.type = 'hidden'; input.name = `design_options[${key2}]`; input.value = designOptions[key2]; this.productForm.appendChild(input); } } } this.productForm.submit(); } }, getAjax: function(url, success) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('GET', url); xhr.onreadystatechange = function() { if (xhr.readyState>3 && xhr.status==200) success(xhr.responseText); }; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); //xhr.withCredentials = true; xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(); return xhr; }, 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) + ')' : ''; } }; document.addEventListener("DOMContentLoaded", function () { console.log('Smartcustomizer'); Smartcustomizer = new Smartcustomizer(); Smartcustomizer.initApp(); Smartcustomizer.renderProductElements(); Smartcustomizer.renderCartElements(); });