ACDiscountApp.CartPage.Show_CalculateTier = function () { var UpdateCartItem = function (item, updatedItemPrice, updatedLinePrice, isUpdate, index) { if (isUpdate) { var originalItemPrice = globalFields.ConvertToFixedDecimalNumber(item.original_price / 100), originalLinePrice = globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100); var condition1 = updatedItemPrice == originalItemPrice; updatedItemPrice = globalFields.ConvertToFixedDecimalString(updatedItemPrice), updatedLinePrice = globalFields.ConvertToFixedDecimalString(updatedLinePrice); if (condition1) { /* Uncomment for unit price strike off */ // jQuery('.cart__price dd[data-cart-item-regular-price]').eq(index).html('
' + globalFields.currencySymbol + updatedItemPrice + '
'); // jQuery('form[action="/cart"] tbody tr:eq(' + index + ') td:eq(3) div:first').html('
' + globalFields.currencySymbol + updatedLinePrice + '
'); } else { originalItemPrice = globalFields.ConvertToFixedDecimalString(originalItemPrice), originalLinePrice = globalFields.ConvertToFixedDecimalString(originalLinePrice); // jQuery('.cart__price dd[data-cart-item-regular-price]').eq(index).html('' + globalFields.currencySymbol + originalItemPrice + '
' + globalFields.currencySymbol + updatedItemPrice + ''); // jQuery('form[action="/cart"] tbody tr:eq(' + index + ') td:eq(3) div:first').html('' + globalFields.currencySymbol + originalLinePrice + '
' + globalFields.currencySymbol + updatedLinePrice + ''); } } } var UpdateCartSubtotal = function (isUpdate, updatedTotalPrice, originalTotalPrice) { if (isUpdate) { updatedTotalPrice = globalFields.ConvertToFixedDecimalString(updatedTotalPrice), originalTotalPrice = globalFields.ConvertToFixedDecimalString(originalTotalPrice); if (originalTotalPrice != updatedTotalPrice) { // jQuery('.js-contents .totals .totals__total-value').html('' + globalFields.formatMoney(originalTotalPrice, globalFields.amount) + ' ' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + ''); //jQuery('.drawer__footer .cart-drawer__footer .totals .totals__total-value').html('' + globalFields.formatMoney(originalTotalPrice, globalFields.amount) + ' ' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + ''); } else { // jQuery('.js-contents .totals .totals__total-value').html('' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + ''); // jQuery('.drawer__footer .cart-drawer__footer .totals .totals__total-value').html('' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + ''); } } } var UpdateSavingMessage = function (isUpdate) { if (priceDiff > 0 && isUpdate && globalFields.isCartPage) { var saveMessage = globalFields.settings.cart_saving_message.replace('{{discount_amount}}', '' + globalFields.formatMoney(priceDiff.toFixed(2), globalFields.amount) + ''); var saveHtml = '' + saveMessage + ''; if (jQuery(window).width() < 700) { // jQuery('#saved-banner-div').length == 0 ? jQuery('.js-contents .totals').after('
' + saveHtml + '
') : jQuery('#saved-banner-div').html(saveHtml); } else{ // jQuery('#saved-banner-div').length == 0 ? jQuery('.js-contents .totals').after('
' + saveHtml + '
') : jQuery('#saved-banner-div').html(saveHtml); } } else if (globalFields.isCartPage) { jQuery('#saved-banner-div').remove(); } } var CheckoutClickCart = function () { jQuery('.cart__footer .cart__ctas button[name="checkout"]').click(function () { // jQuery('[name="updates[]"]').each(function () { // var qtyValue = this.value; var idAtrbtValue = jQuery(this).attr('id'); idAtrbtValue = idAtrbtValue.split('_'); idAtrbtValue = idAtrbtValue[1]; // idAtrbtValue = idAtrbtValue.split(':'); idAtrbtValue = idAtrbtValue[0]; // for (i = 0; i < globalFieldsCartPage_AC.cartObj.items.length; i++) { // if (globalFieldsCartPage_AC.cartObj.items[i].variant_id == Number(idAtrbtValue)) { globalFieldsCartPage_AC.cartObj.items[i].quantity = Number(qtyValue); } // } // }); TieredPricingCart(globalFieldsCartPage_AC.cartObj, false); //GetCode(false); }); } var CheckoutClickAjax = function () { jQuery('.drawer__footer .cart__ctas button[name="checkout"]').click(function (e) { e.preventDefault(); // GetCode(true); }); } var GetCode = function (isUpper) { if (priceDiff > 0) { $.ajax({ type: "POST", async: false, url: "https://customerapp.anncode.com/tier/ACPGenerateCartCode", data: { discountOff: priceDiff, subTotal: minimumDiscountSubtotal, discounType: "fixed_amount" }, success: function (result) { try{ if(result.status != 'error' || result.DiscountCode){ var data_ = JSON.stringify(result); var parsed_data = JSON.parse(data_); var PRID = parsed_data.PRID; var DCID = parsed_data.DCID; var DiscountCode = parsed_data.DiscountCode; SetCookie("discountCodes", PRID + "-" + DCID + "-" + DiscountCode, 30); if (!isUpper) { DiscountCodeCookie(DiscountCode); jQuery('form[action="/cart"]').append(''); } else { DiscountCodeCookie(DiscountCode); //jQuery('form.cart-form').append(''); window.location.href = '/checkout?discount=' + DiscountCode; } } else{ window.location.href = '/checkout'; } } catch(e){console.log(e);} }, error: function (e) { console.log(e.statusText); } }); } else if (isUpper) { window.location.href = '/checkout'; } } var ReInvokeAjaxCartButton = function () { jQuery('.mb_cart.mb_item button.btn, .top-header .dropdown-cart button.btn').off("click"); CheckoutClickAjax(); } var variantIdsToSend = [], minimumDiscountSubtotal = 0, priceDiff = 0; var TieredPricingCart = function (cartObject, isUpdate) { variantIdsToSend = []; minimumDiscountSubtotal = 0; priceDiff = 0; var updatedTotalPrice = 0; var actualTotalPrice = 0; var tierObj = globalFieldsCartPage_AC.cartSubTotalMetafield; let DiscountAppliedOnTag = true; if(tierObj != undefined && tierObj != "[]"){ DiscountAppliedOnTag = tierObj.DiscountAppliedON != undefined ? tierObj.DiscountAppliedON == 'Both_Store' || tierObj.DiscountAppliedON == 'Online_Store' ? true : false : false; }else{ DiscountAppliedOnTag = false; } jQuery('.maindrawer,.mainCart').remove(); if (globalFieldsCartPage_AC.cartSubTotalMetafield.status) { addProgresbarHtml(); } jQuery('.ac-main-list-item-Cart .line:last,.ac-main-list-item-Drawer .line:last').hide(); jQuery(`.display-Discount`).text(''); $('.ac-main-list-item-Cart .line,.ac-main-list-item-Drawer .line,.ac-main-list-item-Cart .circle,.ac-main-list-item-Drawer .circle').css('background-color', 'white'); $('.ac-main-list-item-Cart .circle,.ac-main-list-item-Drawer .circle').css('color', 'orange'); if (tierObj != undefined && tierObj != "[]" && tierObj.status && DiscountAppliedOnTag && globalFields.StartEndDateValid(tierObj.start_date, tierObj.end_date)) { var calculatedTier = CalculateTierCartSubTotal(tierObj, globalFieldsCartPage_AC.is_quantity_total, true); if (!calculatedTier[3]) { for (k = 0; k < globalFieldsCartPage_AC.cartTiersArray.length; k++) { var item = globalFieldsCartPage_AC.cartTiersArray[k]; actualTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.item.original_line_price / 100); if (!item.is_exclude) { variantIdsToSend.push(item.item.variant_id); } if (tierObj.discount_type == 'percentage') { var rslt = CalculateTier(item.item, calculatedTier[2], tierObj, isUpdate, k); } } minimumDiscountSubtotal = actualTotalPrice; updatedTotalPrice = actualTotalPrice - calculatedTier[5]; UpdateCartSubtotal(isUpdate, globalFields.ConvertToFixedDecimalNumber(updatedTotalPrice), globalFields.ConvertToFixedDecimalNumber(actualTotalPrice)); priceDiff = calculatedTier[5]; UpdateSavingMessage(isUpdate); } } } var CalculateTierCartSubTotal = function (tiers, is_quantity_total, isNotInRange) { var eligibleItems = jQuery.grep(globalFieldsCartPage_AC.cartTiersArray, function (n) { return !n.is_exclude; }); var allVariantItemQty = 0; var eligibleSubtotal = 0; var discount_total = 0; for (j = 0; j < eligibleItems.length; j++) { allVariantItemQty += eligibleItems[j].item.quantity; eligibleSubtotal += globalFields.ConvertToFixedDecimalNumber(eligibleItems[j].item.original_line_price / 100); } var tierPrice = 0, minTier = 0, maxTier = ''; for (i = 0; i < tiers.tier_min.length; i++) { tierPrice = parseFloat(tiers.tier_values[i]); minTier = Number(tiers.tier_min[i]), maxTier = tiers.tier_max[i] != 'max' ? Number(tiers.tier_max[i]) : tiers.tier_max[i]; var condition1 = false, condition2 = false; let requiredsubTotalOrQuantity if (is_quantity_total) { condition1 = allVariantItemQty >= minTier; condition2 = maxTier == "max" || allVariantItemQty <= maxTier; requiredsubTotalOrQuantity = allVariantItemQty } else { condition1 = eligibleSubtotal >= minTier; condition2 = maxTier == "max" || eligibleSubtotal <= maxTier; requiredsubTotalOrQuantity = eligibleSubtotal } if (condition1 && condition2) { CalculateProgreBarTierCartSubTotal(requiredsubTotalOrQuantity,is_quantity_total) isNotInRange = false; if (tiers.discount_type == 'percentage') { jQuery(`.display-Discount`).text(`YOU GET A ${tierPrice}% DISCOUNT !`); discount_total = parseFloat(globalFields.ConvertToFixedDecimalNumber((parseFloat(tierPrice) / 100) * globalFields.ConvertToFixedDecimalNumber(eligibleSubtotal))); } else if (tiers.discount_type == 'fixed') { discount_total = globalFields.ConvertToFixedDecimalNumber(parseFloat(tierPrice)); } break; } if (!condition1) { if (requiredsubTotalOrQuantity < tiers.tier_min[0]) { var getTierObj = tierObjCalculations(true); spandMessageForBar(getTierObj[0],0,requiredsubTotalOrQuantity,false) updateBarTier(getTierObj[0]) //CalculateProgreBarTierCartSubTotal(requiredsubTotalOrQuantity,is_quantity_total) } } } return [minTier, maxTier, tierPrice, isNotInRange, eligibleSubtotal, discount_total]; } var CalculateTier = function (item, tierPrice, itemTiers, isUpdate, index) { var updatedItemPrice = 0, updatedLinePrice = 0; if (itemTiers.discount_type == 'percentage') { var originalPriceCut = parseFloat(globalFields.ConvertToFixedDecimalNumber((parseFloat(tierPrice) / 100) * globalFields.ConvertToFixedDecimalNumber(item.original_price / 100))); updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(globalFields.ConvertToFixedDecimalNumber(item.original_price / 100) - originalPriceCut); } //else if (itemTiers.discount_type == 'fixed') { // updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(globalFields.ConvertToFixedDecimalNumber(item.original_price / 100) - parseFloat(tierPrice)); //} if (updatedItemPrice < 0) { updatedItemPrice = 0; } updatedLinePrice = globalFields.ConvertToFixedDecimalNumber(updatedItemPrice * item.quantity); UpdateCartItem(item, updatedItemPrice, updatedLinePrice, isUpdate, index); } var DiscountCodeCookie = function (discount_code) { $.ajax({ type: "HEAD", url: "/discount/" + discount_code, success: function (_result) { }, error: function (e) { console.log(e.statusText); } }) } var FetchCartTiers = function () { let drawerBarHtml jQuery.ajax({ async: false, url: "/cart/?view=ac_cart_subtotal_tiers", success: function (result) { setTimeout(async function () { drawerBarHtml = localStorage.getItem("drawerBarHtml"); $('.ac-CartDrawer-bar').html(drawerBarHtml) globalFieldsCartPage_AC.cartTiersArray = JSON.parse(result); TieredPricingCart(globalFieldsCartPage_AC.cartObj, true); }, 1000); }, error: function (e) { console.log(e.statusText); } }); } jQuery(document).ajaxComplete(function (event, xhr, settings) { ProcessCartResponse(settings.url, xhr.responseText); }); try { var nativeFetch = window.fetch; var isUpdatingCart = false; window.fetch = function (...args) { try { if (typeof args[0] === 'string' && (args[0].includes("/cart/change") || args[0].includes("/cart/add"))) { if (!isUpdatingCart) { isUpdatingCart = true; setTimeout(async function () { fetch('/cart.js') .then(r => r.json().then(data => ({ status: r.status, body: data }))) .then(obj => ProcessCartResponse("/cart.js", JSON.stringify(obj.body))); await setDateTimeInCart(); isUpdatingCart = false; }, 900); } } } catch (err) { console.error("Error in intercepting fetch:", err); } return nativeFetch.apply(window, args); } } catch (e) { console.error("Error in overriding fetch:", e); } var ProcessCartResponse = function (splittedUrl, responseText) { if (splittedUrl != 'undefined' && splittedUrl != "" && splittedUrl != null) { splittedUrl = splittedUrl.split("?"); if (splittedUrl[0] == "/cart.js" || splittedUrl[0] == "/cart/change.js") { globalFieldsCartPage_AC.cartObj = JSON.parse(responseText); setTimeout(function () { FetchCartTiers(); }, 400); } } } function addProgresbarHtml() { let = finalHtml = '' let cartBarHtml = ''; let drawerBarHtml = ''; var getTierObj = tierObjCalculations(true); var tierObj = getTierObj[0] cartBarHtml += `

YOU GET A 20% DISCOUNT !

` // change selecter to see progress bar on cart $('#MainContent .page-header__title').before(cartBarHtml) $('#cart-drawer-container .scd__header').after(drawerBarHtml) // add this html on Drawer file when cart is empty //{% if cart == empty %}
{% endif %} // add this to when cart in not empty {% if cart != empty %}
{% endif %} //please add both conditions on drawer file localStorage.setItem("drawerBarHtml",drawerBarHtml); $('.drawer__inner .drawer__header').html(drawerBarHtml) } function createBarHtml(spendOrClassName,tierValueOrGetAmount,barHtmlOrItem,price) {// to create an HTML bar chart. if (barHtmlOrItem == 'barHtml') { let cartBarHtml let drawerBarHtml cartBarHtml = `
  • ${tierValueOrGetAmount}
    OFF

    $${price}

  • ` drawerBarHtml = `
  • ${tierValueOrGetAmount}
    OFF

    $${price}

  • `; return [cartBarHtml,drawerBarHtml] } else if (barHtmlOrItem == 'items' || barHtmlOrItem == ''){ if(!tierValueOrGetAmount.includes('%')){ cartBarHtml = `ADD ${spendOrClassName} to get a ${tierValueOrGetAmount}% Discount` }else{ cartBarHtml = `ADD ${spendOrClassName} to get a ${tierValueOrGetAmount} Discount` } return [cartBarHtml,cartBarHtml] } else{ cartBarHtml =`🎉 You’re saving ${tierValueOrGetAmount} OFF`; return [cartBarHtml,cartBarHtml] } } function CalculateProgreBarTierCartSubTotal(requiredsubTotalOrQuantity,is_quantity_total) {// ProgreBar Tier calculation based on cart subtotal or quantity let tierForBarfun = tierObjCalculations(false); let tierForBar = tierForBarfun[0] updateBarTier(tierForBar) var tierPrice = 0, minTier = 0, maxTier = ''; for (i = 0; i < tierForBar.tier_min.length; i++) { tierPrice = parseFloat(tierForBar.tier_values[i]); minTier = Number(tierForBar.tier_min[i]), maxTier = tierForBar.tier_max[i] != 'max' ? Number(tierForBar.tier_max[i]) : tierForBar.tier_max[i]; var condition1 = false, condition2 = false; if (is_quantity_total) { condition1 = requiredsubTotalOrQuantity >= minTier; condition2 = maxTier == "max" || requiredsubTotalOrQuantity <= maxTier; } else { condition1 = requiredsubTotalOrQuantity >= minTier; condition2 = maxTier == "max" || requiredsubTotalOrQuantity <= maxTier; } if (condition1 && condition2) { nextTierofDiscount(i,tierForBarfun[1]); spandMessageForBar(tierForBar,i,requiredsubTotalOrQuantity,true) break; } if (!condition1) { // if (requiredsubTotalOrQuantity < tierForBar.tier_min[0]) { // //nextTierofDiscount(0,tierForBarfun[1]); // spandMessageForBar(tierForBar,0,requiredsubTotalOrQuantity,false) // } } } } function nextTierofDiscount(currentStep,zeroIndexTier) {//When the tier range is complete, apply the 'active-Cart' and 'active-Drawer' classes. let barCountsCart barCountsCart = document.querySelectorAll(".ac-main-list-item-Cart") barCountsCart.forEach(step => step.classList.remove("active-Cart")); barCountsCart.forEach((step, index) => { if (index <= currentStep) { step.querySelector('.line').style.backgroundColor = '#de7f30'; step.querySelector('.circle').style.backgroundColor = '#de7f30'; step.querySelector('.circle').style.color = '#fff'; } else { step.querySelector('.line').style.backgroundColor = 'white'; step.querySelector('.circle').style.backgroundColor = 'white'; step.querySelector('.circle').style.color = 'orange'; } }); let barCountsDrawer barCountsDrawer = document.querySelectorAll(".ac-main-list-item-Drawer") barCountsDrawer.forEach(step => step.classList.remove("active-Drawer")); barCountsDrawer.forEach((step, index) => { if (index <= currentStep) { step.querySelector('.line').style.backgroundColor = '#de7f30'; step.querySelector('.circle').style.backgroundColor = '#de7f30'; step.querySelector('.circle').style.color = '#fff'; } else { step.querySelector('.line').style.backgroundColor = 'white'; step.querySelector('.circle').style.backgroundColor = 'white'; step.querySelector('.circle').style.color = 'orange'; } }); jQuery('.ac-main-list-item-Cart .line:last,.ac-main-list-item-Drawer .line:last').hide(); } function spandMessageForBar(tiers,i,requiredsubTotalOrQuantity,isNotInRange) { // This function is utilized to display encouraging messages. let encourageMessageOnSpendCart = $('.ac-main-paragraphCart'); let encourageMessageOnSpendDrawer = $('.ac-main-paragraphDrawer'); encourageMessageOnSpendCart.text('') encourageMessageOnSpendDrawer.text('') let differenceAmountOrQuantity let getNextTier let FinalEncourageMessage let t = tiers.tier_values[i+1] !== undefined if (tiers.tier_values[i+1] !== undefined && isNotInRange) { if (tiers.DiscountBasedOn == "Range of Quantities") { const differenceAmountOrQuantity = tiers.tier_min[i + 1] - requiredsubTotalOrQuantity; const getNextTier = tiers.discount_type === 'percentage' ? `${tiers.tier_values[i + 1]}%` : globalFields.formatMoney((tiers.tier_values[i + 1])*100, globalFields.amount); FinalEncourageMessage = createBarHtml(differenceAmountOrQuantity,getNextTier,'items') encourageMessageOnSpendCart = FinalEncourageMessage[0]; encourageMessageOnSpendDrawer = FinalEncourageMessage[1]; } else { const differenceAmountOrQuantity = globalFields.formatMoney((tiers.tier_min[i + 1] - requiredsubTotalOrQuantity)*100, globalFields.amount); const getNextTier = tiers.discount_type === 'percentage' ? `${tiers.tier_values[i + 1]}` : globalFields.formatMoney((tiers.tier_values[i + 1])*100, globalFields.amount); FinalEncourageMessage = createBarHtml(differenceAmountOrQuantity,getNextTier,'') encourageMessageOnSpendCart = FinalEncourageMessage[0]; encourageMessageOnSpendDrawer = FinalEncourageMessage[1]; } } else { if (isNotInRange ) { if (tiers.DiscountBasedOn == "Range of Quantities") { const differenceAmountOrQuantity = tiers.tier_min[i] - requiredsubTotalOrQuantity; const getNextTier = tiers.discount_type === 'percentage' ? `${tiers.tier_values[i]}%` : globalFields.formatMoney((tiers.tier_values[i])*100, globalFields.amount); FinalEncourageMessage = createBarHtml('',getNextTier,'saving') encourageMessageOnSpendCart = FinalEncourageMessage[0]; encourageMessageOnSpendDrawer = FinalEncourageMessage[1]; } else { const differenceAmountOrQuantity = globalFields.formatMoney((tiers.tier_min[i] - requiredsubTotalOrQuantity)*100, globalFields.amount); const getNextTier = tiers.discount_type === 'percentage' ?`${tiers.tier_values[i]}%` : globalFields.formatMoney((tiers.tier_values[i])*100, globalFields.amount); FinalEncourageMessage = createBarHtml('',getNextTier,'saving'); encourageMessageOnSpendCart = FinalEncourageMessage[0]; encourageMessageOnSpendDrawer = FinalEncourageMessage[1]; } } else { if (tiers.DiscountBasedOn == "Range of Quantities") { const differenceAmountOrQuantity = tiers.tier_min[i] - requiredsubTotalOrQuantity; const getNextTier = tiers.discount_type === 'percentage' ? `${tiers.tier_values[i]}%` : globalFields.formatMoney((tiers.tier_values[i])*100, globalFields.amount); FinalEncourageMessage = createBarHtml(differenceAmountOrQuantity,getNextTier,'items'); encourageMessageOnSpendCart = FinalEncourageMessage[0]; encourageMessageOnSpendDrawer = FinalEncourageMessage[1]; } else { let djd = (tiers.tier_min[i] - requiredsubTotalOrQuantity) const differenceAmountOrQuantity = globalFields.formatMoney((tiers.tier_min[i] - requiredsubTotalOrQuantity)*100, globalFields.amount); const getNextTier = tiers.discount_type === 'percentage' ? `${tiers.tier_values[i]}%` : globalFields.formatMoney((tiers.tier_values[i])*100, globalFields.amount); FinalEncourageMessage = createBarHtml(differenceAmountOrQuantity,getNextTier,''); encourageMessageOnSpendCart = FinalEncourageMessage[0]; encourageMessageOnSpendDrawer = FinalEncourageMessage[1]; } } } $('.ac-main-paragraphDrawer').text(encourageMessageOnSpendDrawer) $('.ac-main-paragraphCart').text(encourageMessageOnSpendCart) } function tierObjCalculations(isPageLoad) { // To display exactly five bars on the cart and drawer pages, retrieve only the tier objects with a length of five. var tierForBar = globalFieldsCartPage_AC.cartSubTotalMetafield; let tierObj = { ...tierForBar }; var eligibleItems = jQuery.grep(globalFieldsCartPage_AC.cartTiersArray, function (n) { return !n.is_exclude; }); // var allVariantItemQty = 0; // var eligibleSubtotal = 0; let total = 0; var discount_total = 0; for (j = 0; j < eligibleItems.length; j++) { if (tierObj.DiscountBasedOn == "Range of Quantities") { total += eligibleItems[j].item.quantity; }else{ total += globalFields.ConvertToFixedDecimalNumber(eligibleItems[j].item.original_line_price / 100); } } let position = 0; let zeroIndexTier = false; if(tierObj.tier_min.length >= 5){ if (total < tierObj.tier_min[0]) { position = 0; zeroIndexTier = false } else if (total >= tierObj.tier_min[tierObj.tier_min.length - 1]) { position = tierObj.tier_min.length - 1; zeroIndexTier = false } else { for (let i = 0; i < tierObj.tier_min.length; i++) { if ((total >= tierObj.tier_min[i]) && ( tierObj.tier_max[i] == "max" || total <= tierObj.tier_max[i] )) { position = i; zeroIndexTier = false break; } } } tierObj.tier_min = tierObj.tier_min.length - position >= 5? tierObj.tier_min.slice(position, position + 5): tierObj.tier_min.slice(-5); tierObj.tier_max = tierObj.tier_max.length - position >= 5? tierObj.tier_max.slice(position, position + 5): tierObj.tier_max.slice(-5); tierObj.tier_values = tierObj.tier_values.length - position >= 5? tierObj.tier_values.slice(position, position + 5): tierObj.tier_values.slice(-5); } return [tierObj,zeroIndexTier] } function updateBarTier(tierObj) { // to remove the current tier class 'active-Cart' and 'active-Drawer' and update with the new tiers. let barCountsCart barCountsCart = document.querySelectorAll(".barCounts-Cart") barCountsCart.forEach(step => step.classList.remove("active-Cart")); barCountsCart.forEach((step, index) => { step.classList.remove("active-Cart"); }); let barCountsDrawer barCountsDrawer = document.querySelectorAll(".barCounts-Drawer") barCountsDrawer.forEach(step => step.classList.remove("active-Drawer")); barCountsDrawer.forEach((step, index) => { step.classList.remove("active-Drawer"); }); for (let i = 0; i < tierObj.tier_min.length; i++) { let tierValue = tierObj.discount_type == "percentage" ? `${tierObj.tier_values[i]}% OFF` : `${globalFields.formatMoney((tierObj.tier_values[i])*100, globalFields.amount)}` $('.ac-label-Cart').eq(i).text(tierValue) $('.ac-label-Drawer').eq(i).text(tierValue) } } var SetCookie = function (cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } if (globalFieldsCartPage_AC.cartSubTotalMetafield.status) { // change selecter to see progress bar on cart in addProgresbarHtml function addProgresbarHtml();//This function is utilized to add a progress bar HTML on the cart page and drawer page during page load. } async function setDateTimeInCart() { try { const response = await fetch('/cart/update.js', { method: "POST", headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { Discountly_dateTime: `${globalFields.Storetime()},${Shopify.shop}` } }) }); if (!response.ok) { throw new Error(`Error: ${response.statusText}`); } const data = await response.json(); // console.log('Cart updated successfully:', data); } catch (error) { // console.error('Failed to update cart:', error); } } // Add event listener for page load to update the cart attribute window.addEventListener('load', async () => { await setDateTimeInCart(); }); jQuery('.header__wrapper .items-center .cart-icon').click(function () { jQuery('.maindrawer').remove(); if (globalFieldsCartPage_AC.cartSubTotalMetafield.status) { addProgresbarHtml(); TieredPricingCart(globalFieldsCartPage_AC.cartObj, true); } }); TieredPricingCart(globalFieldsCartPage_AC.cartObj, true); CheckoutClickCart(); CheckoutClickAjax(); } var globalFieldsCartPage_AC = new ACDiscountApp.CartPage.Global(); var cartObject = new ACDiscountApp.CartPage.Show_CalculateTier();