var $ = jQuery.noConflict(); $(document).ready(function () { jQuery.fn.shake = function(interval,distance,times){ interval = typeof interval == "undefined" ? 70 : interval; distance = typeof distance == "undefined" ? 10 : distance; times = typeof times == "undefined" ? 4 : times; var jTarget = $(this); jTarget.css('position','relative'); for(var iter=0;iter<(times+1);iter++){ jTarget.animate({ left: ((iter%2==0 ? distance : distance*-1))}, interval); } return jTarget.animate({ left: 0},interval); } keyPressCPenvio(); removeItemCart(); viewCupon(); agregarProductosCarrito(); agregarReleatedCarrito(); changeComboCantidadCarrito(); changeInputCantidadCarrito(); starCart(); $(document).on('click', 'html', function (event) { if (banderaCant){ changeInputCantidadProduct($('#' + bandIdCant)); bandIdCant = ""; banderaCant = false; } }); $(document).on('click', '.customCant', function (e) { e.stopPropagation(); }); loadIMGReco(); /*if($('.rating-stars-prods.featured').length){ initBarRatingFeatured(); }*/ }); function starCart(){ $('.bubble').html(''); var valorCP = localStorage.getItem("CP-envio"); $.ajax({ type: "POST", url: "/shoppingcart/get_cp_shoppingcart", data: { zip_code: valorCP, shopping_cart_inicial : "yes" }, dataType: "json", success: function (request) { var data = request.data; var n_tflon = 0; var n_prod = 0; if(request.cart){ $.each(request.cart.products, function (key, value) { if(value.tflon == "yes"){ if(value.active_tflon == "yes"){ n_tflon+= value.quantity; } }else{ n_prod+= value.quantity;; } }); $('.bubble').html((n_tflon+n_prod)); }else{ $('.bubble').html(0); } $('.bubble').addClass("active"); }, error: function () { // sendNoty("error", "Error"); console.log("Error al consultar el carrito startCart"); } }); } var flagColchones = false; var cuponesMonto = []; var findCPBy = "sessionCP"; // sessionCP = Buscar CP SessionStorage. "inputCP" = Buscar por CP input var oculta = 0; var dateShippingTemp = null; var productsSAP = []; var cpAvailable = false; var noProductos = 0; var noProductosTflon = 0; var totalProductos = 0; var totalTeflon = 0; var productoMasCaro = {'code':'', 'name':'', 'price':0}; var banderaBannerTeflon = false; // var typeCart = true; $(".clicTeflonCart").on("click", function() { $('').appendTo('.carrito').addClass('in').click(function() { cerrarPoptFlon(); }); setTimeout(function () { $('.pop-teflon').show(); }, 300); }); $('#closePopTeflon').click(function() { cerrarPoptFlon();}); $(".fa-info-circle").on("click", function() { $('').appendTo('.carrito').addClass('in').click(function() { cerrarPoptFlon(); }); setTimeout(function () { $('.pop-entrega').show(); }, 300); }); $('#closePopEntrega').click(function() { cerrarPoptFlon();}); $(".garanita-carrito").on("click", function() { $('').appendTo('.carrito').addClass('in').click(function() { cerrarPoptFlon(); }); setTimeout(function () { $('.pop-garantia').show(); }, 300); }); $('#closePopGarantia').click(function() { cerrarPoptFlon();}); function cerrarPoptFlon(){ $('.pop-teflon').hide(); $('.pop-entrega').hide(); $('.pop-garantia').hide(); $('#modalCart').remove(); } // Abre Menú mi carrito, Web desde el Header $("#cartMenu").on("click", function() { loadCartON(); $('#itemsCart').html(""); $("#listProductsRelated").html(''); openModal_MiCarrito(); buscarCarrito(); }); // Abre Menú mi carrito, Movil desde el Header $("#cartMenuMovil").on("click", function() { loadCartON(); $('#itemsCart').html(""); $("#listProductsRelated").html(''); openModal_MiCarrito(); buscarCarrito(); }); // Función Abre Menú mi carrito function openModal_MiCarrito(){ calcHeight(); var ancho = document.documentElement.clientWidth; if(ancho<=800){ $('.carrito').show(); $('.carrito').css('width', '100%'); $('.carrito').animate({left: '0%'}, "slow"); }else if(ancho<1200){ $('.carrito').show(); $('.carrito').css('width', '80%'); $('.carrito').animate({left: '20%'}, "slow"); $('').appendTo('body').addClass('in').click(function() { cerrarModal_MiCarrito(); }); }else{ $('.carrito').show(); $('.carrito').css('width', '55%'); $('.carrito').animate({left: '45%'}, "slow"); $('').appendTo('body').addClass('in').click(function() { cerrarModal_MiCarrito(); }); } setTimeout(function () { $('body').css({'overflow-y':"hidden"}); $('.informacion').css('height', '100vh'); }, 300); } // Cierra Menú mi carrito desde boton X $('#closeCart').click(function() { cerrarModal_MiCarrito(); }); // Función Cerrar menú Mi carrito function cerrarModal_MiCarrito(){ // console.log("Cierra modal desde header.js"); $('#btnIr').hide(); $('.carrito').animate({left: '100%'}, "slow"); $('.modal-backdrop').remove(); cerrarPoptFlon(); $('body').css({'overflow-y':"scroll"}); setTimeout(function () { $('menu-shop-container').hide(); }, 450); $("#CPenvio").val(""); $("#codPosEnv").removeClass("alerta"); banderaCant = false; bandIdCant = ""; $("#numCupon").val(""); $('#addcupon').css({ 'display': 'none' }); $('#cuponesDesc').css({ 'display': 'revert' }); } $(document).on('click', ".delCupon", function (e) { idCoupon = $(this).attr("idcoupon"); sendCoupon(false, idCoupon); }); $(document).on('click', "#applyCoupon", function (e) { if ($('#user_ambasador').is(':visible')) { let valor = $("#numCupon").val().toUpperCase(); let valor_final = valor.slice(0,5); if (valor_final === "01EMB" || valor_final === "01emb" ){ $(this).parent().shake(); sendNoty("error","No puedes usar este cupón si eres embajador."); return false; } } if(checkCuponPromo($('#numCupon').val())){ $(this).parent().shake(); sendNoty("error","No puedes usar este cupón."); return false; } sendCoupon($('#numCupon').val(), null); }); $(document).on('keypress', "#numCupon", function (e) { if(e.which === 13){ if ($('#user_ambasador').is(':visible')) { let valor = $("#numCupon").val().toUpperCase(); let valor_final = valor.slice(0,5); if (valor_final === "01EMB" || valor_final === "01emb" ){ $(this).parent().shake(); sendNoty("error","No puedes usar este cupón si eres embajador."); return false; } } if(checkCuponPromo($('#numCupon').val())){ $(this).parent().shake(); sendNoty("error","No puedes usar este cupón."); return false; } sendCoupon($('#numCupon').val(), null); } }); $(document).on('click', "#btnStarShopping", function (e) { starShopping(); }); $(document).on('click', '#CPenvio', function (e) { $("#codPosEnv").removeClass("alerta"); }); $(document).on('click', '#txtEnvio', function (e) { $("#codPosEnv").removeClass("alerta"); }); function keyPressCPenvio() { $("#CPenvio").keypress(function (e) { // console.log("Busca el Codigo postal sendCP()"); var idDivs = { zip_code: 'CPenvio' }; var code = (e.keyCode ? e.keyCode : e.which); if (e.which == 13) { if (validateCP(idDivs)) { // buscarCarrito(); //buscarCarrito_InputCP(); $("#CPenvio").blur(); } } }); } $("table.cart-table .cantidades input").focusin(function () { $(this).css({ 'background-image': 'none' }); }); $("table.cart-table .cantidades input").css({ 'background-image': 'url(/images/products/icon-arrow.svg)' }); // Función para input cantidad function maxLengthCant(object) { if (object.value.length > 3) object.value = object.value.slice(0, 3) } // Funcón que remueve un producto del carrito function removeItemCart() { $(document).on('click', '.delItemCart', function (event) { loadCartON(); $('#itemsCart').html(''); $("#listProductsRelated").html(''); var _this = $(this); var itemId = $(this).attr("id"); // id Producto valorCP = getCP(); $.ajax({ type: "POST", url: "/shoppingcart/update_shoppingcart", data: { type: "delete", zip_code: valorCP, id_product: itemId, quantity: "", delivery_type: "cedis", validate_sap: "no" }, dataType: "json", success: function (request) { // console.log("Respuesta Eliminar del controller"); // console.log(request); var data = request.data; if (request.data.products == undefined) { /*document.location.href = getCookie('currentview');*/ // _etmc.push(["setOrgId", "526003570"]); // _etmc.push(["setUserInfo", {"email": emailClientSalesforce}]); // _etmc.push(["trackCart", { "clear_cart": true } ]); $('.bubble').removeClass("active"); $('.bubble').html(0); $('.bubble').addClass("active"); iniciarTotales(); cerrarModal_MiCarrito(); $('#loaderCarrito').hide(); } else { sendGtag(extractGtagData(_this)); buscarCarrito(); } }, error: function () { $('#loaderCarrito').hide(); sendNoty("error", "Error al eliminar producto"); } }); }); } // click texto del CP $("#txtEnvio").click(function (e) { // console.log("ChangeCP ---> autosend: "+ findCPBy); findCPBy = "inputCP"; $('#ShippCalcSend label').text("Nuevo C.P."); $('#CPenvio').val(""); $('#ShippCalcSend').show(); $("#CPenvio").focus(); }); // Función que busca la informacion del carrito cuando se da click al icono Mi Carrito function buscarCarrito(){ var valorCP = localStorage.getItem("CP-envio"); $("#codPosEnv").removeClass("alerta"); $(".arrow-blue").remove(); $.ajax({ type: "POST", url: "/shoppingcart/get_cp_shoppingcart", data: { zip_code: valorCP, }, dataType: "json", success: function (request) { $('#bnrCart').hide(); if(request.cart == null){ iniciarTotales(); offRecomendados(); $("#itemsCart").show(); $('#loaderCarrito').hide(); $('#btnIr').hide(); $('#itemsCart').html('
carrito vacioEl carrito está vacío
'); return; } var data = request.data; addCouponAmount(request.cart); if (valorCP == "" || valorCP == null || valorCP == undefined) { // console.log("El codigo Postal esta vacio: "+ valorCP); $('#txtEnvio').text("Calcula costo de envío y ¿Cuándo me llega?"); // $('#ShippCalcSend').removeClass("hidden"); $('#ShippCalcSend').show(); findCPBy = "inputCP"; oculta = 0; } else { // console.log("Codigo Postal del: "+ valorCP); // $('#ShippCalcSend').addClass("hidden"); $('#ShippCalcSend').hide(); // console.log("data.ZipCode.status: "+data.ZipCode.status); localStorage.setItem('CP-envio', valorCP); localStorage.setItem('CP-zone', data.ZipCode.zone_id); if (data.ZipCode.status === "yes") { // console.log("Codigo Postal Valido"); cpAvailable = true; $("#txtMsg").hide(); } else{ // console.log("Codigo Postal No Valido"); $('#codPosEnv').addClass("alerta"); $('#CPenvio').parent().parent().parent().shake(); //irA("regresoCP"); cpAvailable = false; $("#txtMsg").show(); $("#txtMsg").text(data.ZipCode.mensaje); // $("#ShippCalcSend").removeClass("hidden"); $('#ShippCalcSend').show(); valorCP = getCP(); $("#CPenvio").val(valorCP); // $("#CPenvio").focus(); Se queda en el Input y vuelve a buscar el carrito } findCPBy = "inputCP"; oculta = 1; tempMsg = ""; if (data.ZipCode.d_ciudad === "" || data.ZipCode.d_ciudad === "" || data.ZipCode.d_ciudad === undefined || data.ZipCode.d_ciudad === null) { if (data.ZipCode.estado === null) { tempMsg = "C.P.: " + valorCP; } else { tempMsg = "C.P.: " + valorCP + " - " + data.ZipCode.estado; } } else { tempMsg = "C.P.: " + valorCP + " - " + data.ZipCode.d_ciudad + ", " + data.ZipCode.estado; } var msjCP = data.ZipCode.mensaje; if(data.ZipCode.mensaje == "No disponible en tu ciudad"){ msjCP = "Hay productos en tu carrito que no están disponibles en tu ciudad"; } // console.log("Agrega el mensaje al txtEnvio: "+ tempMsg); $('#txtEnvio').addClass("azul"); $("#txtEnvio").after("cambiar"); $(".arrow-blue").css({ 'width': '20px' }); $('#txtEnvio').text(tempMsg); $("#txtMsg").text(msjCP); } addProduct_MiCarrito(request.cart,valorCP); validCurrentCupon(request.cart.subtotal); }, error: function (req) { console.log("Error al consultar el carrito"); console.log(req); sendNoty("error", "Error"); } }); } // Función que busca la informacion del carrito cuando cambia el input CP function buscarCarrito_InputCP(){ // console.log("Entra Metodo buscarCarrito_InputCP()"); var valorCP = $("#CPenvio").val(); $("#codPosEnv").removeClass("alerta"); $(".arrow-blue").remove(); calcHeight(); $.ajax({ type: "POST", url: "/shoppingcart/get_cp_shoppingcart", data: { zip_code: valorCP, }, dataType: "json", beforeSend: function (e) { findCPBy = "inputCP"; loadCartON(); $('#itemsCart').html(""); $("#listProductsRelated").html(''); }, success: function (request) { // console.log('Respuesta API'); // console.log(request); var data = request.data; addCouponAmount(request.cart); $('#codPosEnv').show(); $('#ShippCalcSend').hide(); cartDown(); localStorage.setItem('CP-envio', valorCP); localStorage.setItem('CP-zone', data.ZipCode.zone_id); // console.log("data.ZipCode.status: "+data.ZipCode.status); if (data.ZipCode.status === "yes") { cpAvailable = true; $("#codPosEnv").removeClass("alerta"); $("#txtMsg").hide(); } else{ $('#codPosEnv').addClass("alerta"); //$('#CPenvio').parent().parent().parent().shake(); //irA("regresoCP"); cpAvailable = false; $("#txtMsg").text(data.ZipCode.mensaje); $("#txtMsg").show(); $('#ShippCalcSend').show(); valorCP = getCP(); $("#CPenvio").val(valorCP); $('#codPosEnv').shake(); } oculta = 1; tempMsg = ""; if (data.ZipCode.d_ciudad === "" || data.ZipCode.d_ciudad === "" || data.ZipCode.d_ciudad === undefined || data.ZipCode.d_ciudad === null) { if (data.ZipCode.estado === null) { tempMsg = "C.P.: " + valorCP; } else { tempMsg = "C.P.: " + valorCP + " - " + data.ZipCode.estado; } } else { tempMsg = "C.P.: " + valorCP + " - " + data.ZipCode.d_ciudad + ", " + data.ZipCode.estado; } var msjCP = data.ZipCode.mensaje; if(data.ZipCode.mensaje == "No disponible en tu ciudad"){ msjCP = "Hay productos en tu carrito que no están disponibles en tu ciudad"; } $('#txtEnvio').addClass("azul"); $("#txtEnvio").after("cambiar"); $(".arrow-blue").css({ 'width': '20px' }); $('#txtEnvio').text(tempMsg); $("#txtMsg").text(msjCP); // } if(request.cart == null){ // $('#loaderCarrito').hide(); $("#itemsCart").show(); iniciarTotales(); $('#itemsCart').html('El carrito está vacío'); $('#btnIr').html(''); return; } addProduct_MiCarrito(request.cart,valorCP); }, error: function (req) { console.log("Error al consultar el carrito"); console.log(req); sendNoty("error", "Error"); } }); } function getCP() { var tempStorageCP = localStorage.getItem("CP-envio"); var tempInputCP = $("#CPenvio").val(); if (tempStorageCP === null && tempInputCP === "") { // console.log("regresa Vacio"); return ""; } if (tempInputCP !== "") { // console.log("regresa CP del Input"); return tempInputCP; } if (tempStorageCP !== "") { return tempStorageCP; } } // Función que Busca el carrito actual cuando se ejecuta el evento onblur del input CP function autoSearchCP() { var valorCP = $("#CPenvio").val(); if (valorCP != "" & findCPBy === "inputCP") { var idDivs = { zip_code: 'CPenvio' }; if (validateCP(idDivs)) { // findCP(valorCP); // buscarCarrito(); buscarCarrito_InputCP(); } } else if (oculta === 1) { $('#ShippCalcSend').hide(); $('.cp').removeClass("has-error"); $(".help-block").text("").hide(); } } // Función que valida el Texto del Input código postal function validateCP(values) { var promise = true; $.each(values, function (index, value) { $('#' + value).val($('#' + value).val().trim()); // clean validation $('#' + value).keydown(function () { $('#' + value).removeClass("error"); $('#' + value).parent().removeClass('has-error'); $('#' + value).parent().children("span").text("").hide(); }); // end clean validation if (index == 'zip_code') { // console.log("validate") if ($('#' + value).val().length < 5) { $('#' + value).addClass("error"); $('#' + value).parent().addClass("has-error"); $('#' + value).parent().children("span").text("C.P. inválido").show(); $('#' + value).parent().shake(); promise = false; } } }); return promise; } // Función que actualiza el carrito (Cantidad) function updateShoppingcart(idProduct, q, type, sku, price) { // console.log("updateShoppingcart Id del producto: " +idProduct ); // console.log("updateShoppingcart Cantidad: " +q ); // console.log("updateShoppingcart Type: " +type ); var apply_tflon = "no"; var typeVentaTodoMexico = "no"; if(type == "addRelated"){ apply_tflon = "no"; type = "add"; typeVentaTodoMexico = tempProductRelated.typeVentaTodoMexico; }else{ apply_tflon = ($('#check_'+idProduct.trim()).is(":checked")) == true ? "yes" : "no" ; } valorCP = getCP(); $.ajax({ type: "POST", url: "/shoppingcart/update_shoppingcart", data: { type: type, zip_code: valorCP, id_product: idProduct, quantity: q, delivery_type: "home", validate_sap: "no", tflon:apply_tflon, typeVentaTodoMexico : typeVentaTodoMexico }, dataType: "json", beforeSend: function (e) { loadCartON(); $('#itemsCart').html(""); $("#listProductsRelated").html(''); }, success: function (request) { // console.log('Respuesta update_shoppingcart'); // console.log(request); addCouponAmount(request.data); // _etmc.push(["setOrgId", "526003570"]); // _etmc.push(["setUserInfo", {"email": emailClientSalesforce}]); // _etmc.push(["trackCart", { // "cart": [{ // "item" : sku, // "quantity": q, // "price" : price, // "unique_id" : sku}] // }]); if (request.data.products == undefined) { // console.log("No regresa productos"); // unblockUI(); // document.location.href = '/' } else { buscarCarrito(); //autoSearchCP(); //addProduct_MiCarrito(request.data,valorCP); } } }); } // Función que valida el carrito y redirige al Shipping function starShopping(){ // Validamos si existe codigo postal con cobertura if(cpAvailable === false){ sendNoty('error', 'Ingrese un código postal con cobertura'); var ancho = document.documentElement.clientWidth; if(ancho<=770){ $("#contenidoCart").animate({ scrollTop: $('.shopping-cart-menu').height() - $('.recomendados-carrito').height()}, 1000); }else{ $(".shopping-cart-menu").animate({ scrollTop: 10000 }, 1000); } $('#CPenvio').parent().parent().shake(); $("#codPosEnv").addClass("alerta"); return; } valorCP = localStorage.getItem("CP-envio"); if(valorCP === "" || valorCP === null || valorCP === undefined){ sendNoty('error', 'Ingrese un código postal'); var ancho = document.documentElement.clientWidth; if(ancho<=770){ $("#contenidoCart").animate({ scrollTop: $('.shopping-cart-menu').height() - $('.recomendados-carrito').height()}, 1000); }else{ $(".shopping-cart-menu").animate({ scrollTop: 10000 }, 1000); } $("#CPenvio").focus(); $('#CPenvio').parent().parent().shake(); $("#codPosEnv").addClass("alerta"); return; } if(cuponenceros != ""){ sendNoty("error","Existe un cupón en 0, verifica el monto de tu compra."); return; } $.ajax({ type: "POST", url: "/shoppingcart/get_cp_shoppingcart", data: { zip_code: valorCP, }, dataType: "json", beforeSend: function (e) { $('#loaderCarrito').show(); }, success: function (request) { var sinStock = 0; var typeVentaTodoMexico = "no"; // console.log('-> id Zona venta todo mexico: '+ id_zona_venta_todo_mexico); // if(request.data.ZipCode.zone_id == id_zona_venta_todo_mexico){ // typeVentaTodoMexico = "yes"; // } $.each(request.cart.products, function (key, value) { //console.log("Producto -> : "+ key+" - "+ value.tflon); //console.log(value); // if(value.tflon == undefined){ // filtra los productos tflon // if(typeVentaTodoMexico == "yes"){ // if(value.venta_todo_mexico == "no" || value.venta_todo_mexico == null){ // typeVentaTodoMexico = "no"; // } // } // } // console.log("Producto: "+value.name+ " - "+ value.validate.status); if(value.validate.status == "no"){ if(!value.tflon){ // console.log("---> Producto Sin disponibilidad : "+value.name); sinStock++; } // console.log("Producto: sin stock: "+ value.code); } }); if(request.cart.coupon){ var has_coupon = request.cart.coupon.coupon_id.includes(COUPON_PROMO_1.id); if(has_coupon){ setCookie("promoCoupon1","yes",1);} else{ setCookie("promoCoupon1","no",1); } }else{ setCookie("promoCoupon1","no",1); } if(sinStock > 0){ // unblockUI(); $('#loaderCarrito').hide(); sendNoty('error', 'Tienes productos sin disponibilidad en el carrito'); irA("tableProducts"); return; }else{ setCookie("typeVentaTodoMexico",typeVentaTodoMexico,1); setCookie("CP-envio",valorCP,1); setCookie("CP-zone",request.data.ZipCode.zone_id,1); // document.location.href = '/checkout/login'; $('#loaderCarrito').hide(); document.location.href = '/checkout/shipping'; cerrarModal_MiCarrito(); } }}); } function sendCoupon(inputCoupon, indice) { valorCP = getCP(); $.ajax({ type: 'PUT', url: '/shoppingcart/set_coupon', data: { code: inputCoupon, indice: indice, user: true, zip_code : valorCP, delivery_type: "home" }, dataType: 'json', beforeSend: function(e){ $("#applyCoupon").hide(); $('#SpinnerCoupon').show(); }, success: function (response) { $('#SpinnerCoupon').hide(); $("#applyCoupon").show(); if (response.data) { switch (response.data) { case 'expired': sendNoty('error', 'El cupón que ingresaste ya expiró.'); $('#numCupon').shake(); break; case 'invalid_coupon': sendNoty('error', 'Verifica el cupón ingresados.'); $('#numCupon').shake(); break; case 'client_first_purchase': sendNoty('error', 'Este cupón es válido sólo en la primera compra.'); $('#numCupon').shake(); break; case 'coupon_doesnt_mach': sendNoty('error', 'El cupón que ingresaste es válido sólo en envíos a domicilio.'); $('#numCupon').shake(); break; case 'invalid_chairs': sendNoty('error', 'El cupón que ingresaste es válido sólo en la compra de 6 o más sillas.'); $('#numCupon').shake(); break; case 'invalid_rug': sendNoty('error', 'El cupón que ingresaste es válido sólo en la compra de 1 o más tapetes.'); $('#numCupon').shake(); break; case 'used_coupon': sendNoty('error', 'El cupón que ingresaste ya fue usado'); $('#numCupon').shake(); break; case 'invalid_coupon_automatic': sendNoty('error', 'El cupón que ingresaste no es válido'); $('#numCupon').shake(); break; case 'invalid_session': sendNoty('error', 'Para aplicar cupón inicia sesión'); $('#numCupon').shake(); break; case 'code_store_or_presale_exist': sendNoty('error', 'Ups, recuerda que tu código de '+inputCoupon.toUpperCase()+' va primero. Remueve el código que ingresaste y vuelve a empezar.'); $('#numCupon').shake(); break; case 'store_code_exist': sendNoty('error', 'El cupón que ingresaste no aplica con el código de TIENDA.'); $('#numCupon').shake(); break; case 'presale_code_exist': sendNoty('error', 'El cupón que ingresaste no aplica con el código de PREVENTA.'); $('#numCupon').shake(); break; case 'coupon_used_in_period': sendNoty('error', 'El cupón ya fue utilizado.'); $('#numCupon').shake(); break; case 'invalid_reference': sendNoty('error', 'El cupón que ingresaste no aplica con el usuario.'); $('#numCupon').shake(); break; case 'coupon_dont_valid_www': sendNoty('error', 'El cupón que ingresaste no aplica para ventas en línea.'); $('#numCupon').shake(); break; case 'coupon_no_combinable_exist': sendNoty('error', 'El cupón ingresado no aplica para esta compra.'); $('#numCupon').shake(); break; case 'coupon_no_combinable': sendNoty('error', 'El cupón que ingresaste no es Combinable.'); $('#numCupon').shake(); break; default: if(!inputCoupon){ addCouponAmount(response.cart); sendNoty('success', 'El cupon ha sido eliminado'); showMessageCoupon(); }else{ // console.log("Entra:.. "); addCouponAmount(response.cart); $('#addcupon').css({ 'display': 'none' }); $('#cuponesDesc').css({ 'display': 'revert' }); $("#numCupon").val(""); sendNoty('success', 'El cupón ha sido agregado'); } // updatetablePrices(response.cart); // newTableData(response.cart,valorCP); addProduct_MiCarrito(response.cart,valorCP); break; } } else { sendNoty('error', 'Ocurrió un error al aplicar el cupón, por favor, inténtelo nuevamente.'); } // unblockUI(); }, error: function () { // unblockUI(); } }); } // Función que Ordena un array function sortJson(data, key, orden){ return data.sort(function(a,b){ var x = a[key], y = b[key]; if(orden==="asc"){ return ((xy)?1:0)); } if(orden==="desc"){ return ((x>y)?-1:((x').appendTo('body').addClass('in').click(function() { cerrarModal(); }); $('.informacion .infteflon').css('display', "block"); if(ancho<=770){ $('.informacion').css('width', '100%'); $('.informacion').animate({left: '0%'}, "slow"); }else{ $('.informacion').css('width', '35%'); $('.informacion').animate({left: '65%'}, "slow"); } setTimeout(function () { $('body').css('overflow-y', "hidden"); $('.informacion').css('height', '100vh'); }, 300); }); $('#closeInfo').click(function() { $('.informacion').animate({left: '100%'}, "slow"); $('.modal-backdrop').remove(); $('body').css('overflow-y', "auto"); setTimeout(function () { $('.informacion').css('display', 'none'); $('.informacion').css('height', '100%'); $('.informacion .infteflon').css('display', "none"); }, 450); }); function cerrarModal(){ $('#closeInfo').click(); } $(document).on('click', '.checkTflon', function (e) { var typeTflon = $(this).val(); var itemId = null; // id Producto var aplica_Tflon = "no"; var valorCP = getCP(); // console.log("check esta: "+ $(this).is(":checked")); switch (typeTflon) { case "allTflon": aplica_Tflon = ($(this).is(":checked")) == true ? "yes" : "no" ; break; case "oneTflon": var parts = $(this).attr('id').split('_'); itemId = parts[1]; aplica_Tflon = ($(this).is(":checked")) == true ? "yes" : "no" ; break; } // console.log("Tipo Teflon: "+ typeTflon); // console.log("Id producto: "+itemId); // console.log("Aplica teflon: "+aplica_Tflon); $.ajax({ type: "POST", url: "/shoppingcart/update_shoppingcart", data: { type: typeTflon, zip_code: valorCP, id_product: itemId, quantity: "", delivery_type: "cedis", validate_sap: "no", tflon: aplica_Tflon }, dataType: "json", beforeSend:function(e){ loadCartON(); $('#itemsCart').html(""); $("#listProductsRelated").html(''); }, success: function (request) { var data = request.data; if (request.data.products != undefined) { addCouponAmount(request.data); addProduct_MiCarrito(request.data,valorCP); } else { loadCartOFF(); console.log("El update no regreso datos"); } }, error: function () { // unblockUI(); //$('#loaderCarrito').hide(); loadCartOFF(); sendNoty("error", "Error al agregar Tflon al producto"); } }); }); function allTeflonChecked(){ var resp = true; $(".checkTflon").each(function(){ if($(this).val()=="oneTflon"){ // console.log(".checkTflon: "+ $(this).attr("id")); if($(this).is(":checked") == false){ resp = false; } } }); if(resp){ $("#switch_all").prop("checked",true); }else{ $("#switch_all").removeAttr("checked"); } } function iniciarTotales(){ noProductos = 0; noProductosTflon = 0; totalProductos = 0; totalTeflon = 0; $("#tr_Tflon").hide(); $('#itemsCart').html(""); $("#td_totalProd").html("Productos(" + noProductos + ")"); $("#td_textTflon").html("t-Flon(" + noProductosTflon + ")"); $("#td_subtotal").html(setFormatMoney(totalProductos)); $("#td_totalTflon").html(setFormatMoney(totalTeflon)); $("#td_shipping").html(setFormatMoney(0)); $(".trAddCoupones").remove(); $("#total").html(setFormatMoney(0)); $('#itemsCartTotal').html(setFormatMoney(0)); $('.bubble').html(0); } var cuponenceros = ""; function addProduct_MiCarrito(data,zipCode){ flagColchones = false; var tempDateShipping = null; var products = data.products; // Productos del carrito desordenandos var productsGroup = null; // Array promo colchones var productos2 = []; // Array productos carrito ordenados var mensaje = ""; var mensajeShipping = ""; var noAllProducts = 0; // Numero Total de productos var noProductosActivos = 0; // Suma de productos normales mas productos tflon activos var items = ''; // Contenedor codigo HTML var totalCupones = 0; // Monto Total de cupones var totalCuponesAuto = 0 var totalCuponesManual = 0 var montoTotalCarrito = 0; // Monto total de carrito banderaBannerTeflon = false; cuponenceros = ""; noProductos = 0; // No de productos normales noProductosTflon = 0; // No de productos Tflon totalProductos = 0; // Monto Total de productos normales totalTeflon = 0; // Monto Total productos tflon activos productoMasCaro = {'code':'', 'name':'', 'price':0}; // typeCart = true; if(data.Group){ // console.log("Entra if true - es un json"); // console.log(data.Group.descuento) if(data.Group.descuento == undefined || data.Group.descuento > 0 ){ // console.log("Oculta el mensaje"); //$('#bnrCart').hide(); //$("#bnrCart").html(""); }else{ console.log("Entra a mostrar el mensaje"); flagColchones = true; //$('#bnrCart').show(); //$("#bnrCart").html("
¡RECUERDA! si agregas un colchón a tu carrito, obtendrás el 20% de DESCUENTO en el colchón.
¡No dejes pasar esta oportunidad!
ir a colchones
"); } productsGroup = data.Group.productos_aplica; } for (const key in products) { productos2.push(products[key]); } sortJson(productos2,"order_table","asc"); $.each(productos2, function (key, value) { // console.log('valor = '+value); // console.log("Producto: "+ value.venta_todo_mexico); // if(value.venta_todo_mexico !== "yes"){ // typeCart = false; // } console.log(value); if(value.price >= productoMasCaro['price']){ productoMasCaro['price'] = value.price; productoMasCaro['code'] = value.code; productoMasCaro['name'] = value.name; } noAllProducts++; mensaje = ""; clase = ""; idProducto = value.product_id; if(value.tflon == "yes"){ banderaBannerTeflon = true; if(value.active_tflon == "yes"){ // noProductosTflon++; totalTeflon += value.subtotal; noProductosTflon+= value.quantity; } }else{ // noProductos++; totalProductos += value.subtotal; noProductos+= value.quantity; } msgCouponGroup = ""; msgCouponGroupMovil = ""; if(productsGroup!= null){ quantityGroup = getQuantityGroup(productsGroup,idProducto); for (const i in productsGroup) { if(productsGroup[i].id == idProducto){ //msgCouponGroup = "
-"+setFormatMoney(productsGroup[i].discount *quantityGroup)+"
"+ "
Desc. 20%
"; //msgCouponGroupMovil = "
-"+setFormatMoney(productsGroup[i].discount *quantityGroup)+"
"; //msgCouponGroupMovil = '-'+setFormatMoney(productsGroup[i].discount *quantityGroup)+' (Desc. '+productsGroup[i].discount_percentage+'%)'; } } } if(value.tflon == "yes"){ mensaje = ""; clase = ""; mensajeShipping = mensaje; }else{ if (zipCode === "" || zipCode === null || zipCode === undefined) { mensaje = "Envío: A calcular"; } else { if(value.validate!= undefined){ if (value.validate.status === 'yes') { if(value.validate.fecha_entrega == null){ mensaje = "Envío: "+ value.validate.mensaje; clase = "alerta"; mensajeShipping = value.validate.mensaje; }else{ mensaje = "Envío: "+setdate(value.validate.fecha_entrega); var parts = value.validate.fecha_entrega; // var parts = "2021-1-31"; parts = parts.split('-'); var myDate = new Date(parts[0],parts[1]-1,parts[2]); // console.log("Fecha del objeto: "+ value.validate.fecha_entrega); shippingDate(new Date(myDate)); // console.log("Fecha tipo Date: "+ new Date(myDate)); } } else { switch (value.validate.status_type) { case "stock": mensaje = "Envío: "+"No hay suficientes piezas"; clase = "alerta"; mensajeShipping = mensaje; break; case "cobertura": // mensaje = "Envío: "+"Fuera de zona de envío"; if(value.venta_todo_mexico == "no"){ mensaje = "Envío: "+"No disponible en tu ciudad"; clase = "alerta"; }else{ mensaje = "Envío: "+"A calcular"; } mensajeShipping = mensaje; break; case "dates": mensaje = "Envío: "+value.validate.mensaje; clase = "alerta"; mensajeShipping = mensaje; break; case "paqueteria": mensaje = "Envío: Sin cobertura en tu ciudad"; clase = "alerta"; mensajeShipping = mensaje; break; default: mensaje = "Envío: "+"---"; mensajeShipping = mensaje; break; } } }else{ mensaje = "Envío: "+"Códgo postal no existe"; // clase = "alerta"; clase = "sincobertura"; } } } //items += '
'; items += '
'; // Imagen del producto items += '
'; var imgItemProduct = ""; if(value.image.url_thumbnail != 'https://'){ imgItemProduct = value.image.url_thumbnail; }else{ imgItemProduct = value.image.url; } var nameSLUGCart = limpiarSLUGname(value.name); if (!value.image) { items += 'default-tamarindo'; } else { if(value.tflon){ items += '' + value.name + ''; }else{ items += '' + value.name + ' | '+value.subcategory_slug+' | '+value.category_slug+''; } } items += '
'; var itemDesc = ""; if(data["2x1.5"]){ if(data["2x1.5"][idProducto]){ // console.log("Entra A - "+value.name); itemDesc += '-'+setFormatMoney(data["2x1.5"][idProducto].monto)+' (Desc. 2x1.5)'; }else{ // console.log("Entra B - "+value.name); //itemDesc += '-'+ setFormatMoney(value.subtotal) +''; itemDesc += msgCouponGroupMovil; } }else{ // console.log("Entra C - "+value.name); // itemDesc += '-'+ setFormatMoney(value.subtotal) +''; itemDesc += msgCouponGroupMovil } // Nombre , precio y promociones items += '
'; var price_item = 0; if(value.tflon){ items += '' + value.name + ''; if(value.active_tflon == "yes"){ price_item = value.subtotal; }else{ price_item = value.price * value.quantity; } }else{ items += '' + value.name + ''; price_item = value.subtotal; } items += ''; items += ''; items += ''; items += itemDesc; items += '
'; // Cuando me llega items += '
'+mensaje+'
'; // Cantidad if(value.tflon){ items += "
"; quantityProdSelect = "quantityProdSelect-" + idProducto; quantityProdCustom = "quantityProdCustom-" + idProducto; items += ''; items += "
"; // items += ''; items += ""; }else{ items += "
"; select = ""; input = "style='display:none;' disabled"; if (value.quantity > 6) { select = 'style="display:none;"'; input = 'style="display:block;"'; } quantityProdSelect = "quantityProdSelect-" + idProducto; quantityProdCustom = "quantityProdCustom-" + idProducto; // items += ""; for (let i = 1; i <= 6; i++) { selected = ''; if (i == value.quantity) { selected = 'selected'; } items += ''; } items += ''; items += ""; items += '"; items += input + " onkeypress='return validJustNumbers(event);' id='quantityProdCustom-" + idProducto + "'/>"; items += "
"; // items += ''; items += ""; } // Boton eliminar o switch Tflon if(!value.tflon){ items += " eliminar '; items += ""; }else{ is_active_tflon = ""; // console.log("Checkbox: "+ value.name + " --> "+ value.active_tflon); if(value.active_tflon == "yes"){ is_active_tflon = "checked"; } // console.log(is_active_tflon); items += ""; items += '
'; items += ""; } items += '
'; }); $(".trAddCoupones").remove(); if(data.coupon != false ){ // console.log("-------------------Agregando cupones------------------------------"); // console.log("Cupones: "+ JSON.stringify(data.coupon)); // console.log("No de cupones: "+ data.coupon.code_data.length); var objNuevo = data.coupon.code_data; var objNuevoSap = data.coupon.data; var objDesCupones = data.coupon.discount_value; var subtotal = 0; var trCuponManual = ""; var trCuponAuto = ""; var trCouponAll = ""; $.each(objNuevo, function (key, value){ var itemCuponSAP = objNuevoSap.find(cupon => cupon.id === value.coupon_id); var valDiscount = parseFloat(objDesCupones[key]); // console.log( "Key: "+ key +" value: "+ valDiscount + " - "+ value.code); if(itemCuponSAP.automatic ==='no'){ trCouponAll += "" + "" + 'eliminar' + value.code + "" + '-$' + valDiscount.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + " MXN" + "" + ""; trCuponManual += "" + "" + 'eliminar' + value.code + "" + '-$' + valDiscount.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + " MXN" + "" + ""; // if(valDiscount == 0 && value.code== "PREVENTA"){ if(valDiscount == 0){ cuponenceros = value.code; } totalCuponesManual += valDiscount; }else{ trCouponAll += "" + "" + value.code + "" + '-$' + valDiscount.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + " MXN" + "" + ""; trCuponAuto += "" + "" + value.code + "" + '-$' + valDiscount.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + " MXN" + "" + ""; totalCuponesAuto += valDiscount; } }); totalCupones = totalCuponesAuto + totalCuponesManual; // console.log("Total cupones Auto: "+ totalCuponesAuto); // console.log("Total Cupones Manuales: "+ totalCuponesManual); $("#tr_cupones").after(trCouponAll); /*$("#tr_cupones").after(trCuponManual); if(totalCuponesAuto>0){ $("#tr_cupones").after(trCuponAuto); }*/ } noProductosActivos = noProductos + noProductosTflon ; if(totalTeflon == 0){ $("#tr_Tflon").hide(); }else{ $("#tr_Tflon").show(); } $('#itemsCart').html(items); $("#td_totalProd").html("Productos(" + noProductos + ")"); $("#td_textTflon").html("t-Flon(" + noProductosTflon + ")"); $("#td_subtotal").html(setFormatMoney(totalProductos)); $("#td_totalTflon").html(setFormatMoney(totalTeflon)); $("#td_shipping").html(setFormatMoney(data.shipping)); montoTotalCarrito = totalProductos + totalTeflon + data.shipping - totalCupones; //validar leyenda de envio o servicio de entrega y MCI var Tot_Env = Math.round(montoTotalCarrito); var valueInterest = (Tot_Env*.009)*18; var Mensualidad = (Tot_Env+valueInterest)/18; if(Tot_Env >= 1800){ $(".total-MCI span b").html(setFormatMoneyMens(Mensualidad)); $(".total-MCI span").css({ display: "block"}); if(Tot_Env >= 5000){ $(".serv-entrega").css({ display: "block"}); $(".serv-envio").css({ display: "none"}); }else{ $(".serv-entrega").css({ display: "none"}); $(".serv-envio").css({ display: "block"}); } }else{ $(".total-MCI span").css({ display: "none"}); $(".serv-entrega").css({ display: "none"}); $(".serv-envio").css({ display: "block"}); }; $("#total").html(setFormatMoney(montoTotalCarrito)); $('#itemsCartTotal').html(setFormatMoney(montoTotalCarrito)); $('.bubble').html(noProductosActivos); $('#btnIr').html(''); if(cuponenceros == ""){ $("#btnStarShopping").removeAttr("disabled"); $("#btnStarShopping").removeClass("disabledElement"); }else{ $("#btnStarShopping").attr("disabled","disabled"); $("#btnStarShopping").addClass("disabledElement"); } imgError("imgProduct"); allTeflonChecked(); productosRelacionadosCarrito(); checkMissing(); } function shippingDate(date){ tempDate = date.getTime(); if(dateShippingTemp == null){ dateShippingTemp == new Date().getTime(); } else { dateShippingTemp = dateShippingTemp.getTime(); } if(tempDate > dateShippingTemp){ dateShippingTemp = new Date(tempDate); }else{ dateShippingTemp = new Date(dateShippingTemp); } } function getIdProducto(obj) { // tr = $(obj).closest('tr'); // idPro = tr.find('td:eq(0)').text(); return $(obj).attr("itemId"); } function showMessageCoupon(){ if (cuponesMonto.length > 0){ var tempCoupon = parseFloat(cuponesMonto[0].monto); var textTemp = "El cupón que ingresaste con nombre: "+ cuponesMonto[0].nombre +" es válido en compras mínimas a " + setFormatMoney(tempCoupon) +". Para poder utilizarlo, debes agregar más productos a tu carrito."; //$("#textMensaje").html(textTemp); //$("#textMensaje").show(); //$("#bnrCart").hide(); //$("#bnrCart").html("
"+textTemp+"
"); $("#btnStarShopping").attr("disabled",true); $("#btnStarShopping").addClass("disabledElement"); }else{ //$("#textMensaje").hide(); //$("#bnrCart").hide(); //$("#bnrCart").html(""); $("#btnStarShopping").attr("disabled",false); $("#btnStarShopping").removeClass("disabledElement"); } } function updateCouponAmount(item,id){ if(id===null){ cuponesMonto.push(item); }else{ for (const key in cuponesMonto) { if(id === cuponesMonto[key].id ){ cuponesMonto.splice(key,1); } } } showMessageCoupon(); } function addCouponAmount(data){ cuponesMonto = []; var jsonCupon = data.coupon; var itemDiscount = 0; for (const key in jsonCupon.code_data) { var itemSAP = jsonCupon.data[key]; if(itemSAP.valid){ itemDiscount = parseFloat(jsonCupon.discount_value[key]); if(itemDiscount === 0){ var amountCoupon = parseFloat(itemSAP.flag_min_purchase_amount); updateCouponAmount({id: itemSAP.id,nombre:jsonCupon.code_data[key].code,monto:amountCoupon},null); }else{ updateCouponAmount(null,itemSAP.id); } }else{ updateCouponAmount(null,itemSAP.id); } } } function viewCupon() { $('#cuponesDesc').on('click', function (event) { $(this).css({ 'display': 'none' }); $('#addcupon').css({ 'display': 'table-row' }); $("#numCupon").focus(); }); $('#numCupon').blur(function () { // console.log("entra viewCupon()") numcup = $("#numCupon").val(); if (numcup == "") { $('#addcupon').css({ 'display': 'none' }); $('#cuponesDesc').css({ 'display': 'revert' }); } else { } }); } function agregarProductosCarrito(){ $(document).on('click', '.addtocartset', function (event) { var arrProductos = []; var tempArrayProductos= []; if ($(this).attr('data-type') == "shoplook") { tempArrayProductos = JSON.parse($(this).attr('arrPro')); for (const key in tempArrayProductos) { // arrProductos.push(tempArrayProductos[key]["id"]); arrProductos.push( {"id":tempArrayProductos[key]["id"], "typeVentaTodoMexico": tempArrayProductos[key]["venta_todo_mexico"] } ); var jsonfbq = { content_name: tempArrayProductos[key]['name'], content_category: tempArrayProductos[key]["Category"][0]["slug"]+"/"+tempArrayProductos[key]["Subcategory"]["slug"], content_ids: tempArrayProductos[key]["id"], content_type: 'product', quantity_product: 1, value: tempArrayProductos[key]["price"], currency: 'MXN' }; fbq('track', 'AddToCart', jsonfbq); // _etmc.push(["setOrgId", "526003570"]); // _etmc.push(["setUserInfo", {"email": emailClientSalesforce}]); // _etmc.push(["trackCart", { "cart": [{ // "item" : tempArrayProductos[key]["code"], // "quantity": 1, // "price" : tempArrayProductos[key]["price"], // "unique_id" : tempArrayProductos[key]["code"] // }]}]); } // console.log($(this).attr('arrPro')); } else { // arrProductos.push($(this).attr('data-payload_id')); arrProductos.push( {"id":$(this).attr('data-payload_id'), "typeVentaTodoMexico": $(this).attr('data-typeVentaTodoMexico') } ); console.log("---> agregarProductosCarrito else"); fbq('track', 'AddToCart', { content_name: $(this).attr('data-payload_name'), content_category: $(this).attr('data-payload_category')+"/"+$(this).attr('data-payload_subcategory'), content_ids: $(this).attr('data-payload_id'), content_type: 'product', quantity_product: 1, value: $(this).attr('data-payload_price'), currency: 'MXN' }); // _etmc.push(["setOrgId", "526003570"]); // _etmc.push(["setUserInfo", {"email": emailClientSalesforce}]); // _etmc.push(["trackCart", { "cart": [{ // "item" : $(this).attr('data-payload_code') , // "quantity": 1, // "price" : $(this).attr('data-payload_price'), // "unique_id" : $(this).attr('data-payload_code') // }]}]); } // console.log(arrProductos2); // return; var cpSesion = localStorage.getItem("CP-envio"); var _this = this; loadCartON(); $('#itemsCart').html(""); $("#listProductsRelated").html(''); openModal_MiCarrito(); $.ajax({ type: "POST", url: "/shoppingcart/update_shop_look", data: { zip_code: cpSesion, arr_shoplook: arrProductos }, dataType: "json", success: function (data) { // console.log("Respuesta del controller"); // console.log(data); if (data.result == 'ok') { buscarCarrito(); sendGtag(extractGtagData(_this)); } else { sendNoty("error", "Error"); } // unblockUI(); }, error: function (e) { sendNoty("error", "Error al agregar producto al carrito. Vuelva a intentarlo."); console.log("Error al agregar producto al carrito"); console.log(e); unblockUI(); } }); return false; }); } var tempProductRelated = {} ; function agregarReleatedCarrito(){ $(document).on('click', '.addtocartRelated', function (event) { var _this = this; tempProductRelated = {}; fbq('track', 'AddToCart', { content_name: $(this).attr('data-payload_name'), content_category: $(this).attr('data-payload_category')+"/"+$(this).attr('data-payload_subcategory'), content_ids: $(this).attr('data-payload_id'), content_type: 'product', quantity_product: 1, value: $(this).attr('data-payload_price'), currency: 'MXN' }); tempProductRelated = { "id":$(this).attr('data-payload_id'), "typeVentaTodoMexico": $(this).attr('data-typeVentaTodoMexico') }; updateShoppingcart(parseInt($(this).attr("id").trim()), 1, 'addRelated', $(this).attr('data-payload_code'), $(this).attr('data-payload_price') ); sendGtag(extractGtagData(_this)); return; }); } function loadCartON(){ $('#loaderCarrito').show(); $('.recomendados.recomendados-carrito').hide(); $('#headerCartTeflon').hide(); $('#headerCartRes').hide(); $('#btnIr').hide(); $("#itemsCart").hide(); $("#productsRelated").hide(); $("#msgCarrito").hide(); offRecomendados(); } function loadCartOFF(){ onRecomendados(); // $('#headerCartTeflon').show(); $('#headerCartRes').show(); $('#btnIr').show(); $("#itemsCart").show(); $("#productsRelated").show(); $("#msgCarrito").show(); $('#loaderCarrito').hide(); } /*CARRUSEL NUEVO*/ function goCarouselHome() { $(".carousel-beneficios").slick({ fade: false, dots: false, infinite: true, centerMode: false, slidesToShow: 4, slidesToScroll: 1, variableWidth: true, arrows: false, responsive: [{ breakpoint: 1024, settings: { centerMode: true } }, { breakpoint: 780, settings: { arrows: false, variableWidth: true, slidesToShow: 1, slidesToScroll: 1, centerMode: false } }, { breakpoint: 480, settings: { arrows: false, variableWidth: true, slidesToShow: 4, slidesToScroll: 1, centerMode: false } } // You can unslick at a given breakpoint now by adding: // settings: "unslick" // instead of a settings object ] }); } function goCarouselProduct() { } function productosRelacionadosCarrito(){ loadCartOFF(); $('#loaderCarrito').hide(); // console.log("Cierra el loader"); var parentwidth = $("#headerCartRes").width(); $("#btnIr").width(parentwidth); if(banderaBannerTeflon){ $("#headerCartTeflon").show(); }else{ $("#headerCartTeflon").hide(); } cartDown(); $.ajax({ type: "POST", url: "/shoppingcart/get_productos_relacionados", data: { code_related : productoMasCaro['code'] }, dataType: "json", success: function (data) { if (data.result == 'ok') { pintarCarruselCarrito(data['data']['product_relation_data']); }else{ console.log("Error al consultar los productos relacionados"); console.log(data.msg); loadCartOFF(); cartDown(); } }, error: function (e) { console.log("Error al buscar productos relacionados al mas caro"); console.log(e); loadCartOFF(); } }); } function pintarCarruselCarrito(data){ //console.log(data); var item = ''; for(const key in data) { var value = data[key]; var imgItem = value.image; if(value.url_thumbnail != 'https://'){ imgItem = value.url_thumbnail; }else if(value.image == ""){ imgItem = "/images/products/default-image.jpg"; }else{ imgItem = value.image; } //validar leyenda de envio o servicio de entrega y MCI var Tot_Env = value.price; var valueInterest = (Tot_Env*.014)*18; var Mensualidad = (Tot_Env+valueInterest)/18; /*VALIDAR ETIQUETAS DE PROMOCION POR FECHA*/ var currentdate = new Date(); var elAno = currentdate.getFullYear(); var elMes = (currentdate.getMonth()+1); var elDia = currentdate.getDate(); var laHora = currentdate.getHours(); var losMin = currentdate.getMinutes(); var losSeg = currentdate.getSeconds(); //limpiarSLUGname var nameSLUG = limpiarSLUGname(value.name); //var nameSLUG = value.name; //var nameSLUG = nameSLUG.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); item += '
'; item += '
'; item += ''; item += ''+value.name+' | '+value.subcategory_slug+' | '+value.main_slug+''; item += ''; if(elDia >= 25 && elDia <= 28 && elMes === 11 && elAno === 2022){ item += '
-$500 x cada $2,500
'; } if(value.only_store=="yes"){ item += 'exclusivo en tienda'; } item += '
'; item += '
'+value.name+'
'; if(value.price_old > value.price){ item += '
'; item += '
'+setFormatMoney(value.price_old)+'
'; item += '
'+setFormatMoney(value.price)+'
'; item += '
'; }else{ item += '
'+setFormatMoney(value.price)+'
'; } if(elDia >= 16 && elDia <= 17 && elMes === 11 && elAno === 2022){ item += 'logo-promo'; item += 'logo-promo'; } if(Tot_Env >= 1800){ item += ''; }; if(value.only_store=="yes"){ item += ''; }else{ item += ''; } item += '
'; } $("#listProductsRelated").html(item); // loadCartOFF(); // var parentwidth = $("#headerCartRes").width(); // $("#btnIr").width(parentwidth); // if(banderaBannerTeflon){ // $("#headerCartTeflon").show(); // }else{ // $("#headerCartTeflon").hide(); // } // cartDown(); } var banderaCant = false; var bandIdCant = ""; function changeComboCantidadCarrito(){ $(document).on('change', '.SelectCant', function (event) { var valueCombo = $(this).val(); var idproduct= $(this).attr("itemid"); var sku = $(this).attr("sku"); var price = $(this).attr("price"); if($(this).attr("typeElement") == "product"){ var elementInput = "quantityProdCustomP-"+idproduct; }else{ var elementInput = "quantityProdCustom-"+idproduct; } if (valueCombo == 'customOption') { $(this).css({ 'display': 'none' }); $(this).prop('disabled', true); $('#' + elementInput).css({ 'display': 'flex' }); $('#' + elementInput).css({ 'border': '2px solid blue' }); $('#' + elementInput).css({ 'border-radius': '4px' }); $('#' + elementInput).prop('disabled', false); $('#' + elementInput).val(''); banderaCant = true; bandIdCant = elementInput; return; } else { if($(this).attr("typeElement") == "product"){ $(this).attr("tempcant",valueCombo) ; $('#' + elementInput).attr("tempcant",valueCombo) ; var valorCP = getCP(); if (valorCP !== "") { findCP(valorCP); } return; } updateShoppingcart(idproduct, valueCombo, "quantity", sku, price); } }); } function changeInputCantidadCarrito(){ // console.log(">>>>>>>> changeInputCantidadCarrito-----------"); $(document).on('blur', '.customCant', function (event) { if($(this).attr("typeElement") == "product"){ if(!banderaCant) {changeInputCantidadProduct($(this));} return; } var valueInput = $(this).val(); var idproduct= $(this).attr("itemid"); var elementCombo = "quantityProdSelect-"+idproduct; var tempCant = $(this).attr("tempcant"); var sku = $(this).attr("sku"); var price = $(this).attr("price"); // console.log("Valor del input: "+valueInput); // console.log("Id del producto: "+idproduct); // console.log("Temporal cantidad: "+tempCant); if(valueInput == tempCant){ // console.log("No hace nada, el input y la cantidad de producto es igual"); return; } if (valueInput == '') { // console.log("Input vacio, Muestra el combo y selecciona la cantidad actual del producto"); $(this).css({ 'display': 'none' }); $(this).prop('disabled', true); $('#' + elementCombo).css({ 'display': 'flex' }); $('#' + elementCombo).prop('disabled', false); $('#' + elementCombo).val(tempCant); return; } if (valueInput <= 6) { // console.log("Input <=6 No hace cambios en los elementos, solo ejecuta updateShoppingcart"); // $(this).css({ 'display': 'none' }); // $(this).prop('disabled', true); // $('#' + elementCombo).css({ 'display': 'flex' }); // $('#' + elementCombo).prop('disabled', false); // $('#' + elementCombo).val(valueInput); updateShoppingcart(idproduct, valueInput, "quantity", sku, price); return; // } if (valueInput > 6) { // console.log("Input > 6 No hace cambios en los elementos, solo ejecuta updateShoppingcart"); updateShoppingcart(idproduct, valueInput, "quantity", sku, price); return; } }); } function maxLengthCant(object) { if (object.value.length > 3) object.value = object.value.slice(0, 3) } function changeInputCantidadProduct(element){ // console.log(">>>>>>>> changeInputCantidadProduct-----------"); var valorCP = getCP(); if (valorCP == "" || valorCP == null) { // console.log('No hay CP no hace la consulta de Stock'); return; } var valueInput = element.val(); var idproduct= element.attr("itemid"); var tempCant = element.attr("tempcant"); if(element.attr("typeElement") == "product"){ var elementCombo = "quantityProdSelectP-"+idproduct; }else{ var elementCombo = "quantityProdSelect-"+idproduct; } // console.log("Value input: "+valueInput ); // console.log("idproduct: >"+idproduct+"<" ); // console.log("elementCombo: "+elementCombo ); // console.log("tempCant: "+tempCant ); if (valueInput == '') { if (tempCant <= 6) { // console.log("Entra aqui <=6 "); element.css({ 'display': 'none' }); element.prop('disabled', true); $('#' + elementCombo).css({ 'display': 'flex' }); $('#' + elementCombo).prop('disabled', false); $('#' + elementCombo).val(tempCant); }else{ // console.log("Entra aqui else "); element.val(tempCant); } }else{ if (valueInput <= 6) { element.css({ 'display': 'none' }); element.prop('disabled', true); $('#' + elementCombo).css({ 'display': 'flex' }); $('#' + elementCombo).prop('disabled', false); $('#' + elementCombo).val(valueInput); element.attr("tempcant",valueInput) ; $('#' + elementCombo).attr("tempcant",valueInput) ; }else{ element.css({ 'border': '' }); element.css({ 'border-radius': '' }); element.attr("tempcant",valueInput) ; $('#' + elementCombo).attr("tempcant",valueInput) ; } findCP(valorCP); return; } // var valorCP = getCP(); // if (valorCP !== "") { // // console.log("Entra a buscar Carrito"); // //buscarCarrito(); // } // return; } // Función para alertar faltantes en TOTALES de carrito function checkMissing() { /* var currentdate = new Date(); var elAno = currentdate.getFullYear(); var elMes = (currentdate.getMonth()+1); var elDia = currentdate.getDate(); if(elDia >= 23 && elDia <= 31 && elMes === 05 && elAno === 2022){ var subtotal = $("table.resumen #total").html(); subtotal = subtotal.replace(/[MXN $ ,]/gi, ''); subtotal = subtotal * 1; let faltante = (((Math.floor(subtotal / 10000)) + 1) * 10000) - subtotal; console.log("subT= "+faltante); if(subtotal > 0){ $("#bnrCart").show(); $("#bnrCart").html("
Te faltan sólo $" + faltante.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + " MXN para obtener otros $1,000 MXN de descuento, ¡Sigue llenando tu carrito!
"); } */ /* if(subtotal > 8000 && subtotal < cupon1){ var res = cupon1 - subtotal; $("#missing").html("$ " + res.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + " MXN"); $("#missing-cupon").html(cupon1.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")); } */ var subtotal = $("table.resumen #td_subtotal").html(); subtotal = subtotal.replace(/[MXN $ ,]/gi, ''); subtotal = subtotal * 1; let faltante = (((Math.floor(subtotal / 3000)) + 1) * 3000) - subtotal; /*let descuento = (((Math.floor(subtotal / 3000)) + 1) * 500)*/ /* console.log("Division= "+subtotal/3000); console.log("Division con Math= "+Math.floor(subtotal/3000)); console.log("Descuento Previo= "+descuento); console.log("subTotal= "+subtotal); console.log("Faltante= "+faltante); console.log("Descuento Posterior= "+descuento); if(subtotal > 0){ $("#bnrCart").hide(); $("#bnrCart").html("
¡Sigue llenando tu carrito! Agrega $"+faltante.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") +" a tu órden y ahorra $500 extra.
"); } */ /* if(subtotal > 0){ $("#bnrCart").show(); if(subtotal < 3000){ //$("#bnrCart").html("
¡Sigue llenando tu carrito! Ahorra $500 agregando $"+ faltante.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") +" adicionales
"); } if(subtotal >=10000 && subtotal < 20000){ //$("#bnrCart").html("
¡Sigue llenando tu carrito! Ahorra $3,000 comprando más de $20,000
"); } if(subtotal >=20000 && subtotal < 35000){ //$("#bnrCart").html("
¡Sigue llenando tu carrito! Ahorra $6,000 comprando más de $35,000
"); } if(subtotal >=35000 ){ //$("#bnrCart").html("
¡Sigue llenando tu carrito! Ahorra $10,000 comprando más de $50,000
"); } }*/ } //funcion para pixel de facebook addtocart function FBaddtocart(name, cat, id, quant, val){ fbq('track', 'AddToCart', { content_name: name, content_category: cat, content_ids: id, content_type: 'product', quantity_product: quant, value: val, currency: 'MXN' }); } //funcion para cargar imagen recomendada function loadIMGReco(){ $(function(){ $('.dropdown').hover(function() { var name = $(this).data("name"); var src = $(this).data("src"); var image = new Image(); image.src = src; $('#imgRelacionada-'+name).append(image); }, function() { // console.log("sale") $('.submenu-img img').remove(); }); }); } function limpiarSLUGname(text){ var text = text.toLowerCase(); // a minusculas text = text.replace('/ ', '-'); text = text.replace(/[áàäâå]/, 'a'); text = text.replace(/[éèëê]/, 'e'); text = text.replace(/[íìïî]/, 'i'); text = text.replace(/[óòöô]/, 'o'); text = text.replace(/[úùüû]/, 'u'); text = text.replace(/[ýÿ]/, 'y'); text = text.replace(/[ñ]/, 'n'); text = text.replace(/[ç]/, 'c'); text = text.replace(/ /g, "-"); text = text.replace(/\//g, "-"); return text; } function checkCuponPromo(couponText){ if(COUPON_PROMO_2.code == ""){return false;} couponText = couponText.toUpperCase(); return couponText == COUPON_PROMO_2.code; } flagCurrentAmountCoupon = 4000; function validCurrentCupon(totalProducts){ var flagPivote = (Math.trunc(totalProducts / flagCurrentAmountCoupon)) + 1; var extraAmount = (flagPivote * flagCurrentAmountCoupon) - totalProducts; var textMsg = "
¡Sigue llenando tu carrito! Agrega $"+extraAmount.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") +" a tu órden y ahorra $600 extra.
"; $("#bnrCart").html(textMsg); $("#bnrCart").hide(); } /* //function initBarRatingFeatured() { function initBarRating() { $('.reviews-slct').each(function () { var sc = $(this).attr("score"); var id = $(this).attr("id"); setBarRating(id, sc); console.log("id = "+id+" score = "+sc); }); } function setBarRating(id, score) { var stars = 0; if (score != 0) { stars = score * 5 / 100; } $('#' + id).barrating({ theme: 'fontawesome-stars-o', readonly: true, emptyValue: 0, initialRating: stars }); } */