"; source = ((CCRZ.getCookie("handlebars") != "") ? preSource : "") + source; } return Handlebars.compile(source); } }); /* //////////////////////////////////////////////////////// //////////////// GLOBAL AUXILIAR FUNCTIONS //////////////// */ ///////////////////////////////////////////////////////// // CLONE ANY OBJECT function cloneObject(objectToClone) { return JSON.parse(JSON.stringify(objectToClone)); } //Asigna a un un texto de error //Parametros: //elem: $("#elemento") o $(".clase") etc //message: "mensaje de error" function setMessageErrorInElement(elem, message) { elem.html(message).css("color", "#ff0000"); } //Limpia el de error //Parametros: //elem: $("#elemento") o $(".clase") etc //millisecond: 3000 o la cantidad de milisegundos que desee function hideMessageErrorInElement(elem, millisecond) { setTimeout(() => { elem.html(''); }, millisecond); } //Deshabilita los input de un form //Parametros: //elem: $("#elemento") o $(".clase") etc //excludeInput: string de input que desea excluir separados por coma(,). Ejm: "#txtInput1,.txtClassBtn,#txtArea" function disabledForm(elem, excludeInput) { if (excludeInput != undefined) { elem.not(excludeInput).prop('disabled', true); } else { elem.prop('disabled', true); } } //Habilita los input de un form //Parametros: //elem: $("#elemento") o $(".clase") etc function enabledForm(elem) { elem.prop('disabled', false); } //Valida si es visita o no function IsGuest() { if (CCRZ.currentUser.UserType == 'Guest') { return true; } else { return false; } } //Retorna el nombre del día de la semana function getDayName(dayNumber) { let weekday = new Array(7); weekday[0] = "Global_DayName1"; weekday[1] = "Global_DayName2"; weekday[2] = "Global_DayName3"; weekday[3] = "Global_DayName4"; weekday[4] = "Global_DayName5"; weekday[5] = "Global_DayName6"; weekday[6] = "Global_DayName7"; return weekday[dayNumber]; } //Habilita los popovers de un form //Parametros: //elem: $("#elemento") o $(".clase") etc function showMessageTypePopover(elem, title, content, timeClose) { if(CCRZ.getPageConfig('pd.enablepopuppl')){ if($(elem).data('isavailableurl')){ elem.attr('data-html', true); let brandTitle=CCRZ.productDetailModel.attributes.product.prodBean.brandName; let labelBrand=CCRZ.pagevars.pageLabels.seeMoreProductsByBrand?CCRZ.pagevars.pageLabels.seeMoreProductsByBrand:''; let writter=''; let store=CCRZ.pagevars.storefrontName; writter+='
"; } $("#writerExtDataComprador").append(writer); } function writerData( name,ape,email){ $("#writerDataComprador").empty(); // var ape=CCRZ.cartCheckoutView.model.attributes.buyerLastName; // var email=CCRZ.cartCheckoutView.model.attributes.buyerEmail; var writer=""; writer+="
"; $("#writerDataComprador").append(writer); } function paintCustomerData(){ if(CCRZ.pagevars.isGuest){ var nameP=CCRZ.cartCheckoutView.model.attributes.buyerFirstName; var apeP=CCRZ.cartCheckoutView.model.attributes.buyerLastName; var emailP=CCRZ.cartCheckoutView.model.attributes.buyerEmail; writerData(nameP, apeP,emailP); }else{ var nameP=CCRZ.currentUser.FirstName; var apeP=CCRZ.currentUser.LastName; var emailP=CCRZ.currentUser.Email; writerData(nameP, apeP,emailP); } } function clearAmuntAndDelivaryData(){ $("#writerTax").empty(); $("#writertotalAmount").empty(); $("#writerShip").empty(); $("#writerExtDataComprador").empty(); $(".plusInfo").attr("style","display:none"); $(".plusInfoTot").attr("style","display:none"); $(".plusInfoEnv").attr("style","display:none"); } function updateInfo(){ CCRZ.LoadTaxMiniCart=null; if(CCRZ.pagevars.currentPageName == "ccrz__CheckoutNew"){ if(CCRZ.pagevars.isGuest){ CCRZ.LoadTaxMiniCart =setInterval(function() { if(!(typeof CCRZ.cartCheckoutView.model.attributes.buyerFirstName == "undefined")){ // var nameP=CCRZ.cartCheckoutView.model.attributes.buyerFirstName; // var apeP=CCRZ.cartCheckoutView.model.attributes.buyerLastName; // var emailP=CCRZ.cartCheckoutView.model.attributes.buyerEmail; // writerData(nameP, apeP,emailP); paintCustomerData() if(CCRZ.CheckoutPayload!=undefined){ writeExtData(); } updateMiniCartFields(); clearInterval(CCRZ.LoadTaxMiniCart); } }, 1000); }else{ CCRZ.LoadTaxMiniCart =setInterval(function() { console.log('pregunta') if(!(typeof CCRZ.currentUser === "undefined")){ console.log( 'curr:-',CCRZ.currentUser); // var nameP=CCRZ.currentUser.FirstName; // var apeP=CCRZ.currentUser.LastName; // var emailP=CCRZ.currentUser.Email; // writerData(nameP, apeP,emailP); paintCustomerData() if(CCRZ.CheckoutPayload!=undefined){ writeExtData(); } updateMiniCartFields(); clearInterval(CCRZ.LoadTaxMiniCart); } }, 1000); } } } function is_MC_Pixel_Active() { let isActive = false if(typeof _etmc !== "undefined" && CCRZ.getPageConfig('sfmc.mcp_enable',false)){ isActive = true } return isActive } function linkHawkSend(e){ let hawkKey = ''; //CCRZ.pagevars.storefrontName == 'B2CCochez' ? '3f3063fb0b584d43b6c91421aede6c03' : '49842e22915f43fcbcc5c5bcd8280800'; switch (CCRZ.pagevars.storefrontName) { case "B2CCochez": hawkKey = '3f3063fb0b584d43b6c91421aede6c03'; break; case "B2CNovey": hawkKey = '49842e22915f43fcbcc5c5bcd8280800'; break; case "B2BCochez": hawkKey = '3f3063fb0b584d43b6c914XXXXXXXXXX'; break; } HawkSearch.link(e,hawkKey,1, e.target.dataset.productsfid,0) ; //e.stopImmediatePropagation(); } // --------------------- PROTOTYPE ------------------------ String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); } // ---------------- REMOTE INVOKE ACTION ----------------- // Utilizar para cuando el método del controlador recive un JSON como parámetro //----- // Parámetros // remoteCallObj: el objeto con contexto del controlador que se va utilizar. // remoteActionName: nombre del metodo o action a ejecutar en el controlador // data: parametros(objeto) en formato string function callCtrlRemoteAction(remoteCallObj, remoteActionName, data) { // console.log(arguments); return new Promise(function(resolve, reject) { remoteCallObj.invokeContainerLoadingCtx($('.deskLayout'), remoteActionName, data, function(res, err) { if (res != null) { resolve(res); } else if (err.message != "") { resolve(err); } }, { nmsp: false }); }); } //---------- Format data MC PIXEL function set_MC_Pixel_PurchaseSuccess(dataPurchase) { let data = { 'cart': [], 'order_number': dataPurchase.sfdcName, // Transaction ID. Required for purchases and refunds <----- ORDER NUMBER ON SALESFORCE. 'discount': '', 'shipping': dataPurchase.shippingCharge, // Shipping value) 'details': { 'originatedCart' : dataPurchase.originatedCart, 'buyerEmail': dataPurchase.buyerEmail, 'buyerFirstName': dataPurchase.buyerFirstName, 'buyerLastName': dataPurchase.buyerLastName, 'buyerMobilePhone': dataPurchase.buyerMobilePhone, 'contactId': dataPurchase.contact, 'shippingCharge': dataPurchase.shippingCharge, 'subTotal': dataPurchase.subTotal, 'tax': dataPurchase.tax, 'taxSubTotalAmount': dataPurchase.taxSubTotalAmount, 'totalAmount': dataPurchase.totalAmount } } let productList = dataPurchase.orderItems for(product of productList){ data.cart.push({ item: product.mockProduct.name, quantity: product.quantity, price: product.price, unique_id: product.mockProduct.sku }); } if(CCRZ.getPageConfig('env.isprod',false)){ _etmc.push(["trackConversion", data]) }else{ console.log("data compra MC Pixel => ",data) } } //-------------------------------------------------------------------------------- // --------------- FUNCTION DRAG SCROLL FOR PAINT PALETTE ---------------- //-------------------------------------------------------------------------------- function setDragScroll( elemName ) { const ele = document.getElementById( elemName ); ele.style.cursor = 'grab'; let pos = { top: 0, left: 0, x: 0, y: 0 }; const mouseDownHandler = function(e) { ele.style.cursor = 'grabbing'; ele.style.userSelect = 'none'; pos = { left: ele.scrollLeft, top: ele.scrollTop, // Get the current mouse position x: e.clientX, y: e.clientY, }; document.addEventListener('mousemove', mouseMoveHandler); document.addEventListener('mouseup', mouseUpHandler); }; const mouseMoveHandler = function(e) { // How far the mouse has been moved const dx = e.clientX - pos.x; const dy = e.clientY - pos.y; // Scroll the element ele.scrollTop = pos.top - dy; ele.scrollLeft = pos.left - dx; }; const mouseUpHandler = function() { ele.style.cursor = 'grab'; ele.style.removeProperty('user-select'); document.removeEventListener('mousemove', mouseMoveHandler); document.removeEventListener('mouseup', mouseUpHandler); }; // Attach the handler ele.addEventListener('mousedown', mouseDownHandler); } function ifApplyExpressDelivery(){ if(CCRZ.getPageConfig('exdev.stl')){ let availableExpressList = CCRZ.getPageConfig('exdev.stl').split(','); let sucursalFilter; if(localStorage.getItem('locStor'+getPrefixStore3())){ sucursalFilter = getCodeCompany()+(JSON.parse(localStorage.getItem('locStor'+getPrefixStore3())).codigo); if( availableExpressList.find(x=>((x.trim())==sucursalFilter)) ){ // validamos si el horario de la sucursal está habilitado para el horario de Delivery Express /*( ifApplyExpressDeliveryByTime() == true ) ? $('.expressDeliveryStyle').show() : $('.expressDeliveryStyle').hide();*/ const productId = (CCRZ.pagevars.currentPageName == 'ccrz__ProductDetails') ? CCRZ.productDetailModel.attributes.product.prodBean.id : ''; getStatusExpressDeliveryByStore(productId).then(function(res) { if( res == true ){ /*let productBorderTypeDelivery = $(".delivery-type").has('div.box-border-quad'); productBorderTypeDelivery.addClass('box-border-quad-express'); productBorderTypeDelivery.removeClass('box-border-quad'); let productIconTypeDelivery = productBorderTypeDelivery.children('img')[0]; productIconTypeDelivery.src = 'https://storage.googleapis.com/chz-marketing-repositorio-fotos/cochez/Iconos/truck-express.svg '; let productTextTypeDelivery = $('.msg-quad-inv-delivery'); productTextTypeDelivery.empty(); productTextTypeDelivery.append('
Disponible para entrega a domicilio express en 45 minutos
'); productTextTypeDelivery.removeAttr('style'); productTextTypeDelivery.css('color', 'green');*/ //$('.expressDeliveryStyle').show(); // Si se obtiene una respuesta igualmente apagamos lógica para express delivery // Apagamos lógica para express delivery $('.expressDeliveryStyle').hide() }else{ // validamos si el horario de la sucursal está habilitado para el horario de Delivery Express // Apagamos lógica para express delivery /*( ifApplyExpressDeliveryByTime() == true ) ? $('.expressDeliveryStyle').show() : $('.expressDeliveryStyle').hide();*/ $('.expressDeliveryStyle').hide() } }) .catch(function(error) { console.log("Error when validating if it is a holiday : " + error); }); // Validación para horarios especiales / feriados para sucursales // ***Se comenta bloque de validación a espera de ajuste en ambiente de desarrollo*** /*let dateToday = moment().format('YYYY-MM-DD'); const ciaCodeStore = (JSON.parse(localStorage.getItem('locStor'+getPrefixStore3())).codigo); const ciaCodeCompany = getCodeCompany(); ifApplyStoreBySpecialHour(dateToday, ciaCodeCompany, ciaCodeStore).then(function(res) { if( res == true ){ let productBorderTypeDelivery = $('.box-border-quad-express'); productBorderTypeDelivery.addClass('box-border-quad'); productBorderTypeDelivery.removeClass('box-border-quad-express'); let productIconTypeDelivery = productBorderTypeDelivery.children('img')[0]; productIconTypeDelivery.src = 'https://storage.googleapis.com/chz-marketing-repositorio-fotos/novey/iconos_storefront/deliveryNoveyV2.svg'; let productTextTypeDelivery = $('.msg-quad-inv-delivery'); productTextTypeDelivery.empty(); productTextTypeDelivery.append('
Disponible para entrega a domicilio
'); productTextTypeDelivery.removeAttr('style'); productTextTypeDelivery.css('color', '#0055b8'); //$('.expressDeliveryStyle').hide(); }else{ // validamos si el horario de la sucursal está habilitado para el horario de Delivery Express ( ifApplyExpressDeliveryByTime() == true ) ? $('.expressDeliveryStyle').show() : $('.expressDeliveryStyle').hide(); } }) .catch(function(error) { console.log("Error when validating if it is a holiday : " + error); });*/ }else{ $('.expressDeliveryStyle').hide() } } } } function ifApplyExpressDeliveryByTime(){ let date = new Date(); // Creamos y asignamos una fecha / hora para validar horarios // fuera del delivery express //let date2 = new Date().toISOString().split('T')[0]; //date2 = date2 + ' 03:30:00 PM'; // Get current hour with timezone. Require moment-timezone library const currentHour = moment(date, 'YYYY-MM-DD H:mm:ss a').tz('America/Panama').format('HH:mm:ss'); const openHour = date.toISOString().split('T')[0] + ' ' + CCRZ.getPageConfig('exdev.enableexpressdelivery'); const openHourDeliveryExpress = moment(openHour, 'YYYY-MM-DD H:mm:ss a').format('HH:mm:ss'); const closeHour = date.toISOString().split('T')[0] + ' ' + CCRZ.getPageConfig('exdev.disableexpressdelivery'); const closeHourDeliveryExpress = moment(closeHour, 'YYYY-MM-DD H:mm:ss a').format('HH:mm:ss'); return ( ( currentHour >= openHourDeliveryExpress) == true && (currentHour <= closeHourDeliveryExpress) == true ) ? true : false; } // Obtenemos los datos para validación si existe sucursal con horario especial o feriado /*function ifApplyStoreBySpecialHour(specialDate, ciaCode, ciaStore){ let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); remoteCall.invokeCtx('getStoreBySpecialHour', specialDate, ciaCode, ciaStore, function(response, event) { //console.log("AJX RESPONSE :: ==> " + response); let applyResponseSH; if(!response.data.length == 0){ const HoraInicioStore = response.data[0].Hora_Inicio__c; const HoraFinStore = response.data[0].Hora_Fin__c; if( HoraInicioStore == "cerrado" && HoraFinStore == "cerrado"){ applyResponseSH = true; }else{ applyResponseSH = false; } }else{ applyResponseSH = false; } return applyResponseSH; }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); }*/ /* @return promise Validamos si existe una sucursal con horario especial o feriado */ /*function ifApplyStoreBySpecialHour( specialDate, ciaCode, ciaStore ) { return new Promise((resolve, reject) => { let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); remoteCall.invokeCtx('getStoreBySpecialHour', specialDate, ciaCode, ciaStore, function(response, event) { let applyResponseSH; if(!response.data.length == 0){ const HoraInicioStore = response.data[0].Hora_Inicio__c; const HoraFinStore = response.data[0].Hora_Fin__c; if( HoraInicioStore == "cerrado" && HoraFinStore == "cerrado"){ applyResponseSH = true; resolve(applyResponseSH); }else{ applyResponseSH = false; reject(applyResponseSH); } }else{ applyResponseSH = false; reject(applyResponseSH); } return applyResponseSH; }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); }); }*/ /* @return promise VALIDAMOS SI EL PRODUCTO TIENE DELIVERY EXPRESS Y SI ESTÁ EN EL CENTRO DE ENTREGA EXPRESS */ function getStatusExpressDeliveryByStore( productId ) { return new Promise((resolve, reject) => { let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); remoteCall.invokeCtx('getStatusExpressDeliveryByStore', productId, function(response, event) { let applyResponseSH; if(!response.data.length == 0){ console.log('EXPRESS DELIVERY RESPONSE ==> ' + JSON.stringify(response.data)); const expressDeliveryStatus = response.data[0].ccrz__ProductItem__r.express_delivery__c; const inventoryLocationCode = response.data[0].ccrz__InventoryLocationCode__c; console.log("EXPRESS DELIVERY STATUS ==> "+expressDeliveryStatus); console.log("INVENTORY LOCATION CODE ==> "+inventoryLocationCode); if(expressDeliveryStatus == true && inventoryLocationCode == '0303'){ applyResponseSH = true; resolve(applyResponseSH); }else{ applyResponseSH = false; reject(applyResponseSH); } }else{ applyResponseSH = false; reject(applyResponseSH); } return applyResponseSH; }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); }); } function enabledBrandForInk(){ let brandName = CCRZ.prodDetailView.model.attributes.product.prodBean.brandName if(brandName != null){ let brandEnables = CCRZ.getPageConfig('paint.brands_enable').split(',') return brandEnables.includes(brandName.toLowerCase().capitalize()) } else { return false } } // id: a1F5C000000kRcWUAU // qty: 1 function addToCartSFAsync( id, qty ) { console.log("JMC ================> entro"); return new Promise((resolve, reject) => { //Valida el inventario let data=[{ prodId: id, qty: qty.toString() }]; let remoteCall = _.extend(CCRZ.RemoteInvocation, { className: 'AddToCartRemoteValidator' }); remoteCall.invokeContainerLoadingCtx($('.deskLayout'), 'itemQuantityValidationRemoteAction', JSON.stringify(data), function (res, err) { if (res != null) { if (res.success) { //Agrega al carrito el producto let remoteCall2 = _.extend(CCRZ.RemoteInvocation, { className: 'ccrz.cc_RemoteActionController' }); remoteCall2.invokeContainerLoadingCtx($('.deskLayout'), 'addItem', id, qty, null, null, "", null, function (res, err) { if (res.success) { resolve(res); CCRZ.pubSub.trigger('cartChange', res.data); } }, { nmsp: false }); } else { reject(res); } } else if (err.message != "") { reject(res); } }, { nmsp: false }); }); } CCRZ.pubSub.on("chargeFooter", function() { // function hawkLoadEvent(){ if(CCRZ.getPageConfig('hsm.enable_hs')){ if(CCRZ.pagevars.currentPageName=="ccrz__HomePage"){ HawkSearch.Tracking.track('pageload',{pageType: "landing"}); } if(CCRZ.pagevars.currentPageName=="ccrz__Cart"){ HawkSearch.Tracking.track('pageload',{pageType: "cart"}); } if(CCRZ.pagevars.currentPageName=="ccrz__MyAccount"){ HawkSearch.Tracking.track('pageload',{pageType: "custom"}); } if(CCRZ.pagevars.currentPageName=="ccrz__CheckoutNew"){ HawkSearch.Tracking.track('pageload',{pageType: "custom"}); } if(CCRZ.pagevars.currentPageName=="ccrz__ProductList"){ HawkSearch.Tracking.track('pageload',{pageType: "custom"}); } if(CCRZ.pagevars.currentPageName=="ccrz__ProductList"){ } if(CCRZ.pagevars.currentPageName=="ccrz__ProductDetails"){ // setTimeout(() => { HawkSearch.Context.add("uniqueid", CCRZ.productDetailModel.attributes.product.prodBean.id) // }, 1000); HawkSearch.Tracking.track('pageload',{pageType: "item"}); } } }); function hawkDataTrackCynx(qty, typeProduct, dataProduct){ console.log('datos '+ dataProduct.sfidProd); console.log('datos2 '+ dataProduct.id); sfidHawk=dataProduct.sfidProd?dataProduct.sfidProd:dataProduct.id; sendEventHawkTrackAdd2Cart(sfidHawk,dataProduct.price,qty) } function sendEventHawkTrackAdd2Cart(sfidHawk,price,qty){ console.log('hawkEventSend => '+ sfidHawk); HawkSearch.Tracking.track('add2cart',{ uniqueId: sfidHawk, price: parseFloat(price), quantity: parseInt(qty), currency: 'USD' }); } function hawkDataTrackOrderConfirmation(dataPurchase){ let oItems=[]; if(dataPurchase.orderItems){ for(item of dataPurchase.orderItems ){ if(item.product && item.price && item.quantity){ oItems.push({ uniqueid: item.product, itemPrice: item.price, quantity: item.quantity }) } } HawkSearch.Tracking.track('sale', { orderNo: dataPurchase.orderName, itemList: oItems, total: dataPurchase.totalAmount, subTotal: dataPurchase.subTotal, tax: dataPurchase.tax, currency: 'USD' }); } // HawkSearch.Tracking.track('sale', { // orderNo: dataPurchase.orderName, // itemList: dataPurchase.orderItems, // total: dataPurchase.totalAmount, // subTotal: dataPurchase.subTotal, // tax: dataPurchase.tax, // currency: 'USD' // }); } CCRZ.pubSub.on("view:PaymentProcessorView:refresh", function() { updateInfo(); setTimeout(() => { $("#overlay").remove() }, 2000); }) function momentFormatLLLL(date){ let dateLLLL = '' if(date != ''){ let arrDates = moment(date).format('LLLL').split(' ') arrDates[0] = arrDates[0].toLowerCase().capitalize() arrDates.splice(arrDates.length-1) dateLLLL = arrDates.join(' ') } else { dateLLLL = 'Fecha invalida' } return dateLLLL } function obtenerValorParametroBase(sParametroNombre,url) { var sPaginaURL = url; var sURLVariables = sPaginaURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParametro = sURLVariables[i].split('='); if (sParametro[0] == sParametroNombre) { return sParametro[1]; } } return null; } //Funcion que retorna la distancia en kilometros entre dos conjuntos de coordenadas function getDistanceByTwoCoordinates(lat1, lon1, lat2, lon2){ rad = function(x){ return x * Math.PI/180; } //Radio de la tierra en km let R = 6371; let dLat = rad( lat2 - lat1 ); let dLong = rad( lon2 - lon1 ); let a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLong/2) * Math.sin(dLong/2); let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); let d = R * c; return d.toFixed(2); } //Funcion que ordena por alguna propiedad del JSON function jsonSortOrder(prop) { return function(a, b) { if (a[prop] > b[prop]) { return 1; } else if (a[prop] < b[prop]) { return -1; } return 0; } } //Funcion que seteara la tienda y la actualiza en el widget componente del header selector de tiendas function setLocStore(storeCode, isChangingStore){ let cia = getCodeCompany() let stores = JSON.parse(localStorage.getItem('stores'+getPrefixStore3())) let storeSelected = stores.find( x => (cia+x.centro == storeCode) ) let jsonStore = JSON.stringify({ codigo:storeSelected.centro, tienda:storeSelected.nombre, direccion:storeSelected.direccion, horarioLV:storeSelected.horarioLunesViernes, horarioS:storeSelected.horarioSabado, horarioD:storeSelected.horarioDomingo, coordenadas: storeSelected.coordenadas }) if (isChangingStore) { CCRZ.pubSub.trigger('pickStore_Event', storeSelected.nombre); } localStorage.setItem('locStor'+getPrefixStore3(), jsonStore) //Actualiza el componente widget de tiendas en el header locationSelected() } function loaderPayment(text1, text2){ let customLoader = `
${text1}
${text2}
${text1}
${text2}
` return customLoader } /* GIFT CARD */ //variable global var processCount = 0; var addItemSuccessCount = 0; // CCRZ.pubSub.on('view:cartView:refresh', function(){ // if((JSON.parse(sessionStorage.getItem('giftcard')) != null) && (CCRZ.pagevars.queryParams.pagekey != 'GiftCard') && (CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__CheckoutNew') && CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__OrderConfirmation'){ // if(JSON.parse(sessionStorage.getItem('savedCartItems')) != null){ // checkCartToRemoveGiftCard(false); // sessionStorage.removeItem('giftcard'); // let savedItems = JSON.parse(sessionStorage.getItem('savedCartItems')); // let parseItem; // let itemsQty = savedItems.length; // //let response = false; // savedItems.forEach(element => { // parseItem = JSON.parse(element); // addSavedCartItems(parseItem.idProduct, parseItem.quantity, itemsQty); // }); // //CCRZ.pubSub.trigger('cartChange', CCRZ.cartView.cartmodel.attributes.sfid); // }else{ // checkCartToRemoveGiftCard(true); // sessionStorage.removeItem('giftcard'); // } // } // }); //NEW DEV LOCAL STORAGE ANDRES GARCIA CCRZ.pubSub.on('view:cartView:refresh', function(){ if((JSON.parse(localStorage.getItem('giftcard')) != null) && (CCRZ.pagevars.queryParams.pagekey != 'GiftCard') && (CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__CheckoutNew') && CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__OrderConfirmation'){ if(JSON.parse(localStorage.getItem('savedCartItems')) != null){ checkCartToRemoveGiftCard(false); localStorage.removeItem('giftcard'); let savedItems = JSON.parse(localStorage.getItem('savedCartItems')); let parseItem; let itemsQty = savedItems.length; //let response = false; savedItems.forEach(element => { parseItem = JSON.parse(element); addSavedCartItems(parseItem.idProduct, parseItem.quantity, itemsQty); }); //CCRZ.pubSub.trigger('cartChange', CCRZ.cartView.cartmodel.attributes.sfid); }else{ checkCartToRemoveGiftCard(true); localStorage.removeItem('giftcard'); } } // valida el contexto de PG Promocionales //validatePgPromoContext(); }); // CCRZ.pubSub.on('view:CartDetailView:refresh',function(){ // validatePgPromoContext(); // }); function checkCartToRemoveGiftCard(cartChangeFlag){ const ccFlag = cartChangeFlag; if(processCount == 0){ let gcSKU = CCRZ.getPageConfig('GC.gcsku', 'GCSKU'); //let gcSessionStorage = JSON.parse(sessionStorage.getItem('giftcard')); if(CCRZ.cartView.cartmodel.attributes.cartItems != undefined){ if(CCRZ.cartView.cartmodel.attributes.cartItems[0].mockProduct.sku.includes(gcSKU)){ removeGCFromCart(CCRZ.cartView.cartmodel.attributes.sfid, ccFlag); } } processCount++; } } function removeGCFromCart(cartSfid,cartChangeFlag) { const ccFlag = cartChangeFlag; let processCount = 0; let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); remoteCall.invokeCtx('removeItemsFromCart',cartSfid,(res,err)=>{ if(res.success && ccFlag){ CCRZ.pubSub.trigger('cartChange', CCRZ.cartView.cartmodel.attributes.encryptedId); } },{nmsp: false, escape: false, buffer: false} ); } //NEW DEV SAVE CART ITEMS GIFTCARD // function getCartItems(cartSfid) { // //let processCount = 0; // let items; // let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); // remoteCall.invokeCtx('getCartItems',cartSfid,(res,err)=>{ // if(res.success){ // items = JSON.stringify(res.data.cartItems); // sessionStorage.setItem('savedCartItems',items); // } // },{nmsp: false, escape: false, buffer: false} // ); // } //NEW DEV SAVE CART ITEMS GIFTCARD // function addSavedCartItems(idProd, qty, itemsQty){ // let remoteCall = _.extend(CCRZ.RemoteInvocation, { className: 'ccrz.cc_RemoteActionController' }); // remoteCall.invokeContainerLoadingCtx($('.deskLayout'), 'addItem', idProd, qty, null, null, "", null, function (res, err) { // if (res.success) { // console.log('Se logro introducir items al carrito desde el session storage'); // addItemSuccessCount++; // if(addItemSuccessCount == itemsQty){ // CCRZ.pubSub.trigger('cartChange', res.data); // } // } // }, // { nmsp: false }); // } // PUNTOS GRODOS PROMOCIONALES ---------------- // isPromo: true or false function setLocalIsCartPgPromoContext(isPromo){ isPromo ? localStorage.setItem('isPgPromoContext', 'true') : localStorage.removeItem('isPgPromo'); } // function validatePgPromoContext(){ // if((localStorage.getItem('isPgPromoContext') == 'true') && (CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__CheckoutNew') && CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__OrderConfirmation'){ // const cartID = CCRZ.cartView != undefined ? CCRZ.cartView.cartmodel.attributes.sfid : CCRZ.cartDetailView.model.attributes.sfid; // const cartEncId = CCRZ.pagevars.currentCartID; // let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); // remoteCall.invokeCtx('removePGCartItems',cartID, true, function(response, event) { // if(response.success){ // localStorage.removeItem('isPgPromoContext'); // remoteCall.invokeCtx('removeFlagIsPgPromo',cartEncID, function(response, event) { // if(response.success){ // console.log('AJX :: removeFlagIsPgPromo ==> ', response); // //Refresco la pagina si estoy en el cart Detail // if(CCRZ.pagevars.remoteContext.currentPageName == 'ccrz__Cart'){ // location.reload(); // } // } // }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); // CCRZ.pubSub.trigger('cartChange', CCRZ.cartView.cartmodel.attributes.encryptedId); // } // }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); // } // } // function checkCartToRemoveGiftCard(cartChangeFlag){ // const ccFlag = cartChangeFlag; // if(processCount == 0){ // let gcSKU = CCRZ.getPageConfig('GC.gcsku', 'GCSKU'); // //let gcSessionStorage = JSON.parse(sessionStorage.getItem('giftcard')); // if(CCRZ.cartView.cartmodel.attributes.cartItems != undefined){ // if(CCRZ.cartView.cartmodel.attributes.cartItems[0].mockProduct.sku.includes(gcSKU)){ // removeGCFromCart(CCRZ.cartView.cartmodel.attributes.sfid, ccFlag); // } // } // processCount++; // } // } function getAccountGroupInfo(){ return new Promise((resolve, reject) => { const remoteCall = _.extend(CCRZ.RemoteInvocation, { className: 'AddToCartRemoteValidator' }); remoteCall.invokeContainerLoadingCtx($('.deskLayout'), 'getAccountGroupInfo', CCRZ.currentUser.Contact.AccountId, function (res, err) { if(res.success){ resolve(res.data.ccrz__E_AccountGroup__r); }else{ reject(res); } },{ nmsp: false, escape: false, timeout: 10000, buffer: false } ); }); } //Ejemplo de llamado a función con promesa // async function callAccountGroupInfo(){ // let response = await getAccountGroupInfo(); // return response; // } // AJX. Parche para HS. Solo mobile, detecta cuando ya ha cargado HS sus productos y ajusta su div de filtros function isMobile() { const mobileQuery = window.matchMedia("(max-width: 767px)"); return mobileQuery.matches; } CCRZ.pubSub.on('chargeFooter', function(param){ setTimeout(() => { if ($("#viewState").val() == "ListView") { if (isMobile()) { try{ if(CCRZ.pagevars.storefrontName == 'B2CCochez'){ $('.hawk-railNavHeading').addClass('ml-4 mt-5').insertBefore($('.cc_tmpl_TwoColRightRD')); } else if(CCRZ.pagevars.storefrontName == 'B2CNovey'){ $('.hawk-railNavHeading').insertBefore($('.cc_tmpl_TwoColRightRD')); $('.hawk-railNavHeading').addClass('ml-4 mt-5 mb-5'); } }catch(ex){console.log(ex);} } } }, 2000); });
'; } } return wrapper; }); // INSERTA ROW SEGUN PARAMETROS ESTABLECIDOS EN LA FUNCION Handlebars.registerHelper('gridWrapCustom', function(index, isLast, isOpenning, customCol, clases) { var wrapper = "", perRow = customCol, clases = (clases == undefined) ? '' : clases; if (isOpenning) { if (index == 0 || index % perRow == 0) { wrapper += '
Address: 569 Waelchi Ports, South Blainebury, LA 11589
Phone: +9958996486049
Job: Sales Manager
Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing
Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.
We notice you're using an ad blocker
Without advertising income, we can't keep making this site awesome for you.