ACDiscountApp.CartPage.Show_CalculateTier = function () {
var UpdateCartItem = function (item, updatedItemPrice, updatedLinePrice, isNotInRange, 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 (isNotInRange || condition1) {
jQuery('.Drawer__Container .CartItem .CartItem__Info .CartItem__PriceList').eq(index).html('
' + globalFields.formatMoney(updatedItemPrice, globalFields.amount) + '
');
jQuery('.Container.CartRemovePadding .CartItem__Info .CartItem__PriceList').eq(index).html('' + globalFields.formatMoney(updatedItemPrice, globalFields.amount) + '
');
jQuery('.Container.CartRemovePadding .CartItem__LinePriceList').eq(index).html('' + globalFields.formatMoney(updatedLinePrice, globalFields.amount) + '
');
}
else {
originalItemPrice = globalFields.ConvertToFixedDecimalString(originalItemPrice), originalLinePrice = globalFields.ConvertToFixedDecimalString(originalLinePrice);
jQuery('.Drawer__Container .CartItem .CartItem__Info .CartItem__PriceList').eq(index).html('' + globalFields.formatMoney(originalItemPrice, globalFields.amount) + '
' + globalFields.formatMoney(updatedItemPrice, globalFields.amount) + '
');
jQuery('.Container.CartRemovePadding .CartItem__Info .CartItem__PriceList').eq(index).html('' + globalFields.formatMoney(originalItemPrice, globalFields.amount) + '
' + globalFields.formatMoney(updatedItemPrice, globalFields.amount) + '
');
jQuery('.Container.CartRemovePadding .CartItem__LinePriceList').eq(index).html('' + globalFields.formatMoney(originalLinePrice, globalFields.amount) + '
' + globalFields.formatMoney(updatedLinePrice, globalFields.amount) + '
');
}
}
}
var UpdateCartSubtotal = function (isUpdate, updatedTotalPrice, originalTotalPrice) {
if (isUpdate) {
updatedTotalPrice = globalFields.ConvertToFixedDecimalString(updatedTotalPrice), originalTotalPrice = globalFields.ConvertToFixedDecimalString(originalTotalPrice);
if (originalTotalPrice != updatedTotalPrice) {
jQuery('.Cart__Recap .Cart__Total span').html('' + globalFields.formatMoney(originalTotalPrice, globalFields.amount) + ' ' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + '');
jQuery('.anncodeTotalprice').html('' + globalFields.formatMoney(originalTotalPrice, globalFields.amount) + ' ' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + '');
}
else {
jQuery('.Cart__Recap .Cart__Total span').html('' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + '');
jQuery('.anncodeTotalprice').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('.Cart__Total.Heading.u-h6').after('' + saveHtml + '
') : jQuery('#saved-banner-div').html(saveHtml);
}
else{
jQuery('#saved-banner-div').length == 0 ? jQuery('.Cart__Total.Heading.u-h6').after('' + saveHtml + '
') : jQuery('#saved-banner-div').html(saveHtml);
}
}
else if (globalFields.isCartPage) {
jQuery('#saved-banner-div').remove();
}
}
var CheckoutClickCart = function () {
jQuery('.Cart__Recap 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('.Cart.Drawer__Content button[name="checkout"]').click(function (e) {
e.preventDefault();
GetCode(true);
});
}
var GetCode = function (isUpper) {
if (priceDiff > 0) {
jQuery.ajax({
type: "POST", async: false, url: "https://customerapp.anncode.com/tier/ACPPrefixedDiscountCode",
data: { priceDifference: priceDiff, DiscountText:"TRISTAN-",subTotal: minimumDiscountSubtotal, variantIds: variantIdsToSend.toString() },
success: function (result) {
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('');
window.location.href = '/checkout?discount=' + DiscountCode;
} else {
DiscountCodeCookie(DiscountCode);
//jQuery('form.cart-form').append('');
window.location.href = '/checkout?discount=' + DiscountCode;
}
},
error: function (e) { console.log(e.statusText); window.location.href = '/checkout'; }
});
}
else if (isUpper) {
window.location.href = '/checkout';
}
else{
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 hide_buttons = null;
var HideAdditionalPayments = function() {
hide_buttons = setInterval(function() {
if(jQuery('.additional_checkout_buttons, .dynamic-checkout__content').length>0){
jQuery('.additional_checkout_buttons, .dynamic-checkout__content').hide();
clearInterval(hide_buttons);
}
}, 500);
}
let matchFirstSku = []
const firstBundelSet = (CartObjdata) => {
let bundelOneSku = [];
let bundelTwoSku = [];
let StyleMatchKey = ['FV110C1603Z', 'FV110C1605Z', 'FV110C1608Z', 'FV110C1618Z', 'FV110C1629Z', 'FV110C1641Z'];
let StyleMatchWithKey = ['FV070C1384A', 'FV070C1907A', 'FV070C1907B', 'FV070C2017Z', 'FV070C2037Z', 'FV070C2042Z', 'FV070C2043Z', 'FV070C2055Z', 'FV070C2066Z', 'FV070C2086Z', 'FV070C2087Z'];
CartObjdata.items.forEach(item => {
StyleMatchKey.forEach(key => {
if (item.sku.includes(key)) {
if(!bundelOneSku.includes(key)){
bundelOneSku.push(key);
}
}
});
StyleMatchWithKey.forEach(key => {
if (item.sku.includes(key)) {
if(!bundelTwoSku.includes(key)){
bundelTwoSku.push(key);
}
}
});
});
let fisrtBundleCheck = ((bundelOneSku.length > 0) && (bundelTwoSku.length > 0));
if(fisrtBundleCheck){
matchFirstSku = [...bundelOneSku, ...bundelTwoSku];
}else{
matchFirstSku = [];
}
}
let matchSecondSku = []
const secondBundelSet = (CartObjdata) => {
let secondbundelOneSku = [];
let secondbundelTwoSku = [];
let StyleMatchKey = ['HV110D0674A','HV110D0674B','HV110D0687A','HV110D0687B','HV110D0963Z','HV110D0967Z','HV110D0968Z','HV110D0969Z','HV110D0970Z','HV110D0971Z','HV110D0972Z','HV110D0973Z','HV110D0975Z','HV110D0977Z','HV110D0978Z','HV110D0979Z','HV110D0980Z','HV110D0982Z','HV110D0983Z'];
let StyleMatchWithKey = ['HV070D0832Z','HV070D0846Z','HV070D0849Z','HV070D0850Z','HV070D1227Z','HV070D1242Z','HV070D1246Z','HV070D1248Z','HV070D1249Z','HV070D1250Z','HV070D1255Z','HV070D1256Z','HV070D1257Z','HV070D1259Z','HV070D1260Z'];
CartObjdata.items.forEach(item => {
StyleMatchKey.forEach(key => {
if (item.sku.includes(key)) {
if(!secondbundelOneSku.includes(key)){
secondbundelOneSku.push(key);
}
}
});
StyleMatchWithKey.forEach(key => {
if (item.sku.includes(key)) {
if(!secondbundelTwoSku.includes(key)){
secondbundelTwoSku.push(key);
}
}
});
});
let secondBundleCheck = ((secondbundelOneSku.length > 0) && (secondbundelTwoSku.length > 0));
if(secondBundleCheck){
matchSecondSku = [...secondbundelOneSku, ...secondbundelTwoSku];
}else{
matchSecondSku = [];
}
}
var TieredPricingCart = function (cartObject, isUpdate) {
firstBundelSet(cartObject);
secondBundelSet(cartObject);
variantIdsToSend = []; minimumDiscountSubtotal = 0; priceDiff = 0; var updatedTotalPrice = 0;
for (k = 0; k < cartObject.items.length; k++) {
var item = cartObject.items[k], isInRange = true; itemTiers = GetTiersFromTiersArray(item.variant_id);
if (itemTiers != undefined && itemTiers.status && globalFields.StartEndDateValid(itemTiers.start_date, itemTiers.end_date) && (matchFirstSku.some(key => item.sku.includes(key)) ||matchSecondSku.some(key => item.sku.includes(key)))) {
let DiscountAppliedOn = itemTiers.DiscountAppliedON != null && itemTiers.DiscountAppliedON != '' && itemTiers.DiscountAppliedON != undefined ? true : false;
let Location_Tag_s = itemTiers.Location_Tag_ != null && itemTiers.Location_Tag_ != '' && itemTiers.Location_Tag_ != undefined ? true : false;
if(DiscountAppliedOn){
if(Location_Tag_s){
let DiscountAppliedOnTag =itemTiers.DiscountAppliedON == 'Both_Store' || itemTiers.DiscountAppliedON == 'Online_Store' ? true : false;
let LocationObject = Object.keys(itemTiers.Location_Tag_);
if(LocationObject[0] == 'StoreLocation'){
let StoreLocationcheck = itemTiers.Location_Tag_[LocationObject[0]].includes(globalFields.Storecountry) || itemTiers.Location_Tag_[LocationObject[0]].includes(globalFields.Storecity) ? true : false;
if(StoreLocationcheck && DiscountAppliedOnTag){
var rslt = CalculateTier(item, itemTiers, updatedTotalPrice, isUpdate, true, k);
updatedTotalPrice = rslt[0]; isInRange = rslt[1];
if (rslt[1]) {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}else{
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}else{
let TierLocation = itemTiers.Location_Tag_[LocationObject[0]];
let CusotmerCountryLocation = globalFields.Customercountry;
let CusotmerCityLocation = globalFields.Customercity;
let CustomerLocationcheck_1 = (arr, arr1) =>{return arr.some(item => arr1.includes(item))};
let CustomerLocationcheck_2 = (arr2, arr3) =>{return arr2.some(item => arr3.includes(item))};
let CityValue = CustomerLocationcheck_1(TierLocation,CusotmerCountryLocation);
let CountryValue = CustomerLocationcheck_2(TierLocation,CusotmerCityLocation);
if(DiscountAppliedOnTag && (CityValue || CountryValue)){
var rslt = CalculateTier(item, itemTiers, updatedTotalPrice, isUpdate, true, k);
updatedTotalPrice = rslt[0]; isInRange = rslt[1];
if (rslt[1]) {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}else{
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}
}else{
if(itemTiers.DiscountAppliedON == 'Both_Store' || itemTiers.DiscountAppliedON == 'Online_Store' ){
var rslt = CalculateTier(item, itemTiers, updatedTotalPrice, isUpdate, true, k);
updatedTotalPrice = rslt[0]; isInRange = rslt[1];
if (rslt[1]) {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}else{
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}
}else{
var rslt = CalculateTier(item, itemTiers, updatedTotalPrice, isUpdate, true, k);
updatedTotalPrice = rslt[0]; isInRange = rslt[1];
if (rslt[1]) {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}
}
else {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
if (!isInRange) {
minimumDiscountSubtotal += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100); variantIdsToSend.push(item.variant_id);
}
}
UpdateCartSubtotal(isUpdate, globalFields.ConvertToFixedDecimalNumber(updatedTotalPrice), globalFields.ConvertToFixedDecimalNumber(cartObject.original_total_price / 100));
priceDiff = globalFields.ConvertToFixedDecimalNumber((globalFields.ConvertToFixedDecimalNumber(cartObject.original_total_price / 100) - globalFields.ConvertToFixedDecimalNumber(updatedTotalPrice)));
UpdateSavingMessage(isUpdate);
if(priceDiff){
HideAdditionalPayments();
}
setTimeout(function(){
clearInterval(hide_buttons);
}, 5000);
}
setTimeout(function(){
clearInterval(hide_buttons);
}, 10000);
var GetTiersFromTiersArray = function (variantId) {
var tierObj = jQuery.grep(globalFieldsCartPage_AC.cartTiersArray, function (n) { return (n.variant_id === variantId); });
if (tierObj[0].tiers == "[]") {
return undefined;
}
else {
return globalFields.GetTierObject(tierObj[0].tiers[0], variantId);
}
}
var CalculateTier = function (item, itemTiers, updatedTotalPrice, isUpdate, isNotInRange, index) {
for (i = 0; i < itemTiers.tier_min.length; i++) {
var allVariantItemQty = 0;
var tierPrice = parseFloat(itemTiers.tier_values[i]);
var minTier = parseInt(itemTiers.tier_min[i]), maxTier = itemTiers.tier_max[i] != 'max' ? parseInt(itemTiers.tier_max[i]) : itemTiers.tier_max[i];
var updatedItemPrice = 0, updatedLinePrice = 0, condition1 = false, condition2 = false;
if (itemTiers.entity_type === 'products' || itemTiers.entity_type === 'collections') {
var tempItemArray = [];
if (itemTiers.entity_type === 'collections') {
var tempTierArray = jQuery.grep(globalFieldsCartPage_AC.cartTiersArray, function (n) { return (n.tiers != '[]' && n.tiers[0].entity_type == 'collections' && n.tiers[0].entity_id == itemTiers.entity_id); });
for (var m = 0; m < tempTierArray.length; m++) {
var temp = jQuery.grep(globalFieldsCartPage_AC.cartObj.items, function (n) { return (n.variant_id == tempTierArray[m].variant_id); });
if (temp.length != 0) {
tempItemArray.push(temp[0]);
}
}
}
else {
tempItemArray = jQuery.grep(globalFieldsCartPage_AC.cartObj.items, function (n) { return (n.product_id == item.product_id ); });
}
for (j = 0; j < tempItemArray.length; j++) { allVariantItemQty += tempItemArray[j].quantity; }
condition1 = allVariantItemQty >= minTier;
condition2 = maxTier == "max" || allVariantItemQty <= maxTier;
}
else {
condition1 = item.quantity >= minTier;
condition2 = maxTier == "max" || item.quantity <= maxTier;
}
if (condition1 && condition2) {
isNotInRange = false;
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));
}
else if (itemTiers.discount_type == 'fixed_price') {
updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(parseFloat(tierPrice));
}
if (updatedItemPrice < 0) { updatedItemPrice = 0; }
updatedLinePrice = globalFields.ConvertToFixedDecimalNumber(updatedItemPrice * item.quantity);
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(updatedLinePrice);
UpdateCartItem(item, updatedItemPrice, updatedLinePrice, isNotInRange, isUpdate, index);
}
}
if (isNotInRange) {
UpdateCartItem(item, globalFields.ConvertToFixedDecimalNumber(item.original_price / 100), globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100), isNotInRange, isUpdate, index);
}
return [updatedTotalPrice, isNotInRange];
}
var DiscountCodeCookie = function (discount_code) {
jQuery.ajax({
type: "HEAD", url: "/discount/" + discount_code,
success: function (_result) { },
error: function (e) { console.log(e.statusText); }
})
}
var FetchCartTiers = function () {
jQuery.ajax({
async: false,
url: "/cart/?view=ac_cart_tiers",
success: function (result) {
globalFieldsCartPage_AC.cartTiersArray = JSON.parse(result);
TieredPricingCart(globalFieldsCartPage_AC.cartObj, true);
CheckoutClickAjax();
},
error: function (e) { console.log(e.statusText); }
});
}
jQuery(document).ajaxComplete(function (event, xhr, settings) {
ProcessCartResponse(settings.url, xhr.responseText);
});
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();
}, 800);
}
}
}
try {
var nativeFetch = window.fetch;
window.fetch = function (...args) {
try {
if (typeof args[0] === 'string' && (args[0].includes("/cart/change") || args[0].includes("/cart/add") || args[0].includes("/cart/update"))) {
setTimeout(function () {
fetch('/cart.js')
.then(r => r.json().then(data => ({ status: r.status, body: data })))
.then(obj => ProcessCartResponse("/cart.js", JSON.stringify(obj.body)));
}, 800);
}
} catch (err) {
console.error("Error in intercepting fetch:", err);
}
return nativeFetch.apply(window, args);
}
} catch (e) {
console.error("Error in overriding fetch:", e);
}
/* If browser back button was used, flush cache */
(function () {
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload();
}
};
})();
var headerClickFun = function () {
jQuery('#header-open-drawer').click(function (e) {
TieredPricingCart(globalFieldsCartPage_AC.cartObj, true); CheckoutClickCart(); CheckoutClickAjax();
});
}
window.addEventListener('load', function () {
TieredPricingCart(globalFieldsCartPage_AC.cartObj, true); CheckoutClickCart(); CheckoutClickAjax();headerClickFun()
setTimeout(function () {
TieredPricingCart(globalFieldsCartPage_AC.cartObj, true);
}, 2000);
})
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=/"; }
TieredPricingCart(globalFieldsCartPage_AC.cartObj, true); CheckoutClickCart(); CheckoutClickAjax();headerClickFun();
}
var globalFieldsCartPage_AC = new ACDiscountApp.CartPage.Global(); var cartObject = new ACDiscountApp.CartPage.Show_CalculateTier();