Welcome to Honest Baby Clothing


Welcome to Honest Baby Clothing <![CDATA[(function() { function asyncLoad() { var urls = ["https://static.klaviyo.com/onsite/js/klaviyo.js?company_id=NPusCYu0026shop=honestbabyclothing.myshopify.com","//apps.bazaarvoice.com/deployments/honestbabyclothes/main_site/production/en_US/bv.js?shop=honestbabyclothing.myshopify.com","https://cdn.kilatechapps.com/media/countdown/37390221445.min.js?shop=honestbabyclothing.myshopify.com","https://hello.zonos.com/shop-duty-tax/hello.js?1604531948102u0026shop=honestbabyclothing.myshopify.com","//cdn.shopify.com/s/files/1/0257/0108/9360/t/85/assets/usf-license.js?shop=honestbabyclothing.myshopify.com","https://static.fbot.me/shopify/friendbuy-shopify.js?merchantId=58788991-1377-445b-aa90-df53cbded4b9u0026shop=honestbabyclothing.myshopify.com"]; for (var i = 0; i <![CDATA[(function () { var customDocumentWrite = function(content) { var jquery = null; if (window.jQuery) { jquery = window.jQuery; } else if (window.Checkout && window.Checkout.$) { jquery = window.Checkout.$; } if (jquery) { jquery('body').append(content); } }; var hasLoggedConversion = function(token) { if (token) { return document.cookie.indexOf('loggedConversion=' + token) !== -1; } return false; } var setCookieIfConversion = function(token) { if (token) { var twoMonthsFromNow = new Date(Date.now()); twoMonthsFromNow.setMonth(twoMonthsFromNow.getMonth() + 2); document.cookie = 'loggedConversion=' + token + '; expires=' + twoMonthsFromNow; } } var trekkie = window.ShopifyAnalytics.lib = window.trekkie = window.trekkie || []; if (trekkie.integrations) { return; } trekkie.methods = [ 'identify', 'page', 'ready', 'track', 'trackForm', 'trackLink' ]; trekkie.factory = function(method) { return function() { var args = Array.prototype.slice.call(arguments); args.unshift(method); trekkie.push(args); return trekkie; }; }; for (var i = 0; i <![CDATA[ × {{productTitle}} {{variant_compare_at_price}} {{variant_price}} × {{optionVariantData}} t.price?SECOMAPP.jQuery(“#price-field-{{productID}}”).html(“”+SECOMAPP.formatMoney(t.compare_at_price)+” “+SECOMAPP.formatMoney(t.price)+””):SECOMAPP.jQuery(“#price-field-{{productID}}”).html(“”+SECOMAPP.formatMoney(t.price)+””)):SECOMAPP.jQuery(“#sca-btn-{{productID}}”).html(“{{UnavailableButton}}”).addClass(“disabled”).attr(“disabled”,”disabled”).fadeTo(200,.5),t&&t.featured_image){var e=SECOMAPP.jQuery(“#sca-freegift-{{productID}} img”),_=t.featured_image,c=e[0];Shopify.Image.switchImage(_,c,function(t,a,e){SECOMAPP.jQuery(e).parents(“a”).attr(“href”,t),SECOMAPP.jQuery(e).attr(“src”,t)})}},onclickSelect_{{productID}}=function(t){SECOMAPP.jQuery.getJSON(“/products/{{productHandle}}.js”,{_:(new Date).getTime()},function(t){SECOMAPP.jQuery(“.owl-item #sca-freegift-{{productID}} span.sca-product-title”).html(t.title);var e=[];SECOMAPP.jQuery.each(t.options,function(t,a){e[t]=a.name}),t.options=e;for(var a={{variantsGiftList}},_={{mainVariantsList}},c=t.variants.length-1;-1<c;c–)a.indexOf(t.variants[c].id)<0&&_.indexOf(t.variants[c].id)<0&&t.variants.splice(c,1);for(var o=_.length-1;-1<o;o–){var i=a[o],r=_[o],n=-1,s=-1;for(c=t.variants.length-1;-1<c;c–)t.variants[c].id==i?n=c:t.variants[c].id==r&&(s=c);-1<n&&-1 <![CDATA[ {{variantTitle}} {{variant_compare_at_price}} {{variant_price}} <![CDATA[ {{giftTitle}} ]]> o.length)&&(t=o.length),t-=e.length;var r=o.indexOf(e,t);return-1!==r&&r===t},writable:!0,enumerable:!0,configurable:!0}),Array.prototype.indexOf||(Array.prototype.indexOf=function(e,t){var o;if(null==this)throw new TypeError(‘”this” is null or not defined’);var r=Object(this),i=r.length>>>0;if(0===i)return-1;var n=+t||0;if(Math.abs(n)===1/0&&(n=0),n>=i)return-1;for(o=Math.max(n>=0?n:i-Math.abs(n),0);o>>0;if(“function”!=typeof e)throw new TypeError(e+” is not a function”);for(arguments.length>1&&(o=t),r=0;r-1?this.fgsettings.sca_currency_format:null)||r;if(n.indexOf(“amount_no_decimals_no_comma_separator”)<0&&n.indexOf("amount_no_comma_separator_up_cents")<0&&n.indexOf("amount_up_cents")<0&&"function"==typeof Shopify.formatMoney)return Shopify.formatMoney(e,n);function a(e,t){return void 0===e?t:e}function s(e,t,o,r,i,n){if(t=a(t,2),o=a(o,","),r=a(r,"."),isNaN(e)||null==e)return 0;var s=(e=(e/100).toFixed(t)).split(".");return s[0].replace(/(d)(?=(ddd)+(?!d))/g,"$1"+o)+(s[1]?i&&n?i+s[1]+n:r+s[1]:"")}switch(n.match(i)[1]){case"amount":o=s(e,2);break;case"amount_no_decimals":o=s(e,0);break;case"amount_with_comma_separator":o=s(e,2,",",".");break;case"amount_no_decimals_with_comma_separator":o=s(e,0,",",".");break;case"amount_no_decimals_no_comma_separator":o=s(e,0,"","");break;case"amount_up_cents":o=s(e,2,",","","","");break;case"amount_no_comma_separator_up_cents":o=s(e,2,"","","","")}return n.replace(i,o)},SECOMAPP.setCookie=function(e,t,o,r,i){var n=new Date;n.setTime(n.getTime()+24*o*60*60*1e3+60*r*1e3);var a="expires="+n.toUTCString();document.cookie=e+"="+t+";"+a+(i?";path="+i:";path=/")},SECOMAPP.deleteCookie=function(e,t){document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; "+(t?";path="+t:";path=/")},SECOMAPP.getCookie=function(e){for(var t=e+"=",o=document.cookie.split(";"),r=0;r<o.length;r++){for(var i=o[r];" "==i.charAt(0);)i=i.substring(1);if(0==i.indexOf(t))return i.substring(t.length,i.length)}return""},SECOMAPP.getQueryString=function(){for(var e={},t=window.location.search.substring(1).split("&"),o=0;oo.length)&&(t=o.length),t-=e.length;var r=o.indexOf(e,t);return-1!==r&&r===t}}),e){if(e.options&&Array.isArray(e.options))for(var t=0;t<e.options.length;t++){if(void 0!==e.options[t]&&void 0!==e.options[t].values)if((r=e.options[t]).values&&Array.isArray(r.values))for(var o=0;o<r.values.length;o++)(r.values[o].endsWith("(Freegifts)")||r.values[o].endsWith("% off)"))&&(r.values.splice(o,1),o–)}if(e.options_with_values&&Array.isArray(e.options_with_values))for(t=0;t<e.options_with_values.length;t++){var r;if(void 0!==e.options_with_values[t]&&void 0!==e.options_with_values[t].values)if((r=e.options_with_values[t]).values&&Array.isArray(r.values))for(o=0;o=l.price)&&(n=l.price,i=l.price),(!a||a=l.compare_at_price)&&(c=l.compare_at_price,s=l.compare_at_price),(!f||f<=l.compare_at_price)&&(f=l.compare_at_price)),void 0!==l.available&&1==l.available&&(e.available=!0))}e.price=i,e.price_max=a==n?null:a,e.price_min=n==a?null:n,e.compare_at_price=s,e.compare_at_price_max=f,e.compare_at_price_min=c,e.price_varies=n<a,e.compare_at_price_varies=c Skip to content _addItemToCart() function cartAddItem(itemData, onSuccess, onFail) { const url = “/cart/add.js”; const dataType = “json”; const data = { items: [ { …itemData, }, ], }; $.post(url, data, onSuccess, dataType).fail(onFail); } // Update Quantity function cartUpdateItemQuantity(itemID, newQuantity, onSuccess, onFail) { const url = “/cart/change.js”; const dataType = “json”; const data = { id: itemID, quantity: newQuantity }; $.post(url, data, onSuccess, dataType).fail(onFail); } // Remove Item function cartRemoveItem(itemID, onSuccess, onFail) { const url = “/cart/change.js”; const dataType = “json”; const data = { id: itemID, quantity: 0, }; $.post(url, data, onSuccess, dataType).fail(onFail); } async function fetchCart(){ try{ const response = await fetch(“/cart.json”); const fetchedCart = await response.json(); return fetchedCart && fetchedCart; } catch(err){ console.log(err) } } function addCartAttribute() { const url = “/cart/update.js”; const dataType = “json”; const data = { attributes: { ‘product’: ‘fromUpsell’} }; const onSuccess = (res) => { return } const onFail = (res) => { return } $.post(url, data, onSuccess, dataType).fail(onFail); } function removeCartAttribute() { const url = “/cart/update.js”; const dataType = “json”; const data = { attributes: { ‘product’: ” } }; const onSuccess = (res) => { return } const onFail = (res) => { return } $.post(url, data, onSuccess, dataType).fail(onFail); } function populateCartObject(retrievedCart) { Object.keys(retrievedCart).forEach((cartKey) => { cart[cartKey] = retrievedCart[cartKey]; // TOD: // calculate how many items from the upsell are already in the cart // so that we can disable the upsell if all items are in cart if (cartKey === “items”) { retrievedCart[cartKey].forEach((item) => { if (item.properties) { if (item.properties._fromUpsell) { upsellItemsInCart++; } } }); } }); } function getImageCustomSize(image, imgSize) { let itemImgIndexOfFormat = “”; let itemImageURLStart = “”; if(image.indexOf(“.jpg”) > -1){ itemImgIndexOfFormat = image.indexOf(“.jpg”); itemImageURLStart = image.slice(0, itemImgIndexOfFormat); } if(image.indexOf(“.png”) > -1){ itemImgIndexOfFormat = image.indexOf(“.png”); itemImageURLStart = image.slice(0, itemImgIndexOfFormat); } const itemImgURLInsert = `_${imgSize}x`; const itemImgURLEnd = image.slice(itemImgIndexOfFormat); return itemImageURLStart + itemImgURLInsert + itemImgURLEnd; } function formatMoney(cents, format) { if (typeof cents === “string”) { cents = cents.replace(“.”, “”); } var value = “”; var placeholderRegex = /{{s*(w+)s*}}/; var formatString = format || moneyFormat; function formatWithDelimiters(number, precision, thousands, decimal) { thousands = thousands || “,”; decimal = decimal || “.”; if (isNaN(number) || number === null) { return 0; } number = (number / 100.0).toFixed(precision); var parts = number.split(“.”); var dollarsAmount = parts[0].replace(/(d)(?=(ddd)+(?!d))/g, “$1” + thousands); var centsAmount = parts[1] ? decimal + parts[1] : “”; return dollarsAmount + centsAmount; } switch (formatString.match(placeholderRegex)[1]) { case “amount”: value = formatWithDelimiters(cents, 2); break; case “amount_no_decimals”: value = formatWithDelimiters(cents, 0); break; case “amount_with_comma_separator”: value = formatWithDelimiters(cents, 2, “.”, “,”); break; case “amount_no_decimals_with_comma_separator”: value = formatWithDelimiters(cents, 0, “.”, “,”); break; case “amount_no_decimals_with_space_separator”: value = formatWithDelimiters(cents, 0, ” “); break; case “amount_with_apostrophe_separator”: value = formatWithDelimiters(cents, 2, “‘”); break; } return formatString.replace(placeholderRegex, value); } function checkIfDeviceIsMobile() { // https://coderwall.com/p/i817wa/one-line-function-to-detect-mobile-devices-with-javascript const isMobile = typeof window.orientation !== “undefined” || navigator.userAgent.indexOf(“IEMobile”) !== -1; return isMobile; } function setNewHeightForVisibleItemsInCartOnResize($itemsSelector, data) { if (!checkIfDeviceIsMobile()) { const viewedHeight = $(window).height(); // all values are in px unless specified otherwise const heightForHeader = $(“.cart-popup__header”).outerHeight(); const heightForProgressBar = $(“.cart-popup-shipping”).outerHeight(); const heightForCheckout = $(“.cart-popup-checkout”).outerHeight(); const heightForGiftWrapper = $(“.gift-wrapping “).outerHeight(); const heightForPromoCode = $(“.promo-code “).outerHeight(); const heightUpsellContainer = $(‘.cart-upsell-container’).outerHeight(); const heightForGiftWrapperTextarea = $(“.gift-wrapping #gift:checked”) ? $(“.gift-message”).outerHeight() : 0; const defaultHeightForUpsell = $(“.cart-upsell”).outerHeight() ; const totalConstantHeight = heightForHeader + heightForProgressBar + heightForGiftWrapper + heightUpsellContainer + heightForCheckout + heightForPromoCode + heightForGiftWrapperTextarea + defaultHeightForUpsell + 74; const remainingVHForItems = 1 – totalConstantHeight / viewedHeight; const heightForVisibleItems = remainingVHForItems * viewedHeight; $itemsSelector.css(‘min-height’, heightForVisibleItems); } } /** * Get cart data. * * @return {Object} */ const getCardInfo = () => { return fetch(‘/cart.js’) .then(response => response.json()) }; const cart = {}; let cartFilled = false; let cartOpened = false; let upsellItemsInCart = 0; let upsellItemsAvailable = upsellProducts && upsellProducts.filter((upsellItem) => upsellItem.variants[0].available).length; const cartPopupItemClass = “cart-popup-item”; const itemClasses = { wrapper: `${cartPopupItemClass}-wrapper`, checkout: `cart-popup-checkout`, upsell: `cart-upsell`, controls: `${cartPopupItemClass}-controls`, info: `${cartPopupItemClass}-info`, title: `${cartPopupItemClass}-title`, amount: `${cartPopupItemClass}-amount`, property: `${cartPopupItemClass}-property`, size: `${cartPopupItemClass}-size`, color: `${cartPopupItemClass}-color`, actions: `${cartPopupItemClass}-actions`, quantity: `${cartPopupItemClass}-quantity`, increaseQuantity: `${cartPopupItemClass}-increase-quantity`, decreaseQuantity: `${cartPopupItemClass}-decrease-quantity`, remove: `${cartPopupItemClass}-remove`, image: `${cartPopupItemClass}-image`, price: `${cartPopupItemClass}-price`, discountedPrice: `${cartPopupItemClass}-discounted-price`, }; const $cartSelectors = { $headerCartButton: () => { return $(`.site-header__cart`); }, $closeCartButton: () => { return $(`.cart-popup__close`); }, }; const $itemSelectors = { $itemsWrapper: () => { return $(`.${itemClasses.wrapper}`); }, $item: (id) => { return $(`[${id}]`); }, $quantity: (id) => { return $(`[${id}] > .${itemClasses.controls} > .${itemClasses.actions} > .${itemClasses.quantity}`); }, $increaseQuantity: (id) => { return $(`[${id}] > .${itemClasses.controls} > .${itemClasses.actions} > .${itemClasses.increaseQuantity}`); }, $decreaseQuantity: (id) => { return $(`[${id}] > .${itemClasses.controls} > .${itemClasses.actions} > .${itemClasses.decreaseQuantity}`); }, $remove: (id) => { return $(`[${id}] > .${itemClasses.controls} > .${itemClasses.info} > .${itemClasses.remove}`); }, }; const cartEvents = { item: { addToCart: “addItemAddToCartBtn”, remove: “removeItem”, increaseQty: “increaseItemQuantity”, decreaseQty: “decreaseItemQuantity”, }, upsell: { addToCart: “upsellAddToCart”, removedFromCart: “upsellRemovedFromCart”, upsellIsEmpty: “upsellIsEmpty”, upsellIsNoLongerEmpty: “upsellIsNoLongerEmpty”, increaseQuantity: “increaseQuantity”, decreaseQuantity: “decreaseQuantity”, }, }; // TOD: // populate cart object with the actual retrieved cart // and also calculate upsellItemsIncart at the same time getCart(populateCartObject); document.addEventListener(“DOMContentLoaded”, (event) => { $cartSelectors.$headerCartButton().click((event) => { cartPopupShowEvent(event); //arrows }); $cartSelectors.$closeCartButton().click((event) => { event.preventDefault(); hideCartPopup(); }); $(document).on(cartEvents.item.increaseQty, (e, { itemID }) => { cartIncreaseItemQuantityEvent(itemID); }); $(document).on(cartEvents.item.decreaseQty, (e, { itemID }) => { cartDecreaseItemQuantityEvent(itemID); }); $(document).on(cartEvents.item.remove, (e, { itemID }) => { cartRemoveItemEvent(itemID); }); $(document).on(cartEvents.item.addToCart, (e, item) => { cartAddItemEvent(item); //arrows }); $(window).resize((e, data) => { cartOpened && setNewHeightForVisibleItemsInCartOnResize($itemSelectors.$itemsWrapper(), data); }); }); let splide; let splideInitialized = false; const $cartPopupWrapper = $(“[data-cart-popup-wrapper]”); const cartPopupClasses = { backdrop: “cart-popup-backdrop”, cartPopupBody: “cart-popup__body”, withItems: “with-items”, blank: “blank”, hidden: “cart-popup-wrapper–hidden”, }; const $cartPopupItemWrapper = $(“.cart-popup-item-wrapper”); const $cartPopupSelectors = { $backdrop: $(`.${cartPopupClasses.backdrop}`), $cartPopupBodyBlank: $(`.${cartPopupClasses.cartPopupBody}.${cartPopupClasses.blank}`), $cartPopupBodyWithItems: $(`.${cartPopupClasses.cartPopupBody}.${cartPopupClasses.withItems}`), }; $cartPopupSelectors.$backdrop.click(() => { hideCartPopup(); }); function hideCartPopup() { // $cartPopupWrapper.css({ transition: “initial” }); $cartPopupWrapper.prepareTransition().addClass(cartPopupClasses.hidden); $cartPopupSelectors.$backdrop.css({ display: “none” }); // calculateCartTotals(); // updateCartTotals(); cartOpened = false; //$(‘html, body’).css({‘overflow’:’auto’}); $(‘html, body’).css({‘overflow’:”}); } function showCartPopup() { if (!cartFilled) { cartFilled = true; fillCartWithItems(cart.items); // cartPopupUpsellPopulate(); } $cartPopupWrapper.prepareTransition().removeClass(cartPopupClasses.hidden); $cartPopupSelectors.$backdrop.css({ display: “block” }); cartOpened = true; $(‘html, body’).css({‘overflow’:’hidden’}); setNewHeightForVisibleItemsInCartOnResize($itemSelectors.$itemsWrapper()); } function setCartPopupWithItems() { $cartPopupSelectors.$cartPopupBodyWithItems.css({ display: “” }); $cartPopupSelectors.$cartPopupBodyBlank.css({ display: “none” }); } function setCartPopupBlank() { $cartPopupSelectors.$cartPopupBodyWithItems.css({ display: “none” }); $cartPopupSelectors.$cartPopupBodyBlank.css({ display: “table” }); $(“.coupon-wrapper”).hide(); } function fillCartWithItems(items) { items.forEach((item) => { cartPopupAddItem(item); }); } function attachOnClicksToCartItemControls(item) { $itemSelectors.$increaseQuantity(item.id).click((e) => { $itemSelectors.$increaseQuantity(item.id).trigger(cartEvents.item.increaseQty, { itemID: item.id }); }); $itemSelectors.$increaseQuantity(item.id).keyup((e) => { e.preventDefault(); if(e.key === ‘Enter’){ $itemSelectors.$increaseQuantity(item.id).trigger(cartEvents.item.increaseQty, { itemID: item.id }); } }); $itemSelectors.$decreaseQuantity(item.id).click(() => { $itemSelectors.$increaseQuantity(item.id).trigger(cartEvents.item.decreaseQty, { itemID: item.id }); }); $itemSelectors.$decreaseQuantity(item.id).keyup((e) => { e.preventDefault(); if(e.key === ‘Enter’){ $itemSelectors.$increaseQuantity(item.id).trigger(cartEvents.item.decreaseQty, { itemID: item.id }); } }); $itemSelectors.$remove(item.id).click(() => { $itemSelectors.$increaseQuantity(item.id).trigger(cartEvents.item.remove, { itemID: item.id }); }); $itemSelectors.$remove(item.id).keyup((e) => { e.preventDefault(); if(e.key === ‘Enter’){ $itemSelectors.$increaseQuantity(item.id).trigger(cartEvents.item.remove, { itemID: item.id }); } }); } function cartPopupItemLoading(itemID) { $itemSelectors.$item(itemID).css({ pointerEvents: “none” }); $itemSelectors.$item(itemID).css({ opacity: 0.5 }); } function cartPopupItemLoaded(itemID) { $itemSelectors.$item(itemID).css({ pointerEvents: “initial” }); $itemSelectors.$item(itemID).css({ opacity: 1 }); } function cartPopupItemMaxQuantityReached(itemID) { console.log(`max quantity of ${itemID} reached`); } function cartPopupCheckIfItemExists(item) { return $itemSelectors.$item(item.id).length; } function cartPopupShowEvent(event) { event.preventDefault(); cart.items.length ? setCartPopupWithItems() : setCartPopupBlank(); cartPopupProgressBarSetCalculating(); showCartPopup(); cartPopupIsUpsellEmpty(upsellItemsInCart, upsellItemsAvailable) && $(document).trigger(cartEvents.upsell.upsellIsEmpty); calculateCartTotals(); updateCartTotals(); cartPopupProgressBarUpdate(); } window.addEventListener(‘load’, function(event) { event.preventDefault(); if(window.location.hash.indexOf(‘cart’) > -1){ setTimeout(()=>{ cartPopupShowEvent(event); }, 200) } }); function cartPopupAddItem(item, newItem = false) { const imgSize = 200; var itemCustomProperties = ”; $.each(item.properties, function(key, val){ if(key == ‘Sale’){ itemCustomProperties += ”+ key +’: ‘+ val +”; } }); var pre_order_section = ”; if(item.properties[“Final Sale”]){ // removed for live pre_order_section = `${item.properties[“Final Sale”]}`; } const colorAndSizeCases = item.variant_options.length === 1 ? item.variant_options[0].name === “Size” ? `${item.variant_options[0]}` : `${item.variant_options[0]}` : `${item.variant_options[0]} ${item.variant_options[1]} ` const showColorAndSizes = item.variant_options[0] !== “Default Title” && !item.gift_card ? colorAndSizeCases : “; const ifProductIsHasColorAndSize = item ? ` ${itemCustomProperties} ${colorAndSizeCases} ` : “; const ifGiftCard = item.gift_card ? ` Amount: ${item.variant_options} Gift card ${item.properties[“Gift card”] } ` : “”; const discountPrice = !item.gift_card ? “ : “” const itemHtml = ` ${item.product_title} item image ${item.product_title} ${ifGiftCard} ${showColorAndSizes} ${formatMoney(item.price, moneyFormatFull)} ${discountPrice} ${pre_order_section} Remove – ${item.quantity} + `; if(item.id !== giftID){ newItem ? $cartPopupItemWrapper.prepend(itemHtml) : $cartPopupItemWrapper.append(itemHtml); attachOnClicksToCartItemControls(item); } } function cartObjAddItem(itemToAdd) { const foundItemIndex = cart.items.findIndex((item) => item.id === itemToAdd.id); if (foundItemIndex !== -1) { cart.items[foundItemIndex].quantity = itemToAdd.quantity; } else { cart.items = [itemToAdd, …cart.items]; // // Do not generate upsell if the added item is ‘Gift Card’, ‘Gift Box’ and “Upsell Item” // if(!(itemToAdd.properties && itemToAdd.properties[“_fromUpsell”]) && itemToAdd.id != giftID){ findProductForUpsell(itemToAdd.product_id, itemToAdd.product_type, itemToAdd.options_with_values); } } } function cartAddItemEvent(item) { !cartOpened && setCartPopupWithItems(); !cartOpened && showCartPopup(); cartPopupIsUpsellEmpty(upsellItemsInCart, upsellItemsAvailable) && $(document).trigger(cartEvents.upsell.upsellIsEmpty); cartObjAddItem(item); if(item.id !== giftID){ cartPopupCheckIfItemExists(item) ? cartPopupUpdateItemQuantity(item) : cartPopupAddItem(item, true); } calculateCartTotals(); updateCartTotals(); } function cartPopupRemoveItem(itemID) { const $itemToRemove = $itemSelectors.$item(itemID); $itemToRemove.remove(); } function cartObjRemoveItem(itemID) { const itemToRemoveIndex = cart.items.findIndex((item) => item.id === itemID); cart.items.splice(itemToRemoveIndex, 1); } function cartRemoveItemEvent(itemID) { const removedItem = cart.items.find((item) => item.id === itemID); const anyUpsellItem = cart.items.find(item => item.properties._fromUpsell) const removedItemIsFromUpsell = removedItem.properties && removedItem.properties._fromUpsell && removedItem.properties._fromUpsell === “true”; cartPopupItemLoading(itemID); cartPopupProgressBarSetCalculating(); const onSuccess = (cart) => { cartPopupRemoveItem(itemID); cartObjRemoveItem(itemID); const anyUpsellItemLeft = cart.items.some(item => item.properties._fromUpsell) removedItemIsFromUpsell && $(document).trigger(cartEvents.upsell.removedFromCart, removedItem); !anyUpsellItemLeft && removeCartAttribute(); if (!cart.items.length) { cartFilled = false; setCartPopupBlank(); } if(cart.items.length === 1 && cart.items[0].id === giftID){ giftCheckbox.trigger(“click”); } calculateCartTotals(); updateCartTotals(); if(isDiscountCodeApplied()) return; cartPopupProgressBarUpdate(); }; const onFail = (res) => { console.log(“removing item from the cart failed”); console.log(res); cartPopupItemLoaded(itemID); }; cartRemoveItem(itemID, onSuccess, onFail); } function cartPopupUpdateItemQuantity(newCartItem) { const newQuantity = newCartItem.quantity; const $itemToModify = $itemSelectors.$quantity(newCartItem.id); $itemToModify.html(newQuantity); } function cartObjUpdateItemQuantity(newItem) { const cartItemIndex = cart.items.findIndex((item) => item.id === newItem.id); cart.items[cartItemIndex] = newItem; } function cartDecreaseItemQuantityEvent(itemID) { const cartItem = cart.items.find((item) => item.id === itemID); const newQuantity = cartItem.quantity – 1; cartPopupItemLoading(itemID); cartPopupProgressBarSetCalculating(); const onSuccess = (cart) => { const newCartItem = cart.items.find((item) => item.id === itemID); cartObjUpdateItemQuantity(newCartItem); cartPopupUpdateItemQuantity(newCartItem); cartPopupItemLoaded(itemID); calculateCartTotals(); updateCartTotals(); if(isDiscountCodeApplied()) return; cartPopupProgressBarUpdate(); }; const onFail = (res) => { console.log(“decreasing item quantity failed”); console.log(res); cartPopupItemLoaded(itemID); }; if (cartItem.quantity === 1) { $itemSelectors.$decreaseQuantity(itemID).trigger(cartEvents.item.remove, { itemID }); return; } cartUpdateItemQuantity(itemID, newQuantity, onSuccess, onFail); } function cartIncreaseItemQuantityEvent(itemID) { const cartItem = cart.items.find((item) => item.id === itemID); const newQuantity = cartItem.quantity + 1; cartPopupItemLoading(itemID); cartPopupProgressBarSetCalculating(); const onSuccess = (cart) => { const newCartItem = cart.items.find((item) => item.id === itemID); const quantitySuccessfulyUpdated = newQuantity === newCartItem.quantity; if (quantitySuccessfulyUpdated) { cartObjUpdateItemQuantity(newCartItem); cartPopupUpdateItemQuantity(newCartItem); cartPopupItemLoaded(itemID); calculateCartTotals(); updateCartTotals(); if(isDiscountCodeApplied()) return; cartPopupProgressBarUpdate(); } else { cartPopupItemLoaded(itemID); cartPopupItemMaxQuantityReached(itemID); cartPopupProgressBarUpdate(); console.log(“max quantity”); } }; const onFail = (res) => { console.log(“increasing item quantity failed”); console.log(res); cartPopupItemLoaded(itemID); }; cartUpdateItemQuantity(itemID, newQuantity, onSuccess, onFail); } const cartBill = { subtotal: 0, subtotalWithoutGifts: 0, moneyLeftForFreeShipping: 0, shipping: 0, total: 0, onlyGiftCards: false }; const billClasses = { subtotal: `.checkout_subtotal > span`, shipping: `.checkout_shipping > span`, total: `.checkout_total > span`, }; const $billSelectors = { $subtotal: $(`${billClasses.subtotal}`), $shipping: $(`${billClasses.shipping}`), $total: $(`${billClasses.total}`), }; const cartQuantityCounter = { totalQuantity: 0, }; function detectGiftCards(){ cartBill.onlyGiftCards = cart.items.every( item => item.gift_card); } function calculateCartTotal() { cartBill.total = cartBill.shipping === “FREE” ? cartBill.subtotal : cartBill.subtotal + cartBill.shipping; } // TOD: // cart subtotal excluding gifts will work ONLY if the **title** property of the item object contains “gift” in any form function calculateCartSubtotal() { const sum = cart.items.reduce( ({ subtotal, subtotalWithoutGifts }, item) => { subtotal = subtotal + item.price * item.quantity; subtotalWithoutGifts = item.gift_card ? subtotalWithoutGifts : subtotalWithoutGifts + item.price * item.quantity; return { subtotal, subtotalWithoutGifts }; }, { subtotal: 0, subtotalWithoutGifts: 0} ); cartBill.subtotal = sum.subtotal; cartBill.subtotalWithoutGifts = sum.subtotalWithoutGifts; } function calculateCartShipping() { const shippingCost = shippingPriceFromShopify; const minimumTotalForFreeShipping = minimumTotalForFreeShippingFromShopify; var temp_subtotalWithoutGifts = cartBill.subtotalWithoutGifts; var is_gift_there = cart.items.find(item => item.id === giftID); //the main calc cartBill.shipping = !cartBill.subtotalWithoutGifts ? 0 : temp_subtotalWithoutGifts item.gift_card).reduce((acc, item) => { return acc + item.price * item.quantity; }, 0) const notOnlyGiftAndCards = cart.items.filter(item => item.id != giftID).filter(item => !item.gift_card); let discountedItemPrice = !is_gift_there ? discountSubtotal – giftPrice : cartBill.subtotal – giftPrice; discountedItemPrice = notOnlyGiftAndCards.length ? discountSubtotal – giftPrice : discountedItemPrice; cartBill.moneyLeftForFreeShipping = minimumTotalForFreeShipping – discountedItemPrice; return; } if(discountSubtotal && cartBill.onlyGiftCards){ cartBill.moneyLeftForFreeShipping = minimumTotalForFreeShipping – temp_subtotalWithoutGifts; return; } cartBill.moneyLeftForFreeShipping = minimumTotalForFreeShipping – temp_subtotalWithoutGifts; } function updateCartPopupShipping() { const shipping = isNaN(cartBill.shipping) ? cartBill.shipping : formatMoney(cartBill.shipping, moneyFormatFull); $billSelectors.$shipping.html(shipping); } function updateCartPopupSubtotal() { $billSelectors.$subtotal.html(formatMoney(cartBill.subtotal, moneyFormatFull)); } function updateCartPopupTotal() { $billSelectors.$total.html(formatMoney(cartBill.total, moneyFormatFull)); } function calculateCartTotalQuantity() { cartQuantityCounter.totalQuantity = cart.items.reduce((sum, item) => { return sum + item.quantity; }, 0); } function updateCartIconTotalQuantity() { const cartQuantityIconAttribute = `[data-cart-count]`; const cartHeaderQuantityAttribute = `[cart-header-count]`; const $cartIconCounter = $(`${cartQuantityIconAttribute}`); const $cartHeaderCounter = $(`${cartHeaderQuantityAttribute}`); return cartQuantityCounter.totalQuantity > 0 ? $cartIconCounter.html(cartQuantityCounter.totalQuantity) && $cartHeaderCounter.html(“(“+cartQuantityCounter.totalQuantity+”)”) : $cartIconCounter.html(“”) && $cartHeaderCounter.html(“”) && $cartIconCounter.addClass(“hide”) && $(“.cart-bag”).addClass(“no-roll”); } function calculateCartTotals() { detectGiftCards(); calculateCartSubtotal(); calculateCartShipping(); calculateCartTotal(); calculateCartTotalQuantity(); } function updateCartTotals() { updateCartPopupSubtotal(); updateCartPopupShipping(); updateCartPopupTotal(); updateCartIconTotalQuantity(); cartPopupProgressBarUpdate(); handleCheckoutDiscount(); } const progressBarClasses = { progressBar: `progress-bar`, currentProgress: `current-progress`, text: `progress-bar-text`, }; const $progressBarSelectors = { $progressBar: $(`.${progressBarClasses.progressBar}`), $currentProgress: $(`.${progressBarClasses.currentProgress}`), $text: $(`.${progressBarClasses.text}`), }; const progressBarColors = { currentProgress: “#f2d439”, background: “#f2e0d6”, }; const freeShippingText = `Hooray! You get FREE SHIPPING!`; const calculatingText = `Calculating…`; const cartPopupProgressBarText = () => { const formattedMoney = formatMoney(cartBill.moneyLeftForFreeShipping, moneyFormatFull); const leftMoneyToFreeShippingText = `You’re only ${formattedMoney} away from FREE SHIPPING!`; $progressBarSelectors.$text.html(leftMoneyToFreeShippingText); }; function cartPopupProgressBarFill() { const calculateFillPercentage = () => { return 100 – (cartBill.moneyLeftForFreeShipping / minimumTotalForFreeShippingFromShopify) * 100; }; const fillProgressPercentage = cartBill.moneyLeftForFreeShipping >= 0 ? calculateFillPercentage() : 100; $progressBarSelectors.$currentProgress.css({ width: `${fillProgressPercentage}%` }); } function cartPopupProgressBarUpdate() { cartBill.moneyLeftForFreeShipping >= 0 ? cartPopupProgressBarText() : cartPopupProgressBarSetFreeShipping(); cartPopupProgressBarFill(); } function cartPopupProgressBarSetCalculating() { $progressBarSelectors.$text.html(calculatingText); } function cartPopupProgressBarSetFreeShipping() { $progressBarSelectors.$text.html(freeShippingText); } const upsellPrefix = “upsell”; const cartUpsellClass = `cart-upsell`; const upsellClasses = { item: `${cartUpsellClass}-item`, controls: `${cartUpsellClass}-controls`, info: `${cartUpsellClass}-info`, actions: `${cartUpsellClass}-actions`, title: `${cartUpsellClass}-title`, color: `${cartUpsellClass}-color`, size: `${cartUpsellClass}-size`, image: `${cartUpsellClass}-image`, price: `${cartUpsellClass}-price`, upsellContainer: `${cartUpsellClass}-container`, price: `${cartUpsellClass}-price`, addToCart: `${cartUpsellClass}-add-to-cart`, loading: `${cartUpsellClass}-loading`, increase: `${cartUpsellClass}-increase-quantity`, decrease: `${cartUpsellClass}-decrease-quantity`, quantity: `${cartUpsellClass}-quantity`, }; const $upsellSelectors = { $upsell: () => { return $(`.${cartUpsellClass}`); }, $upsellContainer: () => { return $(`.${upsellClasses.upsellContainer}`); }, $productWrapper: (productID) => { return $(`[${upsellPrefix}-${productID}]`); }, $title: (productID) => { return $(`[${upsellPrefix}-${productID}] > .${upsellClasses.controls} .${upsellClasses.title}`); }, $image: (productID) => { return $(`[${upsellPrefix}-${productID}] > .${upsellClasses.image}`); }, $price: (productID) => { return $(`[${upsellPrefix}-${productID}] > .${upsellClasses.controls} .${upsellClasses.price}`); }, $addToCart: (productID) => { return $(`[${upsellPrefix}-${productID}] > .${upsellClasses.controls} .${upsellClasses.addToCart}`); }, $increaseQuantity: (productID) => { return $(`[${upsellPrefix}-${productID}] > .${upsellClasses.controls} .${upsellClasses.increase}`); }, $decreaseQuantity: (productID) => { return $(`[${upsellPrefix}-${productID}] > .${upsellClasses.controls} .${upsellClasses.decrease}`); }, $quantity: (productID) => { return $(`[${upsellPrefix}-${productID}] > .${upsellClasses.controls} .${upsellClasses.quantity}`); } }; function createSelectList(product){ const variants = product.variants.filter(variant => variant.available); let options = ” let firstVariantImage = ” variants.forEach((variant, index) => { if(index===0) firstVariantImage = variant.featured_image.src; options += `${variant.title}` }) return { options, firstVariantImage} } function handleVariantChange(product){ $(`.${upsellClasses.info} select`).change(function(e){ const variantId = $(this).val(); const foundVariant = product.variants.find(variant => variant.id === +variantId) const variantImage = foundVariant ? foundVariant.featured_image.src : “” const variantTitle = foundVariant ? foundVariant.name : “” if(variantImage !== “”){ const formatedImage = getImageCustomSize(variantImage, 200); $(this).closest(‘.cart-upsell-item’).find(‘img’)[0].src = formatedImage } if(variantTitle !== “”){ $(this).closest(‘.cart-upsell-item’).find(‘img’)[0].setAttribute(‘data-producttitle’,variantTitle) $(this).closest(‘.cart-upsell-item’).find(`.${upsellClasses.title} a`)[0].setAttribute(‘data-producttitle’,variantTitle) $(this).closest(‘.cart-upsell-item’).find(`.${upsellClasses.addToCart}`)[0].setAttribute(‘data-producttitle’,variantTitle) } }); } function cartPopupUpsellGenerateProductHTML(product, withWrapper = true) { if(!product) return; const { options, firstVariantImage } = createSelectList(product); const productVariant = product.variants[0]; const productimage = `${productVariant.name}`; const productTitle = product.title; const variants = product.variants.filter(variant => variant.available); const isSelectNeeded = variants.length > 1 ? `${options}` : ” let add_cart_title = product.title; if(productVariant.name.length > 0){ add_cart_title = productVariant.name; } const wrapperOpen = withWrapper ? “ : “”; const wrapperclose = withWrapper ? “ : “”; return ` ${wrapperOpen} ${productimage} ${productTitle} ${isSelectNeeded} ${formatMoney(product.price, moneyFormatFull)} Add – 1 + ${wrapperclose}`; } function cartPopupUpsellAddProduct(product) { const productHtml = cartPopupUpsellGenerateProductHTML(product); $upsellSelectors.$upsell().append(productHtml); handleVariantChange(product) cartPopupUpsellProductAttachEvent(product.variants[0]); } function cartPopupUpsellProductAttachEvent(product, onlyAdd = false) { $upsellSelectors.$addToCart(product.id).click(() => { $upsellSelectors.$addToCart(product.id).trigger(cartEvents.upsell.addToCart, { product }); $upsellSelectors.$addToCart(product.id).unbind(“click”); }); $upsellSelectors.$addToCart(product.id).keyup((e) => { e.preventDefault(); if(e.key === “Enter”){ $upsellSelectors.$addToCart(product.id).trigger(cartEvents.upsell.addToCart, { product }); $upsellSelectors.$addToCart(product.id).unbind(“click”); } }); if(onlyAdd) return; $upsellSelectors.$increaseQuantity(product.id).click(() => { $upsellSelectors.$increaseQuantity(product.id).trigger(cartEvents.upsell.increaseQuantity, { product}); }); $upsellSelectors.$increaseQuantity(product.id).keyup((e) => { e.preventDefault(); if(e.key === ‘Enter’){ $upsellSelectors.$increaseQuantity(product.id).trigger(cartEvents.upsell.increaseQuantity, { product }); } }); $upsellSelectors.$decreaseQuantity(product.id).click(() => { $upsellSelectors.$decreaseQuantity(product.id).trigger(cartEvents.upsell.decreaseQuantity, { product }); }); $upsellSelectors.$decreaseQuantity(product.id).keyup((e) => { e.preventDefault(); if(e.key === ‘Enter’){ $upsellSelectors.$decreaseQuantity(product.id).trigger(cartEvents.upsell.decreaseQuantity, { product }); } }); } function cartPopupUpsellPopulate() { $(“.cart-upsell-item”).remove(); //console.log(“%c Upsell Products:”, “color: #FF336A”, upsellProducts) upsellProducts.forEach((product) => { const isUpsellProductAlreadyInCart = cart.items.filter(item => product.variants.find(variant => variant.id === item.id)); //const isProductAvailable = product.variants[0].available; //isProductAvailable && !isUpsellProductAlreadyInCart && cartPopupUpsellAddProduct(product); !isUpsellProductAlreadyInCart.length && cartPopupUpsellAddProduct(product); }); } function addUpsellToCart(product) { const $productSelector = $upsellSelectors.$productWrapper(product.id); const currentVariantID = $($productSelector).find(‘select option:selected’).val(); const qty = parseInt($upsellSelectors.$quantity(product.id)[0].innerText); const productData = { id: currentVariantID ? currentVariantID : product.id, quantity: qty, properties: { _fromUpsell: true }, attributes: { _fromUpsell: true }, }; cartPopupProgressBarSetCalculating(); const onSuccess = ({ items }) => { $productSelector.trigger(cartEvents.item.addToCart, items[0]); $(“.cart-upsell-item”).each(function(){ if($(this).data(“upsell”) !== product.id) return; $(this).remove(); }) cartPopupIsUpsellEmpty() && $upsellSelectors.$upsellContainer().trigger(cartEvents.upsell.upsellIsEmpty); if(isDiscountCodeApplied()) return; cartPopupProgressBarUpdate(); // checkIfDeviceIsMobile() && //document.getElementsByClassName(“cart-popup”)[0].scrollTo({ top: 0, behavior: “smooth” }); addCartAttribute() }; const onFail = (res) => { // 422 possible -> item sold out // 500 possible -> network error const response = res.responseJSON alert(response && response.description ? response.description : “You have reached the maximum quantity for this product” ) cartPopupProgressBarUpdate(); cartPopupUpsellProductAttachEvent(product, onlyAdd = true); }; cartAddItem(productData, onSuccess, onFail); } function removeUpsellFromCart(item) { $(document).trigger(cartEvents.upsell.removeFromCart, { item }); } function cartPopupUpsellShowRemovedProduct(product) { const removedProductIndex = upsellProducts.findIndex(({ variants }) => variants.find(v => v.id === product.id)); const removedProduct = upsellProducts[removedProductIndex]; const removedProductHtml = cartPopupUpsellGenerateProductHTML(removedProduct, false); const removedProductElement = document.createElement(“div”); removedProductElement.innerHTML = removedProductHtml; removedProductElement.className = `${upsellClasses.item}`; removedProductElement.setAttribute(`${upsellPrefix}-${product.id}`, “”); removedProductElement.setAttribute(“data-upsell”, product.id); const currentVariant = removedProduct && removedProduct.variants.find(variant => variant.id === product.id); removedProduct && $(“.cart-upsell”).append(removedProductElement); removedProduct && handleVariantChange(removedProduct) removedProduct && currentVariant && $(`.${upsellClasses.info} select option[value=’${currentVariant.id}’]`).prop(“selected”, true).trigger(“change”); // TOD: // show upsell if all items were removed and this is the first item to be added again let showUpsell = $(“.cart-upsell-item”).length > 0; showUpsell && $(document).trigger(cartEvents.upsell.upsellIsNoLongerEmpty); removedProduct && cartPopupUpsellProductAttachEvent(product); } function cartPopupIsUpsellEmpty(upsellItemsInCart = 0, upsellItemsAvailable = 0) { return $(“.cart-upsell-item”).length === 0 ? upsellItemsInCart === upsellItemsAvailable : $(“.cart-upsell-item”).length ? false : true; } function decreaseQuantity(productID){ let quantity = $upsellSelectors.$quantity(productID)[0]; if(parseInt(quantity.innerText) > 1){ const decreasedQuantity = parseInt(quantity.innerText) – 1; $upsellSelectors.$quantity(productID)[0].innerText = decreasedQuantity; } } function increaseQuantity(productID){ let quantity = $upsellSelectors.$quantity(productID)[0]; const increasedQuantity = parseInt(quantity.innerText) + 1; $upsellSelectors.$quantity(productID)[0].innerText = increasedQuantity; } function filterUpsellProducts(products, type, color = false) { //console.log(“%c Cart item color:”, “color: darkorange”, color) //console.log(“%c Cart item type:”, “color: orange”, type) const excludeGifts = products.filter(product => product.type !== “Gift Card” && product.type !== “Gift Wrapping”) const onlyDifferentTypes = excludeGifts.filter(product => product.type !== type); const onlyifIncludesColor = color && onlyDifferentTypes.filter(product => { return product.options.find(option => option.values.includes(color)); }) return onlyifIncludesColor.length ? onlyifIncludesColor : onlyDifferentTypes ; } async function findProductForUpsell(id, type, options){ if(!id || !type || !options) return; try{ const response = await fetch(`/recommendations/products.json?product_id=${id}`) const data = await response.json(); if(data){ const { products } = data; // console.log(“%c Fetched Products:”, “color: lightblue”, products); const color = options.find(option => option.name === “Color”); const filteredUpsell = filterUpsellProducts(products, type, (color ? color.value : false)); // console.log(“%c Filtered Products:”, “color: yellow”, filteredUpsell) const old_ids = upsellProducts.map(item => item.id); upsellProducts = upsellProducts.concat(filteredUpsell.filter(({id}) => !old_ids.includes(id))).slice(-4).reverse(); cartPopupUpsellPopulate(); $(“.cart-upsell-item”).length > 0 && $(document).trigger(cartEvents.upsell.upsellIsNoLongerEmpty); } } catch(e){ console.error(e); } } document.addEventListener(“DOMContentLoaded”, (event) => { $(document).on(cartEvents.upsell.addToCart, (e, { product }) => { addUpsellToCart(product); }); $(document).on(cartEvents.upsell.decreaseQuantity, (e, { product }) => { decreaseQuantity(product.id) }); $(document).on(cartEvents.upsell.increaseQuantity, (e, { product }) => { increaseQuantity(product.id) }); $(document).on(cartEvents.upsell.removedFromCart, (e, variants) => { cartPopupUpsellShowRemovedProduct(variants); }); $(document).on(cartEvents.upsell.upsellIsEmpty, (e) => { $upsellSelectors.$upsellContainer().hide(); }); $(document).on(cartEvents.upsell.upsellIsNoLongerEmpty, (e) => { $upsellSelectors.$upsellContainer().show(); }); }); // if upsell is empty (all items already in cart) -> page refreshed -> upsell stays on loaded on first open -> // -> close cart -> open cart, upsell is now correctly loaded const giftCheckbox = $(“#gift”); const giftID = 34659931717765 const addGiftToCard = (gift_id) => { const productData = { id: gift_id, quantity: 1 }; cartPopupProgressBarSetCalculating(); const onSuccess = ({ items }) => { $(document).trigger(cartEvents.item.addToCart, items[0]); $(“label[for=’gift’]”).eq(0).hide(); $(“label[for=’gift’]”).eq(1).show(); if(isDiscountCodeApplied()) return; cartPopupProgressBarUpdate(); }; const onFail = (res) => { console.log(“adding Gift to the cart failed”); // 422 possible -> item sold out // 500 possible -> network error console.log(res); cartPopupProgressBarUpdate(); }; cartAddItem(productData, onSuccess, onFail); } const removeGiftFromCart = (gift_id) => { cartPopupItemLoading(gift_id); cartPopupProgressBarSetCalculating(); const onSuccess = (cart) => { cartPopupRemoveItem(gift_id); cartObjRemoveItem(gift_id); $(“label[for=’gift’]”).eq(0).show(); $(“label[for=’gift’]”).eq(1).hide(); if (!cart.items.length) { cartFilled = false; setCartPopupBlank(); } calculateCartTotals(); updateCartTotals(); if(isDiscountCodeApplied()) return; cartPopupProgressBarUpdate(); }; const onFail = (res) => { console.log(“removing item from the cart failed”); console.log(res); cartPopupItemLoaded(gift_id); }; cartRemoveItem(gift_id, onSuccess, onFail); } const isGiftAdded = (checkbox) => { getCardInfo() .then(cartToken => { const isAdded = cartToken.items && cartToken.items.find(item => item.id === giftID); return isAdded ? checkbox.prop(‘checked’, true) : checkbox.prop(‘checked’, false) }) .catch(err => console.error(err)) } const addNoteToCart = () => { const ifChecked = giftCheckbox.is(‘:checked’); const textArea = $(“#CartNote”).val().trim(); $.ajax({ url: ‘/cart/update.js’, type: ‘POST’, data: {note: ifChecked ? textArea : ” }, success: function(result) { return; }, fail: function(error) { alert(error); } }) } giftCheckbox.change(function(event){ event.preventDefault(); if(event.target.checked){ $(this).addClass(“checked”); return giftID && addGiftToCard(giftID); } if(!event.target.checked){ $(this).removeClass(“checked”); return giftID && removeGiftFromCart(giftID); } }) $(“.cart-popup-checkout-button”).click(function(){ addNoteToCart(); }); $(document).ready(function(){ isGiftAdded(giftCheckbox); }) const couponFormCointainer = $(“.promo-code”); const couponForm = $(“.promo-code form”); const couponLoader = $(“.promo-code .loading-coupon”); const couponButton = $(“.promo-code .button-text”); const couponWrapper = $(“.coupon-wrapper”); const couponRemove = $(“.coupon-wrapper .coupon-remove”); couponForm.submit(function(e){ e.preventDefault(); const formData = $(this); const couponCode = formData.find(“#promo”).val().trim(); applyDiscountToCheckoutPage(couponCode); }) couponRemove.click(function(e){ e.preventDefault(); $(“.coupon-tag .coupon-name”).addClass(‘just_removed’); applyDiscountToCheckoutPage(‘%20’); }) const isDiscountCodeApplied = () => { return “js-discount-code” in window.localStorage ? true : false; } const applyDiscountToCheckoutPage = async(code) => { try{ startStopCouponLoading(couponButton, couponLoader) cartPopupProgressBarSetCalculating(); const response = await fetch(`/checkout?discount=${code}`) const data = await response.text(); const parser = new DOMParser(); const doc = parser.parseFromString(data, ‘text/html’); const subtotal = $(doc).find(“.payment-due__price”).text().trim(); const errorMessage = $(doc).find(“#error-for-reduction_code”); const warningMessage = $(doc).find(“.notice–warning .notice__text”); const couponText = $(doc).find(“.tag__text .reduction-code__text”).text().trim(); if(!$(“.coupon-tag .coupon-name”).hasClass(‘just_removed’)){ $(“.coupon-tag .coupon-name”).addClass(‘just_added’); } else{ $(“.coupon-tag .coupon-name”).removeClass(‘just_added’); $(“.coupon-tag .coupon-name”).removeClass(‘just_removed’); } showCallbackMessage(errorMessage, warningMessage, subtotal, couponText, code, true); calculateDiscountedPrice(); cartPopupProgressBarUpdate(); setNewHeightForVisibleItemsInCartOnResize($itemSelectors.$itemsWrapper()); } catch(err){ console.error(err); startStopCouponLoading(couponLoader, couponButton) cartPopupProgressBarUpdate(); } } const handleCheckoutDiscount = async() => { try{ if(cartBill.onlyGiftCards) return $(couponWrapper).hide(); if(!isDiscountCodeApplied()) return; cartPopupProgressBarSetCalculating(); const response = await fetch(“/checkout”) const data = await response.text(); const parser = new DOMParser(); const doc = parser.parseFromString(data, ‘text/html’); const subtotal = $(doc).find(“.payment-due__price”).text().trim(); const couponText = $(doc).find(“.tag__text .reduction-code__text”).text().trim(); showCallbackMessage([], [], subtotal, couponText, “”, false); calculateDiscountedPrice(); cartPopupProgressBarUpdate(); } catch(err){ console.error(err); cartPopupProgressBarUpdate(); } } const startStopCouponLoading = (couponButton, couponLoader ) => { couponButton.hide(); couponLoader.show(); } const calculateDiscountedPrice = () => { let discountedSubtotal = parseInt($(“.checkout_subtotal span.pull-right”).text().replace(/[^0-9]/g, ”)); const gift = cart.items.filter(item => item.id === giftID) const giftCard = cart.items.filter(item => item.gift_card); const giftCardsPrice = cart.items.reduce((acc, item) => { return item.gift_card ? acc += item.price * item.quantity : acc + 0; }, 0) if(gift.length && !giftCard.length){ subtotalWithoutDiscount = cartBill.subtotal; discountedSubtotal = discountedSubtotal; } else if(giftCard.length && !gift.length){ subtotalWithoutDiscount = cartBill.subtotal – (giftCardsPrice); discountedSubtotal = discountedSubtotal – (giftCardsPrice) } else if(giftCard.length && gift.length){ subtotalWithoutDiscount = cartBill.subtotal – (giftCardsPrice) discountedSubtotal = discountedSubtotal – (giftCardsPrice) } else{ subtotalWithoutDiscount = cartBill.subtotal; discountedSubtotal = discountedSubtotal; } if(!discountedSubtotal || !subtotalWithoutDiscount) return; const discountedPriceForItems = cart.items.map(item => { const discountPercentage = Math.round(((subtotalWithoutDiscount – discountedSubtotal) / subtotalWithoutDiscount) * 100); // (( old – new ) / old) * 100 const discountedPrice = Math.round(item.price * (1 – discountPercentage / 100)); return { id: item.id, originalPrice: formatMoney(item.price, moneyFormatFull), discountedMoney: formatMoney(discountedPrice, moneyFormatFull) } }) discountedPriceForItems.forEach(item => showDiscountedPrice(item.id, item.originalPrice, item.discountedMoney) ) } const showDiscountedPrice = (id, price, discountedPrice) => { const items = document.querySelectorAll(`.${cartPopupItemClass}`); if(!items) return; items.forEach(item =>{ if(!item.attributes.length) return; var itemAttributes = […item.attributes].map(attr => attr.nodeName) if(itemAttributes.includes(id.toString())){ const priceWrapper = item.querySelector(`.${itemClasses.discountedPrice}`); const priceWithoutDiscount = item.querySelector(`.${itemClasses.price}`); if(!priceWrapper) return; if(discountedPrice === price){ priceWrapper.innerText = “”; priceWithoutDiscount.style.fontWeight = “”; priceWithoutDiscount.style.textDecoration = “”; return; } priceWrapper.innerText = `${discountedPrice}`; priceWithoutDiscount.style.fontWeight = “100”; priceWithoutDiscount.style.textDecoration = “line-through”; } }); } const showCallbackMessage = (error, warning, subtotal, couponText, code, loader) => { //$(“.coupon-tag .coupon-name”).removeClass(‘just_added’); if(error.length || warning.length ){ $(couponWrapper).show(); if(!isDiscountCodeApplied() || (isDiscountCodeApplied() && cartBill.onlyGiftCards)){ $(“.coupon-tag”).hide(); } error.length ? couponWrapper.append(`

${error[0].innerText} `) : couponWrapper.append(`

${warning[0].innerText} `); setTimeout(() => { couponWrapper.find(“p”).remove(); if(!isDiscountCodeApplied() || (isDiscountCodeApplied() && cartBill.onlyGiftCards)){ $(couponWrapper).hide(); $(“.coupon-tag”).hide(); } else{ $(“.coupon-tag”).show(); } },5000); startStopCouponLoading(couponLoader, couponButton) couponForm.trigger(“reset”); return; } if(code === “%20”){ window.localStorage.removeItem(“js-discount-code”); $(couponWrapper).hide(); calculateCartTotals(); calculateCartShipping(); updateCartPopupSubtotal(); startStopCouponLoading(couponLoader, couponButton) couponForm.trigger(“reset”); return; }; if (!couponText) return; $(couponWrapper).show(); if((!isDiscountCodeApplied() && !cartBill.onlyGiftCards) || (isDiscountCodeApplied() && !cartBill.onlyGiftCards)){ $(“.coupon-tag”).show(); } couponWrapper.find(“.coupon-name”).text(couponText); $(“.checkout_subtotal span.pull-right”).text(subtotal); couponForm.trigger(“reset”); window.localStorage.setItem(‘js-discount-code’, JSON.stringify({checkout_subtotal: subtotal, coupon: couponText})) calculateCartShipping(); if(loader) return startStopCouponLoading(couponLoader, couponButton); } ]]>

{{/items}}

Source

Leave a Comment

Your email address will not be published. Required fields are marked *