var goodpabaseUrl="https://addons.good-apps.co/";var goodpaApiUrl="https://addons.good-apps.co/";var goodpaShop="perfumes-bogotaa.myshopify.com";var goodpaTriggerEvents=[6];var goodpaPageIds=[];var goodpaCertainBtns=[];var goodpaCurrencyCode="USD";var goodpaCurrencySymbol="$";var goodpaUrl=window.location.href;var goodpaVersion="165" var goodpaShowPopupAllPeriod=0;var goodpaShowPopupPerDay=0;var goodpaWhenPopupDisplayed=0;var goodpaRemoveFunnelProducts=0;var hucsWidget={"widget_name":"Elegance","widget_type":"1","widget_themes":"style_1","popup_type":"3","design_type":{"position":"center","animation":"animate__fadeIn","layout":"list","widget_width":"container","template":"accesories"},"product":{"background_img":"#fff","product_mark_color":"#000","background":"#000","product_button_color":"#b3b3b3","prod_border_width":"2","prod_border_color":"#b3b3b3","prod_border_radius":"12","prod_title_show":true,"prod_title_color":"#2e3843","prod_title_font_size":"16","prod_title_font_weight":"400","prod_title_font_style":"normal","prod_title_line_height":"19","price_show":true,"price_color":"#52c41a","price_font_size":"18","price_font_weight":"700","price_font_style":"normal","price_line_height":"20"},"custom_css":""};var goodpaMaxShowOffer=0;var goodpaTriggerButton="";var goodpabuyItNow="";var goodpaCartButton="";var goodpaInlineWidget="";var goodpaInlineWidgetCartPage="";var goodpaInlineWidgetThankYouPage="";var goodpaInlineWidgetSelectedPage="";var goodpaInlineWidgetBtnSelector="";var goodpaCheckoutBtnSelector="";var goodpaCartSubtotal="";var goodpaCartSubtotalContainer="";var goodpaActiveApp="1";var goodpaAppName="ProductAddons";if(!goodpaApp){var goodpaApp=function(){if(goodpaActiveApp==="0"){return;} const noImage=goodpabaseUrl+'assets/images/no-image.jpg';let currentProductId;let purchaseData=[];let statisticArr=[];let iframe;let productsData=[];let excludeOffers=[];let triggerProduct=false;const appContainerClass='.goodpa-app-container' const url=location.href;const storeUrl=new URL(url).origin;let addedToCart=false;let addonContainers=[];const offerTypes={crossSell:1,upsell:2,bundle:3,postPurchase:4,discount:5,frequentlyBoughtTogether:6,homePage:8,exitIntent:7,cartPage:9,beforeCheckout:10,slider:11,bundleByProduct:13,bundleComboProducts:14,bundleBuilder:15,fbt:16,volumeDiscount:17,addons:18} const triggerTypes={addToCart:'1',cartPage:'2',thankYouPage:'3',selectedPages:'4',certainButtons:'5',productPage:'6',exitIntent:'7',homePage:'8',collectionPage:'9',blogPage:'10',beforeCheckout:'11',buyItNow:'12'} const popupTypes={popup:'1',float_popup:'2',inline:'3'} const inlineWidgetPosition={before:'1',after:'2'} styleLoader() if(Shopify.designMode){buildPreviewContainer();} function buildPreviewContainer(){const rootDiv=document.querySelector(appContainerClass);if(!rootDiv)return;const html='The Good APP will be displayed here!';const element=document.createElement("div");element.classList.add('goodhl-app-preview');element.style.padding='20px';element.style.border='1px solid #e4e4e4';element.style.borderRadius='8px';element.style.textAlign='center';element.innerHTML=html;rootDiv.append(element);} function clearPreviewContainer(){const previewContainer=document.querySelector(appContainerClass);if(previewContainer){previewContainer.innerHTML='';}} if(location.href.includes('offerId')&&location.href.includes(goodpaAppName)){setCrisp();buildPreviewMessage();addPreviewMessageStyles();setTimeout(()=>{openPopup();},0) popupEvents();} function buildPreviewMessage(){const html=`

Hi, I’m your assistant from Good Apps Product Accessories App. If you can’t see the Widget, click ‘Fix for ME’ and we’ll resolve it immediately.

`;const element=document.createElement("div");element.classList.add('goodpa_minipopup','goodpa_minipopup_hide');element.innerHTML=html;const rootDiv=document.body;rootDiv.append(element);} function addPreviewMessageStyles(){const styles=` .goodpa_minipopup { position: fixed; left: 30px; bottom: 10%; width: 300px; height: 350px; padding: 30px; background: #fff; box-shadow: 0px 3px 16px 0px rgba(0,0,0,0.08); border: 1px solid #f1f1f2; border-radius: 8px; z-index: 999; transition: 0.7s; } @media (max-width: 480px){ .goodpa_minipopup { width: 80%; } } @media (max-width: 380px){ .goodpa_minipopup { padding: 15px; } } .goodpa_minipopup_hide { transform: translateY(120%); opacity: 0; } .goodpa_minipopup_content { position: relative; display: flex; height: 100%; flex-direction: column; justify-content: space-between; align-items: center; } .goodpa_minipopup__close { position: absolute; width: 10px; top: -25px; right: -17px; transition: 0.3s; cursor: pointer; } @media (max-width: 380px){ .goodpa_minipopup__close { width: 8px; top: -16px; right: -7px; } } .goodpa_minipopup__close:hover { transform: scale(1.2); } .goodpa_minipopup__message { text-align: center; margin: 0px; font-size: 16px; font-weight: 400; text-transform: none; } @media (max-width: 380px){ .goodpa_minipopup__message { font-size: 14px; } } .goodpa_minipopup__btns { display: flex; justify-content: center; gap: 10px; } @media (max-width: 480px){ .goodpa_minipopup__btns { flex-direction: column; } } .goodpa_minipopup__btn { padding: 10px 25px; border-radius: 6px; font-size: 12px; transition: 0.5s; cursor: pointer; border: none; color: white; } .goodpa_minipopup__btn--yellow { background: #FFB73E; } .goodpa_minipopup__btn--yellow:hover { background: #b09059; } .goodpa_minipopup__btn--gray { background: #f9f9f9; color: #78829d } .goodpa_minipopup__btn--gray:hover { background: #f1f1f2; } `;const element=document.createElement("style");element.innerHTML=styles;const rootDiv=document.head;rootDiv.append(element);};function openPopup(){const popup=document.querySelector('.goodpa_minipopup');popup.classList.remove('goodpa_minipopup_hide');};function closePopup(){const popup=document.querySelector('.goodpa_minipopup');popup.classList.add('goodpa_minipopup_hide');};function popupEvents(){const closeBtn=document.querySelector('.goodpa_minipopup__btn--gray');const closeIcon=document.querySelector('.goodpa_minipopup__close');closeBtn.addEventListener('click',()=>{closePopup();}) closeIcon.addEventListener('click',()=>{closePopup();}) const opener=document.querySelector('.goodpa_minipopup__btn--yellow');opener.addEventListener('click',(e)=>{e.preventDefault();$crisp.push(["do","chat:open"]) $crisp.push(["do","message:send",["text","Hi, I’m using GA Product Accessories and can’t see the widget. Please assist."]]);})} function setCrisp(){const scriptTag=document.createElement('script');scriptTag.setAttribute('type','text/javascript');scriptTag.innerHTML=` window.$crisp=[]; window.CRISP_WEBSITE_ID="4e50b386-fde3-4da7-97f2-80e38503c5ab"; $crisp.push(["set", "user:email", "{{ $userEmail }}"]); $crisp.push(["set", "user:name", "{{ $storeOwnerName }}"]); $crisp.push(["set", "session:segments", [["Accessories"]]]); $crisp.push(["set", "session:event", ["user:welcome"]]); $crisp.push(["set", "session:data", [ [ ["myshopifyurl", "${storeUrl}"], ["totalsales", "{{ $allAmount }}"], ["totalOffers", "{{ $countOffers }}"] ] ]]); (function(){ d=document; s=d.createElement("script"); s.src="https://client.crisp.chat/l.js"; s.async=1; d.getElementsByTagName("head")[0].appendChild(s); })();`;const rootDiv=document.head;rootDiv.append(scriptTag);$crisp.push(["do","chat:close"])} goodpaCurrencySymbol=decodeHTML(goodpaCurrencySymbol.replace(/(<([^>]+)>)/ig,""));const currentCurrencyCode=Shopify.currency.active;let currentCurrencySymbol=goodpaCurrencySymbol;let currencyRate=1;if(goodpaCurrencyCode!==currentCurrencyCode){const country=Shopify.country;currencyRate=Shopify.currency.rate;const regexStr=`[${getMainCurrencySymbol()}]`;const regex=new RegExp(regexStr,'g') currentCurrencySymbol=goodpaCurrencySymbol.replace(regex,getCurrencySymbol(country,currentCurrencyCode));} function getCurrencySymbol(locale,currency){return(0).toLocaleString(locale.toLowerCase(),{style:'currency',currency:currency,minimumFractionDigits:0,maximumFractionDigits:0}).replace(/\d/g,'').trim()} function getMainCurrencySymbol(){if(goodpaCurrencySymbol.includes('{{')){return goodpaCurrencySymbol.replace(/{{(.*?)}}/ig,'').trim();}else{return goodpaCurrencySymbol.trim();}} function getPriceByRate(price){return(parseFloat(price)*currencyRate).toFixed(2);} function getStorePriceByRate(price){return(parseFloat(price)/ currencyRate).toFixed(2);} function currencyFormat(num){if(currentCurrencySymbol.includes('{{')){return currentCurrencySymbol.replace(/{{(.*?)}}/ig,formatNumber(num));}else{return currentCurrencySymbol+formatNumber(num);}} function formatNumber(num){num=parseFloat(num).toFixed(2);return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,");} function decodeHTML(html){const txt=document.createElement('textarea');txt.innerHTML=html;return txt.value;};function setCookieData(){let url=location.href;const goodpaCurrentShownPerMonth=getCookie('goodpaCurrentShownPerMonth');const goodpaCurrentShownPerDay=getCookie('goodpaCurrentShownPerDay');const ZERO=0;const oneMonth=new Date(Date.now()+3600000*24*25);const oneWeek=new Date(Date.now()+3600000*24*7);const oneDay=new Date(Date.now()+3600000*24);let currentDate=new Date(Date.now());currentDate=currentDate.toUTCString();if(url.includes('#')){url=url.split('#');if(url[url.length-1]){let parameter='#'+url[url.length-1];setCookie('goodpaUrl',parameter,{expires:oneWeek});}} if(!goodpaCurrentShownPerMonth){setCookie('goodpaCurrentShownPerMonth',ZERO,{expires:oneMonth});setCookie('goodpaStartDatePerMonth',currentDate,{expires:oneMonth});} if(!goodpaCurrentShownPerDay){setCookie('goodpaCurrentShownPerDay',ZERO,{expires:oneDay});setCookie('goodpaStartDatePerDay',currentDate,{expires:oneDay});}} setCookieData();function setCookie(name,value,options={}){options={path:'/',...options};if(options.expires instanceof Date){options.expires=options.expires.toUTCString();} let updatedCookie=encodeURIComponent(name)+"="+encodeURIComponent(value);for(let optionKey in options){updatedCookie+="; "+optionKey;let optionValue=options[optionKey];if(optionValue!==true){updatedCookie+="="+optionValue;}} document.cookie=updatedCookie;} function getCookie(name){let matches=document.cookie.match(new RegExp("(?:^|; )"+name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,'\\$1')+"=([^;]*)"));return matches?decodeURIComponent(matches[1]):undefined;} function setContainerId(){return`goodpa-app-${makeId(5)}`;} function buildPopUpType(dataOffer,currentProductId,triggerType){for(let key in dataOffer.offers){const offerItem=dataOffer.offers[key];mainOfferId=dataOffer.offers[key].main_offer_id;buildInlineWidget({dataOffer,offerItem,currentProductId,triggerType,mainOfferId});}} function styleLoader(){const headID=document.head;const link=document.createElement('link');link.type='text/css';link.rel='stylesheet';headID.appendChild(link);link.href=goodpabaseUrl+`css/goodpa-product-accesories.css?v=${goodpaVersion}`;};function buildInlineWidget(params){const{offerItem}=params;let rootId=setContainerId();let nodeElement=null;nodeElement=getInlineNode();function getInlineNode(){let defaultNodeElements=[];let inlineWidgetArr=[];if(params.triggerType=='2'){defaultNodeElements=['.cart__items'];inlineWidgetArr=goodpaInlineWidgetCartPage.length?decodeHTML(goodpaInlineWidgetCartPage).split(','):inlineWidgetArr;}else{defaultNodeElements=['form[action*="/cart/add"]'];inlineWidgetArr=goodpaInlineWidget.length?decodeHTML(goodpaInlineWidget).split(','):inlineWidgetArr;} const commonInlineWidgetArr=inlineWidgetArr.concat(defaultNodeElements);const uniqueInlineWidgetArr=[...new Set(commonInlineWidgetArr)];if(uniqueInlineWidgetArr.length){for(let i=0;i
${brandLabel} `;const element=document.createElement("div");element.classList.add("goodpa-inline");element.innerHTML=html;const rootDiv=document.getElementById(rootId);rootDiv.append(element);const product_data=offerItem.products;const allow_message=offerItem.allow_message;let fillAddonsProductCount=0;for(let key in product_data){if(product_data.hasOwnProperty(key)){for(const[productId,variantsArr]of Object.entries(product_data[key])){const productArray=dataOffer.products;if(!(Array.isArray(productArray))){let params={product1:productArray[`${productId}`],variantsArr,rootId,offerObj} const template=hucsWidget.design_type.template;if(template=="accesories"){fillAccesoriesWidget(params,allow_message,dataOffer);}else if(template=="circlesquare"){fillCirclesquareWidget(params,allow_message);document.querySelector('.goodpa-product__wrapp').setAttribute('style','display: flex; flex-wrap: wrap; justify-content: center;')}if(template=="amazon"){fillAmazonWidget(params,allow_message,fillAddonsProductCount);fillAmazonTemplateImg(params,fillAddonsProductCount);fillAddonsProductCount++}else if(!template){fillAccesoriesWidget(params,allow_message,dataOffer);}}}}} addonContainers.push({rootId,mainOfferId:offerObj.mainOfferId,offerId:offerObj.offerId});actionsAddons(element);actionsImg(element);buildWidget(hucsWidget,rootId);setTimeout(()=>{rootDiv.style.display='block';},500);} function buildBrandLabel(dataOffer){if(!dataOffer.brand){return'';} const brandingHtml='Powered by GoodApps';return brandingHtml;} function getActiveVariants(allVariants,activeVariants){const variants=[];for(let key in allVariants){if(activeVariants.includes(allVariants[key].productId)){variants.push(allVariants[key]);}else{}} return variants;} function createAddedProductsData(variantId,propertyId){let targetId;if(document.querySelector('.form input[name="id"]')){targetId=document.querySelector('.form input[name="id"]').value;}else if(document.querySelector('shopify-payment-terms')){let idAttr=document.querySelector('shopify-payment-terms').getAttribute('variant-id');targetId=idAttr;}else if(document.querySelector('select[name="id"]')){const select=document.querySelector('select[name="id"]');targetId=select.value;}else{const query=window.location.search.substring(1);const vars=query.split('&');vars.forEach((v)=>{let pair=v.split('=');if(pair.length>1){targetId=pair[1]}else{targetId=data.product.variants[0].id;}})} if(!targetId)return;const localProductsData=localStorage.getItem('goodpaProductsData');productsData=localProductsData?JSON.parse(localProductsData):productsData;let productData={targetProductId:targetId,funnelProducts:[]} if(productsData.length){const checkTargetId=productsData.find(item=>item.targetProductId===targetId);if(checkTargetId){setProductsData(checkTargetId);}else{productsData.push(productData);setProductsData(productData);}}else{productsData.push(productData);setProductsData(productData);} function setProductsData(data){data.funnelProducts.push({variantId:variantId,propertyId:propertyId})} localStorage.setItem('goodpaProductsData',JSON.stringify(productsData));} function calcVariantsDiscountPrice(product,variants){const variantPrice=getPriceByRate(parseFloat(variants['variantPrice']));const discountVal=product.discount_type!=="%"?getPriceByRate(product.discount):product.discount;if(product.discount_type==="%"){return(variantPrice-(variantPrice*+discountVal / 100)).toFixed(2);}else{return(+variantPrice- +discountVal).toFixed(2);}} function fillAmazonTemplateImg(params,id){const{product1,variantsArr}=params;const product={...product1};const variants=getActiveVariants(product.variants,variantsArr);product.variants=variants;const productImg=product.variants[0].image||noImage;const htmlimg=`
Product
`;const element=document.createElement("div");element.setAttribute('data-active',false);element.classList.add("goodpa_image");element.innerHTML=htmlimg;const rootDiv=document.querySelector('.goodpa__img');rootDiv.append(element);} function calcTotalProductPrice(product,price,qty=1){if(product.variants.length>1){return price} return(+qty>1)?price*+qty:price;} function changeVariantPrice(element,price){const priceContainer=element.querySelector(".goodpa-compare-price");const mainPriceContainer=element.querySelector(".goodpa-price");const discountContainer=element.querySelector(".goodpa-save");let newPrice=price;if(discountContainer){const discountValue=discountContainer.getAttribute("data-discount");const discountType=discountContainer.getAttribute("data-discountType");if(discountType==="%"){newPrice=(+price-(+price*+discountValue / 100)).toFixed(2);}else{newPrice=(+price- +discountValue).toFixed(2);}} if(priceContainer){priceContainer.innerText=currencyFormat(price);} mainPriceContainer.innerText=currencyFormat(newPrice)} function changeVariantImage(element,activeImage){if(!activeImage)return;const image=element.querySelector('.goodpa-product__img img');image.setAttribute('src',activeImage);} function changeVariantImageAmazon(element,activeImage,id){if(!activeImage)return;const imgWrap=element.querySelector('.goodpa__img');const image=imgWrap.querySelector(`.goodpa-product--img[data-id="${id}"]`);image.setAttribute('src',activeImage);} function fillAccesoriesWidget(params,allow_message,dataOffer){const{product1,variantsArr,rootId,offerObj}=params;const product={...product1};const variants=getActiveVariants(product.variants,variantsArr);product.variants=variants;const productTitle=product.title;const productDescription=product.description;const productImg=product.variants[0].image||noImage;let productPrice=getPriceByRate(product.variants[0].variantPrice);let minQty=product.bundle_qty?product.bundle_qty:1;let variantsBlockHtml='';let variantIds=[];if(product.variants.length>1){let variantsHtml=`';variantsBlockHtml=variantsHtml;variantIds.push(product.variants[0].productId);}else{variantIds.push(product.variants[0].productId);} let totalProductPrice=calcTotalProductPrice(product,productPrice,minQty);let currency='';if(document.querySelector('.disclosure__button')){productPrice=productPrice;currency=` ${Shopify.currency.active}`;}else{productPrice=currencyFormat(productPrice);} const html=`
Product

${productTitle}

${productDescription}

${productPrice}${currency}
${variantsBlockHtml}
`;const element=document.createElement("div");element.setAttribute('data-active',false);element.classList.add("goodpa-product__item","product__item","product__item--list","goodpa-product__item--metro","goodpa-product-border--color","goodpa-product-border","goodpa-product-item","goodpa-bundle-product","goodpa-inactive");element.innerHTML=html;const variationSelect=element.querySelectorAll('.goodpa-variations');if(variationSelect.length){variationSelect.forEach(select=>{select.addEventListener("change",function(e){e.preventDefault();let variantPrice=this.selectedOptions[0].getAttribute('data-price');let variantDiscountPrice=this.selectedOptions[0].getAttribute('data-diccounted-price');const variantStorePrice=this.selectedOptions[0].getAttribute('data-store-price');const activeImg=this.selectedOptions[0].getAttribute('data-image');const element=this.closest('.goodpa-product-item');const variants=element.querySelectorAll('.goodpa-variations');let productId=this.value;if(variants.length>1){let variantIds=[];let resultPrice=0;let resultDiscountPrice=0;variants.forEach(item=>{const itemId=item.selectedOptions[0].value;const itemPrice=+item.selectedOptions[0].getAttribute('data-price');const itemDiscountPrice=+item.selectedOptions[0].getAttribute('data-diccounted-price');variantIds.push(itemId);resultPrice+=itemPrice;resultDiscountPrice+=itemDiscountPrice;}) productId=variantIds.join(',');variantPrice=resultPrice;variantDiscountPrice=resultDiscountPrice;} element.querySelector('.goodpa-product__content').setAttribute('data-productId',productId);element.querySelector('.goodpa-product__content').setAttribute('data-storePrice',variantStorePrice);element.querySelector('.goodpa-price').setAttribute('data-product-price',variantDiscountPrice);changeVariantImage(element,activeImg);changeVariantPrice(element,variantPrice);});})} previewProductEvents(element,product,rootId,null,offerObj);const rootDiv=getAppSelector('.goodpa-product__wrapp',rootId);rootDiv.append(element);} function fillCirclesquareWidget(params,allow_message){const{product1,variantsArr,rootId,offerObj}=params;const product={...product1};const variants=getActiveVariants(product.variants,variantsArr);product.variants=variants;const productTitle=product.title;const productDescription=product.description;const productImg=product.variants[0].image||noImage;let productPrice=getPriceByRate(product.variants[0].variantPrice);let minQty=product.bundle_qty?product.bundle_qty:1;let variantsBlockHtml='';let variantIds=[];if(product.variants.length>1){let variantsHtml=`';variantsBlockHtml=variantsHtml;variantIds.push(product.variants[0].productId);}else{variantIds.push(product.variants[0].productId);} let totalProductPrice=calcTotalProductPrice(product,productPrice,minQty);productPrice=currencyFormat(productPrice);const html=`
Product

${productTitle}

${productDescription}

${productPrice}
${variantsBlockHtml}
`;const element=document.createElement("div");element.setAttribute('data-active',false);element.classList.add("goodpa-product__item","product__item","goodpa-product__item--metro","goodpa-product-item","goodpa-inactive","goodpa-product-grid");element.innerHTML=html;changeShape(element) const variationSelect=element.querySelectorAll('.goodpa-variations');if(variationSelect.length){variationSelect.forEach(select=>{select.addEventListener("change",function(e){e.preventDefault();let variantPrice=this.selectedOptions[0].getAttribute('data-price');let variantDiscountPrice=this.selectedOptions[0].getAttribute('data-diccounted-price');const variantStorePrice=this.selectedOptions[0].getAttribute('data-store-price');const activeImg=this.selectedOptions[0].getAttribute('data-image');const element=this.closest('.goodpa-product-item');const variants=element.querySelectorAll('.goodpa-variations');let productId=this.value;if(variants.length>1){let variantIds=[];let resultPrice=0;let resultDiscountPrice=0;variants.forEach(item=>{const itemId=item.selectedOptions[0].value;const itemPrice=+item.selectedOptions[0].getAttribute('data-price');const itemDiscountPrice=+item.selectedOptions[0].getAttribute('data-diccounted-price');variantIds.push(itemId);resultPrice+=itemPrice;resultDiscountPrice+=itemDiscountPrice;}) productId=variantIds.join(',');variantPrice=resultPrice;variantDiscountPrice=resultDiscountPrice;} element.querySelector('.goodpa-product__content').setAttribute('data-productId',productId);element.querySelector('.goodpa-product__content').setAttribute('data-storePrice',variantStorePrice);element.querySelector('.goodpa-price').setAttribute('data-product-price',variantDiscountPrice);changeVariantImage(element,activeImg);changeVariantPrice(element,variantPrice);});})} previewProductEvents(element,product,rootId,null,offerObj);const rootDiv=getAppSelector('.goodpa-product__wrapp',rootId);rootDiv.append(element);} function fillAmazonWidget(params,allow_message,id){const{product1,variantsArr,rootId,offerObj}=params;const product={...product1};const variants=getActiveVariants(product.variants,variantsArr);product.variants=variants;const productTitle=product.title;const productDescription=product.description;let productPrice=getPriceByRate(product.variants[0].variantPrice);let minQty=product.bundle_qty?product.bundle_qty:1;let variantsBlockHtml='';let variantIds=[];if(product.variants.length>1){let variantsHtml=`';variantsBlockHtml=variantsHtml;variantIds.push(product.variants[0].productId);}else{variantIds.push(product.variants[0].productId);} let totalProductPrice=calcTotalProductPrice(product,productPrice,minQty);productPrice=currencyFormat(productPrice);const html=`

${productTitle}

${productDescription}

${productPrice}
${variantsBlockHtml}
`;const element=document.createElement("div");element.setAttribute('data-active',false);element.setAttribute('data-id',id);element.setAttribute('style','margin: 10px; justify-content: start;');element.classList.add("goodpa-product__item","product__item","product__item--list","goodpa-product__item--metro","goodpa-product-item","goodpa-bundle-product","goodpa-inactive","goodpa-product-amazon");element.innerHTML=html;const variationSelect=element.querySelectorAll('.goodpa-variations');if(variationSelect.length){variationSelect.forEach((select)=>{select.addEventListener("change",function(e){e.preventDefault();const id=e.target.closest('.goodpa-product__item').getAttribute('data-id');let variantPrice=this.selectedOptions[0].getAttribute('data-price');let variantDiscountPrice=this.selectedOptions[0].getAttribute('data-diccounted-price');const variantStorePrice=this.selectedOptions[0].getAttribute('data-store-price');const activeImg=this.selectedOptions[0].getAttribute('data-image');const element=this.closest('.goodpa-product-item');const variants=element.querySelectorAll('.goodpa-variations');let productId=this.value;if(variants.length>1){let variantIds=[];let resultPrice=0;let resultDiscountPrice=0;variants.forEach(item=>{const itemId=item.selectedOptions[0].value;const itemPrice=+item.selectedOptions[0].getAttribute('data-price');const itemDiscountPrice=+item.selectedOptions[0].getAttribute('data-diccounted-price');variantIds.push(itemId);resultPrice+=itemPrice;resultDiscountPrice+=itemDiscountPrice;}) productId=variantIds.join(',');variantPrice=resultPrice;variantDiscountPrice=resultDiscountPrice;} element.querySelector('.goodpa-product__content').setAttribute('data-productId',productId);element.querySelector('.goodpa-product__content').setAttribute('data-storePrice',variantStorePrice);element.querySelector('.goodpa-price').setAttribute('data-product-price',variantDiscountPrice);const parentElement=element.closest('.goodpa-inline');changeVariantImageAmazon(parentElement,activeImg,id);changeVariantPrice(element,variantPrice);});})} previewProductEvents(element,product,rootId,null,offerObj);const rootDiv=getAppSelector('.goodpa-product__wrapp',rootId);rootDiv.append(element);} function cloneNodeBtn(classBtn){const button=document.querySelector(`${classBtn}`);if(button){const buttonClone=button.cloneNode(true);button.insertAdjacentElement('afterend',buttonClone);button.style.display="none";buttonClone.classList.add('goodpa_btn_clone');buttonClone.addEventListener('click',function(e){e.preventDefault();if(addonContainers.length){const addonsOffers=getAddonsProducts(addonContainers);addAddonsProducts(addonsOffers.products);sendAddonStatistic(addonsOffers.offers);addedToCart=true;setTimeout(()=>{button.click();},500)}})}} function changeShape(element){const changeShape=hucsWidget.product.change_shape if(changeShape==true){element.querySelector('.goodpa-product__img-wrap').classList.add('goodpa-square');element.querySelector('.product__button').classList.add('goodpa-square');}else{element.querySelector('.goodpa-product__img-wrap').classList.remove('goodpa-square');element.querySelector('.product__button').classList.remove('goodpa-square');}} function actionsImg(element){const template=hucsWidget.design_type.template;if(template=='amazon'){const img=element.querySelectorAll('.goodpa-product__img-wrap');img.forEach(item=>{item.addEventListener("click",function(e){const el=this.closest('.goodpa_image');const index=[...el.parentElement.children].indexOf(el);const prod_wrap=element.querySelector('.goodpa-product__wrapp');const prod=prod_wrap.children[index];prod.querySelector('.goodpa-product__title').click();})})}} function actionsAddons(element){const allowCheckbox=element.querySelectorAll('.goodpa-product-item');allowCheckbox.forEach(item=>{item.addEventListener("click",function(e){const el=this.closest('.goodpa-product-item');const variations=e.target.closest('.goodpa-variations');const title=e.target.closest('.goodpa-prod-title');const img=e.target.closest('.goodpa-product__img');const notification=e.target.closest('.goodpa-product__notification');const index=[...el.parentElement.children].indexOf(el);const template=hucsWidget.design_type.template;if(!title&!variations&!img&!notification){if(el.classList.contains('goodpa-inactive')){el.setAttribute('data-active',true);const allow_notification=el.querySelector('input[name="allow_message"]').value;if(allow_notification=='true'){el.querySelector(".goodpa-product__notification").classList.remove('hide');}else{el.querySelector(".goodpa-product__notification").classList.add('hide')} if(template=='amazon'){const allow_notification=el.querySelector('input[name="allow_message"]').value;const el_wrap=el.closest('.goodpa-popup__products');const img_wrap=el_wrap.querySelector('.goodpa__img') const img=img_wrap.children[index];img.querySelector('.goodpa-product__img').classList.remove('goodpa-product__img--inactive');} el.classList.add('goodpa-product-border--color');el.classList.remove('goodpa-inactive');el.querySelector('.product__button').classList.remove('goodpa-inactive--button');el.querySelector('.product__button--mark').classList.remove('hide');if(el.querySelector('.goodpa-product__img-wrap')){el.querySelector('.goodpa-product__img-wrap').classList.remove('goodpa-product__img-wrap_inactive');}}else{el.setAttribute('data-active',false);const allow_notification=el.querySelector('input[name="allow_message"]').value;if(allow_notification=='true'){el.querySelector(".goodpa-product__notification").classList.add('hide');} if(template=='amazon'){const el_wrap=el.closest('.goodpa-popup__products');const img_wrap=el_wrap.querySelector('.goodpa__img') const img=img_wrap.children[index];img.querySelector('.goodpa-product__img').classList.add('goodpa-product__img--inactive');} el.classList.remove('goodpa-product-border--color');el.classList.add('goodpa-inactive');el.querySelector('.product__button').classList.add('goodpa-inactive--button');el.querySelector('.product__button--mark').classList.add('hide');if(el.querySelector('.goodpa-product__img-wrap')){el.querySelector('.goodpa-product__img-wrap').classList.add('goodpa-product__img-wrap_inactive');}}}});})} function getAddonsProducts(addonContainers){const allProductsData=[];let uniqIds=[];const addonsData=[];addonContainers.forEach(({rootId,mainOfferId,offerId})=>{let offerData={mainOfferId,offerId} const container=document.querySelector(`#${rootId}`);let products=container.querySelectorAll('.goodpa-product__item');products.forEach(product=>{const isActive=product.getAttribute('data-active');const message=product.querySelector("textarea[name='notification_input']").value if(isActive==='true'){const targetElement=addonsData.find(el=>+el.offerId===+offerId);if(!targetElement){addonsData.push(offerData);} const variants=product.querySelectorAll('.goodpa-variations');if(variants.length){variants.forEach(variantItem=>{const variantId=variantItem.selectedOptions[0].value;if(uniqIds.includes(variantId)){const targetElement=allProductsData.find(el=>+el.variantId===+variantId);targetElement.qty=+targetElement.qty+1;}else{allProductsData.push({propertyId:makeId(5),variantId,storePrice:variantItem.selectedOptions[0].getAttribute('data-store-price'),discountType:null,discountValue:null,qty:1,mainOfferId,offerId,message,rootId}) uniqIds.push(variantId);}})}else{const variantId=product.querySelector('.goodpa-product__content').getAttribute('data-productId');if(uniqIds.includes(variantId)){const targetElement=allProductsData.find(el=>+el.variantId===+variantId);targetElement.qty=+targetElement.qty+1;}else{allProductsData.push({propertyId:makeId(5),variantId,storePrice:product.querySelector('.goodpa-product__content').getAttribute('data-storePrice'),discountType:null,discountValue:null,qty:1,mainOfferId,offerId,message,rootId}) uniqIds.push(variantId);}}}});});return{products:allProductsData,offers:addonsData}} function addAddonsProducts(products){let items=[];if(!products.length)return;products.forEach((productItem,index,array)=>{const isLastItem=index===array.length-1;items.push({'id':productItem.variantId,'quantity':+productItem.qty,'properties':{offer:productItem.propertyId,note:productItem.message}});if(isLastItem){addItem(items).then(()=>{products.forEach((productItem)=>{let mainOfferId=productItem.mainOfferId;let offerId=productItem.offerId;let variantId=productItem.variantId;let propertyId=productItem.propertyId;let storePrice=productItem.storePrice;createPurchaseData(mainOfferId,offerId,variantId,propertyId,storePrice);createAddedProductsData(variantId,propertyId);})});}});} function sendAddonStatistic(offers){if(!offers.length)return;offers.forEach(({mainOfferId,offerId})=>{sendStatistic(mainOfferId,offerId,true);})} function makeId(length){let result='';const characters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';const charactersLength=characters.length;for(let i=0;ielement.classList.remove(`goodpa-cart-btn-text-upsell`));cartBtnTextAdded.forEach((element)=>element.classList.remove(`goodpa-cart-btn-added-text-upsell`));cartBtn.forEach((element)=>element.setAttribute('data-cart','add'));if(beforeAlert){beforeAlert.classList.remove(`goodpa-alert-upsell`);} break;} getObjJsonKeys(rootId,widgetJson,dataJsonTranslation,"translation");getObjJsonKeys(rootId,widgetJson,dataJsonMainSection);getObjJsonKeys(rootId,widgetJson,dataJsonProductStyle);getObjJsonKeys(rootId,widgetJson,dataShowHide,"show");if(type!=offerTypes.volumeDiscount){setProductDescription(rootId,widgetJson);}else if(type===offerTypes.volumeDiscount){setActiveColor(widgetJson,rootId);} const custom_css=widgetJson.custom_css;const customCssDiv=getAppSelector('#goodpa-custom-css',rootId);if(custom_css){customCssDiv.innerText=custom_css.replace(/.goodpa-/g,`#${rootId} .goodpa-`);}else{customCssDiv.innerText='';} const prodDesc=getAppSelectorAll('.goodpa-desc-short',rootId);prodDesc.forEach((element)=>{let str=element.innerText.trim();if(str.length>100){let trimmedStr=str.substring(0,100)+"...";element.innerText=trimmedStr;}});} function fillWidgetSettings(widgetJson,rootId){const goodpaPopup=getAppSelector('.goodpa-popup',rootId);const goodpaWrap=getAppSelector('.goodpa-popup__wrap',rootId);const goodpaBody=getAppSelector('.goodpa-popup__body',rootId);const productWrapp=getAppSelector('.goodpa-product__wrapp',rootId);const position=widgetJson.design_type.position,animation=widgetJson.design_type.animation,layout=widgetJson.design_type.layout,layout_col=widgetJson.design_type.layout_col?widgetJson.design_type.layout_col:'grid-item-2',widgetWidth=widgetJson.design_type.widget_width;if(widgetJson.widget_type!=offerTypes.volumeDiscount){if(goodpaPopup){goodpaPopup.classList.remove('goodpa-popup__position--full','goodpa-popup__position--right_bottom','goodpa-popup__position--left_bottom','goodpa-popup__position--bottom','goodpa-popup__position--top','goodpa-popup__position--center');goodpaPopup.classList.add(`goodpa-popup__position--${position}`);goodpaPopup.classList.remove("goodpa-hide");goodpaWrap.setAttribute('class','goodpa-popup__wrap');goodpaWrap.classList.add(`animate__animated`,`${animation}`);}} if(widgetJson.widget_type!=offerTypes.slider){if(widgetJson.widget_type!=offerTypes.volumeDiscount){productWrapp.classList.remove('goodpa-product--grid','goodpa-product--list','goodpa-product--metro','goodpa-grid-item-2','goodpa-grid-item-3','goodpa-grid-item-4');const productItem=getAppSelectorAll('.goodpa-product__item',rootId);productItem.forEach((element)=>element.classList.remove('goodpa-product__item--grid','goodpa-product__item--list','goodpa-product__item--metro'));if(layout){productWrapp.classList.add(`goodpa-product--${layout}`,`goodpa-${layout_col}`);productItem.forEach((element)=>element.classList.add(`goodpa-product__item--${layout}`));}else{productWrapp.classList.add('goodpa-product--grid','goodpa-grid-item-2');productItem.forEach((element)=>element.classList.add(`goodpa-product__item--grid`));}} goodpaBody.classList.remove('goodpa-width-container','goodpa-width-full');goodpaBody.classList.add(`goodpa-width-${widgetWidth}`);}} function getObjJsonKeys(rootId,widgetJson,obj,type){for(let key in obj){if(type==="show"){setShowHide(rootId,widgetJson,obj[key].data,obj[key].value,obj[key].element);}else if(type==="translation"){setJsonTranslation(rootId,widgetJson,obj[key].data,obj[key].value,obj[key].element);}else{setJsonData(rootId,widgetJson,obj[key].data,obj[key].value,obj[key].element,obj[key].cssOption,obj[key].cssType);}}} function setJsonTranslation(rootId,widgetJson,obj,value,element){if(!widgetJson[obj])return;const option=widgetJson[obj][value];if(option==null)return;const elements=getAppSelectorAll('.'+element,rootId);elements.forEach((element)=>{element.innerText=option;})} function setJsonData(rootId,widgetJson,obj,value,element,styleOpt,type){if(!widgetJson[obj])return;const option=widgetJson[obj][value];let inputOption=option;if(option==null)return;if(styleOpt==="border-top-right-radius"&&element===".goodpa-bg-top"&&inputOption!=0){inputOption=+inputOption+3;} if(type==="size"){inputOption=inputOption+'px';} const elements=getAppSelectorAll('.'+element,rootId);elements.forEach((element)=>{element.style[styleOpt]=inputOption;})} function setShowHide(rootId,widgetJson,obj,value,element){if(!widgetJson[obj])return;const option=widgetJson[obj][value];if(option==null)return;const elements=getAppSelectorAll('.'+element,rootId);elements.forEach((element)=>{if(option){element.classList.remove('goodpa-hide');}else{element.classList.add('goodpa-hide');}})} function setProductDescription(rootId,widgetJson){const option=widgetJson['product']['prod_desc_show_full'];if(option==null)return;const shortDescription=getAppSelectorAll('.goodpa-desc-short',rootId);const fullDescription=getAppSelectorAll('.goodpa-desc-full',rootId);shortDescription.forEach((element)=>{if(option){element.classList.add('goodpa-hide');}else{element.classList.remove('goodpa-hide');}}) fullDescription.forEach((element)=>{if(option){element.classList.remove('goodpa-hide');}else{element.classList.add('goodpa-hide');}})} async function fetchCart(){const options={method:'GET',headers:{"Content-Type":"application/json","Accept":"application/json"}};const resp=await fetch("/cart.json",options);return await resp.json();} async function addItem(items){const options={method:'POST',headers:{"Content-Type":"application/json","Accept":"application/json"},body:JSON.stringify({'items':items})};const url="/cart/add.json";const resp=await fetch(url,options);return await resp.json();} async function removeItem(data){const options={method:'POST',headers:{"Content-Type":"application/json","Accept":"application/json"},body:JSON.stringify({...data,quantity:0})};const url="/cart/change.js";const resp=await fetch(url,options);return await resp.json();} function removeItemByLine(oneBasedLineIndex){return removeItem({line:oneBasedLineIndex});} async function fetchProduct(handle){const options={method:'GET',headers:{"Content-Type":"application/json","Accept":"application/json"}};const resp=await fetch(`/products/${handle}.json`,options);return resp.json();} function setOfferFetchUrl(offerParams,url){const domain=goodpaShop;const product_id=offerParams.productId?`&product_id=${offerParams.productId}`:'';const variants_id=offerParams.variantsId?`&variants_id=${offerParams.variantsId}`:'';const trigger_event=offerParams.triggerType;const display_on_device=window.innerWidth>991?'3':'2';const cart_value=0;const page_id=trigger_event==='4'?`&page_select=${offerParams.targetCode}`:'';const button_code=trigger_event==='5'?`&button_code=${encodeURIComponent(offerParams.targetCode)}`:'';let logged_user;const exclude_offers=excludeOffers.length?`&exclude_offers=${excludeOffers.join(',')}`:'';const cart=0;if(typeof shopifyAnalitics!=='undefined'){logged_user=ShopifyAnalytics.meta.page.customerId?'1':'0';}else{logged_user='0';} let goodpaUrl=getCookie('goodpaUrl');let parameter='';if(goodpaUrl){parameter=goodpaUrl;} const url_parameter=parameter?`&url_parameter=${encodeURIComponent(parameter)}`:'';return goodpaApiUrl+`${url}?domain=${domain}${product_id}${variants_id}&cart=${cart}&trigger_event=${trigger_event}&display_on_device=${display_on_device}&cart_value=${cart_value}&logged_user=${logged_user}${page_id}${button_code}${url_parameter}${exclude_offers}`;} async function offerFetch(offerParams){setExcludeOffers();getExcludeCartOffer();const options={headers:{'Content-Type':'application/json',"Accept":"application/json"}};let url=setOfferFetchUrl(offerParams,'api/front/offers');const resp=await fetch(url,options);if(!resp.ok){throw new Error(`HTTP error, status = ${resp.status}`);} return await resp.json();} async function createStatisticFetch(main_offer_id,offer_id,addedToCart,funnelViews){const options={method:'POST',headers:{'Content-Type':'application/json',"Accept":"application/json"},body:JSON.stringify(createStatisticRequest(main_offer_id,offer_id,addedToCart,funnelViews))};let url=goodpaApiUrl+`api/front/statistic`;const resp=await fetch(url,options);if(!resp.ok){throw new Error(`HTTP error, status = ${resp.status}`);} return await resp.text();} function createStatisticRequest(main_offer_id,offer_id,addedToCart,views){const domain=goodpaShop;const action=addedToCart?'accept':'decline';return{domain:domain,main_offer_id:main_offer_id,offer_id:offer_id,action:action,views:views}} function sendStatistic(mainOfferId,offerId,funnelAction=false){if(statisticArr.includes(offerId)){const offerIdsArr=statisticArr.filter(element=>element===offerId);let funnelViews;if(funnelAction){funnelViews=offerIdsArr.length>1?0:1;}else{funnelViews=offerIdsArr.length>=1?0:1;} createStatisticFetch(mainOfferId,offerId,funnelAction,funnelViews);}else{createStatisticFetch(mainOfferId,offerId,funnelAction,1);}} async function createPurchaseFetch(data){const options={method:'POST',headers:{'Content-Type':'application/json',"Accept":"application/json"},body:JSON.stringify(createPurchaseRequest(data))};let url=goodpaApiUrl+`api/front/purchase`;const resp=await fetch(url,options);if(!resp.ok){throw new Error(`HTTP error, status = ${resp.status}`);} return await resp.text();} function createPurchaseRequest(data){const domain=goodpaShop;const main_offer_id=data.main_offer_id;const amount=[];data.offer_amount.forEach(item=>{amount.push({offer_id:item.offer_id,amount:item.amount})});return{domain:domain,main_offer_id:main_offer_id,offer_amount:amount}} function createPurchaseData(mainOfferId,offerId,variantId,propertyId,storePrice){const localOfferData=localStorage.getItem('goodpaPurchaseData');purchaseData=localOfferData?JSON.parse(localOfferData):purchaseData;let offerData={'main_offer_id':mainOfferId,'offer':[]} if(purchaseData.length){const checkMainOfferId=purchaseData.find(item=>item.main_offer_id===mainOfferId);if(checkMainOfferId){setOfferData(checkMainOfferId);}else{purchaseData.push(offerData);setOfferData(offerData);}}else{purchaseData.push(offerData) setOfferData(offerData);} function setOfferData(data){data.offer.push({offer_id:offerId,product_id:variantId,property_id:propertyId,product_store_price:storePrice})} localStorage.setItem('goodpaPurchaseData',JSON.stringify(purchaseData));localStorage.setItem('goodpaPurchaseDataApp',JSON.stringify(purchaseData));} const s_ajaxListener=new Object();s_ajaxListener.tempOpen=XMLHttpRequest.prototype.open;s_ajaxListener.tempSend=XMLHttpRequest.prototype.send;s_ajaxListener.callback=function(){let thisUrl=this.url.replace(/\?(.+)/ig,"");if(thisUrl==="/cart/add.js"||thisUrl==="/cart/add.json"||thisUrl==="/cart/add"){const triggerType=triggerTypes.addToCart;let dataStr,variantsId;if(typeof(this.data)==='object'){if(this.data instanceof FormData){for(let pair of this.data.entries()){if(pair[0]==='id'){variantsId=pair[1];}}}}else if(typeof(this.data)==='string'){if(this.data.includes('&')){dataStr=this.data.split('&');dataStr.forEach(element=>{if(element.includes('id=')){variantsId=element.split('=');variantsId=variantsId[variantsId.length-1];}});}else if(this.data.includes('{')){dataStr=JSON.parse(this.data);variantsId=dataStr.id?dataStr.id:dataStr.items[0].id;}} if(addedToCart===false){if(addonContainers.length){const addonsOffers=getAddonsProducts(addonContainers);sendAddonStatistic(addonsOffers.offers) addAddonsProducts(addonsOffers.products);} currentProductId=variantsId;if(Object.keys(goodpaTriggerEvents).length&&goodpaTriggerEvents.includes(+triggerType)){if(location.href.includes('/products/')){addToCartProductPage(triggerType,variantsId,currentProductId);}else{addToCartTrigger(triggerType,variantsId,currentProductId);}}}} if(thisUrl==="/cart/change.js"||thisUrl==="/cart/change.json"||thisUrl==="/cart/change"||thisUrl==="cart.js"){setTimeout(()=>{removeFunnelProducts();setTimeout(()=>{cartPageDiscount();},1000);},500);}} XMLHttpRequest.prototype.open=function(a,b){if(!a)var a='';if(!b)var b='';s_ajaxListener.tempOpen.apply(this,arguments);s_ajaxListener.method=a;s_ajaxListener.url=b;if(a.toLowerCase()=='get'){s_ajaxListener.data=b.split('?');s_ajaxListener.data=s_ajaxListener.data[1];}} XMLHttpRequest.prototype.send=function(a,b){if(!a)var a='';if(!b)var b='';s_ajaxListener.tempSend.apply(this,arguments);if(s_ajaxListener.method.toLowerCase()=='post')s_ajaxListener.data=a;s_ajaxListener.callback();} const nativeFetch=window.fetch;window.fetch=async function(...args){if(typeof args[0]==='string'){let thisUrl=args[0].replace(/\?(.+)/ig,"");if(thisUrl==="/cart/add.js"||thisUrl==="/cart/add.json"||thisUrl==="/cart/add"){if(typeof args[1].body==='string'&&(args[1].body.includes('offer')||triggerProduct)){triggerProduct=false;return nativeFetch.apply(window,args);} let response=await nativeFetch.apply(window,args);if(response.status===200){const triggerType=triggerTypes.addToCart;let dataArgs,variantsId;if(typeof(args[1].body)==='object'&&args[1].body instanceof FormData){for(let pair of args[1].body.entries()){if(pair[0]==='id'){variantsId=pair[1];}}}else if(typeof(args[1].body)==='string'){if(args[1].body.includes('&')){dataArgs=args[1].body.split('&');dataArgs.forEach(element=>{if(element.includes('id=')){variantsId=element.split('=');variantsId=variantsId[variantsId.length-1];}});}else if(args[1].body.includes('{')){dataArgs=JSON.parse(args[1].body);variantsId=dataArgs.id?dataArgs.id:dataArgs.items[0].id;}}else{return response;} if(addonContainers.length&&goodpaInlineWidgetBtnSelector===''){const addonsOffers=getAddonsProducts(addonContainers);sendAddonStatistic(addonsOffers.offers) addAddonsProducts(addonsOffers.products);} currentProductId=variantsId;if(Object.keys(goodpaTriggerEvents).length&&goodpaTriggerEvents.includes(+triggerType)){if(location.href.includes('/products/')){addToCartProductPage(triggerType,variantsId,currentProductId);}else{addToCartTrigger(triggerType,variantsId,currentProductId);}}} return response}else if(thisUrl==="/cart/change.js"||thisUrl==="/cart/change.json"||thisUrl==="/cart/change"||thisUrl==="/cart.js"){let response=await nativeFetch.apply(window,args);if(response.status===200){removeFunnelProducts();setTimeout(()=>{cartPageDiscount();},1000);} return response}else{return nativeFetch.apply(window,args);}}} function removeFunnelProducts(){if(goodpaRemoveFunnelProducts===1)return;const removeProduct=2;let reloadCart=false;fetchCart().then(function(dataCart){updateProductsData(dataCart);const localProductsData=JSON.parse(localStorage.getItem('goodpaProductsData'));if(localProductsData){localProductsData.forEach((element,index)=>{if(dataCart.items.length){const lineItemProperty=dataCart.items.find(product=>+product.id===+element.targetProductId&&!product.properties.offer);if(lineItemProperty)return;if(goodpaRemoveFunnelProducts===removeProduct){for(let i=0;iitem.propertyId===dataCart.items[i].properties.offer);if(isFunnelProduct){removeItemByLine(i+1);reloadCart=true;break;}}}else{return;}}});}else{return;} setTimeout(()=>{if((goodpaRemoveFunnelProducts===removeProduct)&&reloadCart){location.reload();}},2000)});} function updateProductsData(dataCart){const localProductsData=JSON.parse(localStorage.getItem('goodpaProductsData'));if(!localProductsData)return;if(dataCart.items.length<1||localProductsData.length<1){localStorage.removeItem('goodpaProductsData');}else{localProductsData.forEach((element,i)=>{if(element.funnelProducts.length){element.funnelProducts.forEach((funnelProduct,index)=>{const isFunnelProduct=dataCart.items.find(item=>item.properties.offer===funnelProduct.propertyId);if(!isFunnelProduct){element.funnelProducts.splice(index,1);}})}else{localProductsData.splice(i,1);}}) localStorage.setItem('goodpaProductsData',JSON.stringify(localProductsData));}} function sendPurchaseAPI(offerData,orderItems){if(!offerData){return} offerData.forEach(mainOfferItem=>{const offerDataItem={'main_offer_id':mainOfferItem.main_offer_id,'offer_amount':[]} mainOfferItem.offer.forEach(offerItem=>{const lineItemProperty=orderItems.find(item=>offerItem.property_id===item.properties.offer) if(lineItemProperty){let discount;let qty=+lineItemProperty.quantity!==0?+lineItemProperty.quantity:1;if(lineItemProperty.applied_discounts.length>0&&lineItemProperty.applied_discounts[0].amount){discount=lineItemProperty.applied_discounts[0].amount;} if(offerDataItem.offer_amount.length){const checkOfferId=offerDataItem.offer_amount.find(item=>item.offer_id===offerItem.offer_id);if(checkOfferId){checkOfferId.amount=(+checkOfferId.amount+(discount?(+offerItem.product_store_price*qty)-discount:+offerItem.product_store_price*qty)).toFixed(2);}else{offerDataItem.offer_amount.push({offer_id:offerItem.offer_id,amount:discount?((+offerItem.product_store_price*qty)-discount).toFixed(2):(+offerItem.product_store_price*qty).toFixed(2)});}}else{offerDataItem.offer_amount.push({offer_id:offerItem.offer_id,amount:discount?((+offerItem.product_store_price*qty)-discount).toFixed(2):(+offerItem.product_store_price*qty).toFixed(2)});}}}) if(offerDataItem.offer_amount.length){createPurchaseFetch(offerDataItem);}}) localStorage.removeItem('goodpaPurchaseDataApp');} if(location.href.includes('/products/')){const triggerType=triggerTypes.productPage;if(Object.keys(goodpaTriggerEvents).length&&goodpaTriggerEvents.includes(+triggerType)){let url=location.href.split('/');let productsIndex=url.indexOf('products');url=url[productsIndex+1];fetchProduct(url).then(function(dataPage){const productId=dataPage.product.id;const offerParams={triggerType,productId,} offerFetch(offerParams).then(function(dataOffer){if(dataOffer.offers){currentProductId='';for(let key in dataOffer.offers){const offerItem=dataOffer.offers[key];const offerType=offerItem.offer_type;if(offerType===offerTypes.fbt){let isProductInResp=dataOffer.products[productId];if(!isProductInResp){dataOffer.products[productId]=setTriggerProductToOffer(dataPage.product);} const offerProducts=offerItem.products;offerProducts.unshift(setTriggerProductIds(dataPage.product));const offerDiscount=dataOffer.discount[offerItem.id];offerDiscount.unshift({discount:null,discount_type:null,min_qty:null,qty:0})}} buildPopUpType(dataOffer,false,triggerType);}});})}} if(location.href.includes('/cart')){const triggerType=triggerTypes.cartPage;if(Object.keys(goodpaTriggerEvents).length&&goodpaTriggerEvents.includes(+triggerType)){variantsId='0';const offerParams={triggerType,variantsId,productId:'0',} offerFetch(offerParams).then(function(dataOffer){buildPopUpType(dataOffer,false,triggerType);const defaultNodeElements=['#checkout'];const inlineWidget=goodpaCheckoutBtnSelector.length?goodpaCheckoutBtnSelector:defaultNodeElements;if(inlineWidget){const button=document.querySelector(`${inlineWidget}`);if(button){const buttonClone=button.cloneNode(true);button.insertAdjacentElement('afterend',buttonClone);button.style.display="none";buttonClone.classList.add('goodpa_checkout_clone');buttonClone.addEventListener('click',function(e){e.preventDefault();e.stopImmediatePropagation();e.stopPropagation();fetchCart().then(function(dataCart){createOrderCartFetch(dataCart).then(result=>{location.href=result.checkout;},error=>{console.log(error);})})})}}});}} async function createOrderCartFetch(dataCart){const options={method:'POST',headers:{'Content-Type':'application/json',"Accept":"application/json"},body:JSON.stringify(createOrderCartRequest(dataCart))};let url=goodpaApiUrl+`api/front/draft-order`;const resp=await fetch(url,options);if(!resp.ok){throw new Error(`HTTP error, status = ${resp.status}`);} return await resp.json();} function createOrderCartRequest(dataCart){const domain=goodpaShop;const line_items=[];const addonesItems=document.querySelectorAll('.goodpa-product__item') dataCart.items.forEach(item=>{line_items.push({discount:null,price:item.line_price,product_id:item.id,properties:null,quantity:item.quantity,title:item.handle,variant_id:item.variant_id,})});addonesItems.forEach((item)=>{if(item.getAttribute('data-active')==="true"){const price=item.querySelector('.goodpa-product__content').getAttribute('data-storeprice');const product_id=item.querySelector('.goodpa-product__content').getAttribute('data-productid');const title=item.querySelector('.goodpa-product__title').innerText;line_items.push({discount:null,price:+price*100,product_id:+product_id,properties:null,quantity:1,title:title,variant_id:+product_id,})}}) return{domain:domain,line_items:line_items}} if("/thank_you"===location.href.slice(-10)||Shopify.checkout){const orderItems=Shopify.checkout.line_items;const offerData=JSON.parse(localStorage.getItem('goodpaPurchaseDataApp'));let cart=orderItems.map(item=>item.product_id);cart=cart.join();let variantsId=orderItems.map(item=>item.variant_id);variantsId=variantsId.join();sendPurchaseAPI(offerData,orderItems);localStorage.removeItem('goodpaDataOrder');} function sendPurchaseAPI(offerData,orderItems){if(!offerData){return} offerData.forEach(mainOfferItem=>{const offerDataItem={'main_offer_id':mainOfferItem.main_offer_id,'offer_amount':[]} mainOfferItem.offer.forEach(offerItem=>{const lineItemProperty=orderItems.find(item=>offerItem.property_id===item.properties.offer) if(lineItemProperty){let discount;let qty=+lineItemProperty.quantity!==0?+lineItemProperty.quantity:1;if(lineItemProperty.applied_discounts.length>0&&lineItemProperty.applied_discounts[0].amount){discount=lineItemProperty.applied_discounts[0].amount;} if(offerDataItem.offer_amount.length){const checkOfferId=offerDataItem.offer_amount.find(item=>item.offer_id===offerItem.offer_id);if(checkOfferId){checkOfferId.amount=(+checkOfferId.amount+(discount?(+offerItem.product_store_price*qty)-discount:+offerItem.product_store_price*qty)).toFixed(2);}else{offerDataItem.offer_amount.push({offer_id:offerItem.offer_id,amount:discount?((+offerItem.product_store_price*qty)-discount).toFixed(2):(+offerItem.product_store_price*qty).toFixed(2)});}}else{offerDataItem.offer_amount.push({offer_id:offerItem.offer_id,amount:discount?((+offerItem.product_store_price*qty)-discount).toFixed(2):(+offerItem.product_store_price*qty).toFixed(2)});}}}) if(offerDataItem.offer_amount.length){createPurchaseFetch(offerDataItem);}}) localStorage.removeItem('goodpaPurchaseData');} function getVariantImageSrc(imageId,product){if(!imageId){return product.image.src} let image=product.images.find(item=>item.id===imageId);if(image){return image.src}else{return product.image.src}} function setTriggerProductToOffer(product){const regex=/(<([^>]+)>)/ig;const variantsObj={};for(let key in product.variants){let variantItem=product.variants[key];let imageSrc=getVariantImageSrc(variantItem.image_id,product);let variantObj={title:variantItem.title,description:product.body_html?(product.body_html).replace(regex,""):"",image:imageSrc,inventory_management:variantItem.inventory_management,productId:variantItem.id,variantPrice:goodpaCurrencyCode!==currentCurrencyCode?getStorePriceByRate(variantItem.price):variantItem.price,} variantsObj[variantItem.id]=variantObj;} return{title:product.title,description:product.body_html?(product.body_html).replace(regex,""):"",image:product.image.src,inventory_management:product.variants[0].inventory_management,productId:product.id,variants:variantsObj,fbtTriggeredProduct:true}} function setTriggerProductIds(product){const variantsArr=[];for(let key in product.variants){variantsArr.push(product.variants[key].id);} return{[product.id]:variantsArr}}!function(){let lastBtn=null document.addEventListener('click',function(e){if(!e.target.closest)return;lastBtn=e.target.closest('button, input[type=submit]');},true);document.addEventListener('submit',function(e){if('submitter'in e)return;var canditates=[document.activeElement,lastBtn];lastBtn=null;for(var i=0;i{let qty=item.quantity;if(orderData){if(!!item.properties&&!!item.properties.offer){const lineItemProperty=orderData.find(prod=>prod.propertyId===item.properties.offer);if(lineItemProperty){discount=lineItemProperty.discountValue!=null?{value_type:lineItemProperty.discountType,value:+lineItemProperty.discountValue}:null;item.properties.offer=lineItemProperty.propertyId;properties=item.properties;qty=+lineItemProperty.qty;}}else{discount=null;properties=item.properties;}} line_items.push({title:item.title,product_id:item.product_id,variant_id:item.variant_id,price:goodpaCurrencyCode!==currentCurrencyCode?getStorePriceByRate(item.price / 1000)*1000:item.price,quantity:qty,discount:discount,properties:properties}) if(+item.quantity>+qty){let result=+item.quantity- +qty;item.properties.offer=null;line_items.push({title:item.title,product_id:item.product_id,variant_id:item.variant_id,price:goodpaCurrencyCode!==currentCurrencyCode?getStorePriceByRate(item.price / 1000)*1000:item.price,quantity:result,discount:null,properties:item.properties})}}) return{domain:domain,line_items:line_items}} function createOrder(){const modalBody=document.querySelector("#goodpa-app");if(modalBody){getAppSelector('.goodpa-popup__body').classList.add('goodpa-preload');} const line_items=[];fetchCart().then(function(dataCart){const orderData=JSON.parse(localStorage.getItem('goodpaDataOrder'));dataCart.items.forEach(item=>{if(orderData){if(!!item.properties&&!!item.properties.offer){const lineItemProperty=orderData.find(prod=>prod.propertyId===item.properties.offer);if(lineItemProperty){if(lineItemProperty.discountValue!=null){line_items.push(item);}}}}});if(line_items.length){createOrderFetch(dataCart.items,orderData).then(result=>{location.href=result.checkout;},error=>{location.href='/checkout';})}else{location.href='/checkout';}})} function setExcludeOffers(){if(+goodpaMaxShowOffer===0)return;const localoffersData=JSON.parse(localStorage.getItem('goodpaOffersData'));if(localoffersData){const excludeOffersArr=localoffersData.filter(item=>+item.shown>=+goodpaMaxShowOffer);if(excludeOffersArr){excludeOffersArr.forEach(item=>{if(excludeOffers.indexOf(item.main_offer_id)===-1){excludeOffers.push(item.main_offer_id)}});}}} function getExcludeCartOffer(){const offerId=localStorage.getItem(`goodpaExcludeCartOfferId`);if(!offerId)return;excludeOffers.push(offerId);localStorage.removeItem(`goodpaExcludeCartOfferId`);} class ProductPreview{constructor(product,activeProduct,rootId,countDownTimer,offerObj){this.template=this.setTemplate(product,activeProduct);this.body=document.querySelector("body");this.closeButton=this.template.querySelector('.goodpa-product-det__close');this.qtyMinusBtn=this.template.querySelector('.goodpa-product-det__qty--minus');this.qtyPlusBtn=this.template.querySelector('.goodpa-product-det__qty--plus');this.qtyInput=this.template.querySelector('.goodpa-product-det__qty--input');this.variationSelect=this.template.querySelector('.goodpa-product-det__variations-select');this.sliderPrevBtn=this.template.querySelector('.goodpa-product-det__prev');this.sliderNextBtn=this.template.querySelector('.goodpa-product-det__next');this.addToCartBtn=this.template.querySelector('.goodpa-cart-btn');this.removeBtn=this.template.querySelector('.goodpa-remove-btn');this.activeProduct=activeProduct;this.rootId=rootId;this.countDownTimer=countDownTimer;this.maxQty=offerObj.maxQty||1;this.init();};getActiveProductData(activeProduct){const showQty=activeProduct.querySelector('.goodpa-qty')?activeProduct.querySelector('.goodpa-qty').classList.contains('goodpa-hide'):true;const qtyVal=activeProduct.querySelector('.goodpa-qty-input')?activeProduct.querySelector('.goodpa-qty-input').value:null;const activeVariant=activeProduct.querySelector('.goodpa-variations')?activeProduct.querySelector('.goodpa-variations').value:null;const showButtons=activeProduct.querySelector('.goodpa-cart-btn')?true:false;const showAddToCartBtn=showButtons?activeProduct.querySelector('.goodpa-cart-btn').classList.contains('goodpa-hide'):null;const addToCartBtnText=showButtons?activeProduct.querySelector('.goodpa-cart-btn-text').innerText:null;const removeBtnText=showButtons?activeProduct.querySelector('.goodpa-remove-btn-text').innerText:null;const addedVariants=[];if(activeProduct.querySelector('.goodpa-variations')){const varianOptions=activeProduct.querySelectorAll('.goodpa-variations option');varianOptions.forEach(option=>{const added=option.getAttribute('data-added');if(added==='true'){addedVariants.push(parseInt(option.value));}});} let data={show_qty:!showQty,qty_val:qtyVal,active_variant:activeVariant,show_buttons:showButtons,is_product_added:showAddToCartBtn,add_to_cart_text:addToCartBtnText,remove_text:removeBtnText,added_variants:addedVariants} return data;} setTemplate(product,activeProduct){let activeProductData=this.getActiveProductData(activeProduct);let productImg=noImage;if(product.image!=undefined){productImg=`${product.title}`;} let productPrice='';let comparePrice='';let minQty=product.min_quantity?product.min_quantity:1;let imagesArr=[];let variantsHtml='';if(product.variants.length>1){variantsHtml=`';}else{variantsHtml='';productPrice=getPriceByRate(product.variants[0].variantPrice);} if(product.discount!=undefined&&product.discount_type!=undefined&&parseInt(product.discount)!=0){let discountVal=product.discount_type!=="%"?getPriceByRate(product.discount):product.discount;comparePrice=`${currencyFormat(productPrice)}`;if(product.discount_type==="%"){productPrice=(+productPrice-(+productPrice*+product.discount / 100));}else{productPrice=(+productPrice- +discountVal);}} productPrice=currencyFormat(productPrice);if(imagesArr.length){if(imagesArr.length>1){let sliderImages='';imagesArr.forEach((item,i)=>{let active=item.ids.includes(parseInt(activeProductData.active_variant))?'goodpa-slide-active':'';sliderImages+=`
${product.title}
`;});productImg=`
${sliderImages}
`;}else{productImg=`${product.title}`;}} const description=product.description_html?`
${product.description_html}
`:`

${product.description}

`;const html=`
${productImg}

${product.title}

${comparePrice} ${productPrice}
${description}
${variantsHtml}
`;const element=document.createElement("div");element.classList.add("goodpa-product-det__modal");element.innerHTML=html;return element;} init(){this.closeButton.addEventListener('click',this.hide.bind(this));if(this.qtyInput){const activeProductInput=this.activeProduct.querySelector('.goodpa-qty-input');this.qtyPlusBtn.addEventListener('click',e=>{e.preventDefault();changeQtyValue(this.qtyInput,'add',this.maxQty);changeQtyValue(activeProductInput,'add',this.maxQty);});this.qtyMinusBtn.addEventListener('click',e=>{e.preventDefault();changeQtyValue(this.qtyInput,'sub',this.maxQty);changeQtyValue(activeProductInput,'sub',this.maxQty);});this.qtyInput.addEventListener('change',e=>{e.preventDefault();changeQtyValue(this.qtyInput,'change',this.maxQty);changeQtyValue(activeProductInput,'change',this.maxQty);});} if(this.variationSelect){let _this=this;this.variationSelect.addEventListener("change",function(e){e.preventDefault();const activeOption=this.selectedOptions[0];const element=this.closest('.goodpa-product-det__body');if(_this.addToCartBtn){_this.addToCartBtn.setAttribute('data-productId',this.value);} _this.changeVariant(element,activeOption);const activeProductVariationSelect=_this.activeProduct.querySelector('.goodpa-variations');activeProductVariationSelect.value=this.value;if("createEvent"in document){let evt=document.createEvent("HTMLEvents");evt.initEvent("change",false,true);activeProductVariationSelect.dispatchEvent(evt);} else{activeProductVariationSelect.fireEvent("onchange");}});} if(this.sliderPrevBtn&&this.sliderNextBtn){this.sliderPrevBtn.addEventListener('click',this.changeSlider.bind(this,'prev'));this.sliderNextBtn.addEventListener('click',this.changeSlider.bind(this,'next'));} if(this.addToCartBtn){this.addToCartBtn.addEventListener('click',e=>{e.preventDefault();this.addProduct();});} if(this.removeBtn){this.removeBtn.addEventListener('click',e=>{e.preventDefault();this.removeProduct();});} return this;} show(){this.body.append(this.template);} hide(){if(this.countDownTimer){restartTimer(this.rootId,this.countDownTimer);} this.template.remove();} changeActiveImg(elements,activeElement){elements.forEach(element=>element.classList.remove('goodpa-slide-active'));activeElement.classList.add('goodpa-slide-active');} changeVariant(element,activeOption){const comparePriceContainer=element.querySelector(".goodpa-product-det__price-compare");const mainPriceContainer=element.querySelector(".goodpa-product-det__price-main");const price=activeOption.getAttribute('data-price');const variantId=activeOption.getAttribute('data-variant-id');let newPrice=price;if(comparePriceContainer){const discountValue=comparePriceContainer.getAttribute("data-discount");const discountType=comparePriceContainer.getAttribute("data-discountType");if(discountType==="%"){newPrice=(+price-(+price*+discountValue / 100)).toFixed(2);}else{newPrice=(+price- +discountValue).toFixed(2);} comparePriceContainer.innerText=currencyFormat(price);} mainPriceContainer.innerText=currencyFormat(newPrice) let sliderItems=element.querySelectorAll('.goodpa-product-det__slider-item');if(sliderItems){sliderItems.forEach(item=>{const imageIds=item.getAttribute('data-image-id').split(',');if(imageIds.includes(variantId)){this.changeActiveImg(sliderItems,item);}})} const inCart=activeOption.getAttribute('data-added');if(inCart&&inCart==='true'){if(this.addToCartBtn&&this.removeBtn){this.addToCartBtn.classList.add('goodpa-hide');this.removeBtn.classList.remove('goodpa-hide');}}else{if(this.addToCartBtn&&this.removeBtn){this.addToCartBtn.classList.remove('goodpa-hide');this.removeBtn.classList.add('goodpa-hide');}}} changeSlider(type){let sliderItems=document.querySelectorAll('.goodpa-product-det__slider-item');let activeSlide;let activeSlideNumber;sliderItems.forEach((item,i)=>{if(item.classList.contains('goodpa-slide-active')){activeSlide=item;activeSlideNumber=i;}});activeSlide.classList.remove('goodpa-slide-active');let newActiveSlide=activeSlide;for(let i=0;i=sliderItems.length){newActiveSlide=0;} break} case'prev':{newActiveSlide=activeSlideNumber-1;if(newActiveSlide<0){newActiveSlide=sliderItems.length-1;} break}} if(newActiveSlide===i){sliderItems[i].classList.add('goodpa-slide-active');}}} addProduct(){this.addToCartBtn.classList.add('goodpa-preload');const activeProductAddBtn=this.activeProduct.querySelector('.goodpa-cart-btn');activeProductAddBtn.click();setTimeout(()=>{this.addToCartBtn.classList.remove('goodpa-preload');this.addToCartBtn.classList.add('goodpa-hide');this.removeBtn.classList.remove('goodpa-hide');setTimeout(()=>{if(this.countDownTimer){restartTimer(this.rootId,this.countDownTimer);} this.template.remove();},1000);},1000);} removeProduct(){const variantId=this.addToCartBtn.getAttribute('data-productid');this.removeBtn.classList.add('goodpa-preload');const activeProductRemoveBtn=this.activeProduct.querySelector('.goodpa-remove-btn');activeProductRemoveBtn.click();setTimeout(()=>{this.removeBtn.classList.remove('goodpa-preload');this.removeBtn.classList.add('goodpa-hide');this.addToCartBtn.classList.remove('goodpa-hide');if(this.variationSelect){this.setVariantAddedToCart(variantId,false);}},1000);} setVariantAddedToCart(variantId,param){const varianOptions=this.variationSelect.querySelectorAll('option');varianOptions.forEach(option=>{const optionValue=parseInt(option.value);if(parseInt(variantId)===optionValue){option.setAttribute('data-added',param);}});}} function previewProductEvents(element,product,rootId,countDownTimer,offerObj){const previewOpenerImg=element.querySelector('.goodpa-product__img');const previewOpenerTitle=element.querySelector('.goodpa-prod-title');previewOpenerTitle.addEventListener("click",function(e){e.preventDefault();let detailModal=new ProductPreview(product,element,rootId,countDownTimer,offerObj);detailModal.show();if(countDownTimer){countDownTimer.stopTimer();}});if(previewOpenerImg){previewOpenerImg.addEventListener("click",function(e){e.preventDefault();let detailModal=new ProductPreview(product,element,rootId,countDownTimer,offerObj);detailModal.show();if(countDownTimer){countDownTimer.stopTimer();}});}} function cartPageDiscount(){const subTotalPriceClass=goodpaCartSubtotal.length?decodeHTML(goodpaCartSubtotal):'';const subTotalContainerClass=goodpaCartSubtotalContainer.length?decodeHTML(goodpaCartSubtotalContainer):'';if(!subTotalPriceClass||!subTotalContainerClass)return;let subTotalPrice;let subTotalContainer;const localDataOrder=JSON.parse(localStorage.getItem('goodpaDataOrder'));if("/cart"===location.href.slice(-5)&&localDataOrder){setTimeout(()=>{runCartPageDiscount();},1000);} function runCartPageDiscount(){subTotalPrice=document.querySelector(subTotalPriceClass);subTotalContainer=document.querySelector(subTotalContainerClass);const goodpaCartContainer=document.querySelector(`.goodpa-cart-container`);if(goodpaCartContainer){subTotalPrice.style.textDecoration='';goodpaCartContainer.remove();} const isDiscount=localDataOrder.find(product=>product.discountValue!=null);if(!isDiscount)return;fetchCart().then(function(dataCart){const{total_price,items}=dataCart;if(items.length){let totalDiscountPrice=calcDiscountPrice(localDataOrder,items);buildDiscountContainer(total_price,totalDiscountPrice);}});} function calcDiscountPrice(localDataOrder,items){let totalDiscountPrice=0;items.forEach(productItem=>{if(!!productItem.properties&&!!productItem.properties.offer){const lineItemProperty=localDataOrder.find(product=>product.propertyId===productItem.properties.offer);if(lineItemProperty&&lineItemProperty.discountValue){let productPrice=productItem.discounted_price / 100;if(lineItemProperty.discountType==='%'){productPrice=(+productPrice-(+productPrice*+lineItemProperty.discountValue / 100)).toFixed(2);}else{productPrice=(+productPrice- +lineItemProperty.discountValue).toFixed(2);} totalDiscountPrice+=productPrice*lineItemProperty.qty;}else{totalDiscountPrice+=(productItem.discounted_price / 100)*productItem.quantity;}}else{totalDiscountPrice+=(productItem.discounted_price / 100)*productItem.quantity;}}) return totalDiscountPrice;} function buildDiscountContainer(totalPrice,totalDiscountPrice){const discount=(totalPrice-(totalDiscountPrice*100))/ 100;const html=`

- ${currencyFormat(discount)}

${currencyFormat(totalDiscountPrice)}

`;const element=document.createElement("div");element.classList.add("goodpa-cart-container");element.style.textAlign='right';element.innerHTML=html;subTotalContainer.after(element);subTotalPrice.style.textDecoration='line-through';}} cartPageDiscount();};goodpaApp();}