(function ($) { /* Index */ var wheight = $(window).height(); var indexElement = 0; var indexElementColor = 0; var onScroll = false; //Swipper para la vista product y product2 var swiperProduct = new Swiper('.swiperProduct', { zoom: true, zoom: { maxRatio: 2, }, pagination: { el: '.swiper-pagination', dynamicBullets: true, }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }); //precargar precios y combinaciones de productos por default $(".thumbnail").each(function () { //vars for process let price = 0, salePrice = 0, chkColor = "", optionValue = "", urlProduct = $(this).find("a:first").attr("href"), arrCombinations = $(this).attr("attr-combinations-product").split(","); urlProduct = urlProduct.split("#"); urlProduct = urlProduct[0].split("?op="); urlProduct = urlProduct[0]; //get color in item color if ($(this).find(".optionColors").length > 0) { //si existe item color $(this).find(".optionColors > div").each(function () { if ($(this).hasClass("chkColor")) { chkColor = $(this).attr("attr-value"); //get price and saleprice option select price = $(this).attr("attr-price"); salePrice = $(this).attr("attr-saleprice"); } }); //get color by first element if (chkColor == "") { chkColor = $(this).find(".optionColors > div").first().attr("attr-value"); //get price and saleprice option select price = $(this).find(".optionColors > div").first().attr("attr-price"); salePrice = $(this).find(".optionColors > div").first().attr("attr-saleprice"); } } //get option value size in select droplist if ($(this).find("[name='selectOption[0]']").length > 0) { optionValue = $("option:selected", this).val(); //get price and saleprice option select price = $("option:selected", this).attr("attr-price"); salePrice = $("option:selected", this).attr("attr-saleprice"); } else if ($(this).find("[name='selectOption[1]']").length > 0) { optionValue = $("option:selected", this).val(); //get price and saleprice option select price = $("option:selected", this).attr("attr-price"); salePrice = $("option:selected", this).attr("attr-saleprice"); } //get id combination let chkCombination = ""; arrCombinations.forEach(function (element) { if (element.split("_")[1] === optionValue + chkColor) { chkCombination = element.split("_")[0]; return false; } }); //set new route in product if (chkColor !== "") urlProduct = urlProduct + "#" + chkColor; if (chkCombination !== "") urlProduct = urlProduct + "?op=" + chkCombination; //set new route product $(this).find("a:first").attr("href", urlProduct); $(this).find(".urlProduct-" + $(this).attr('numItem')).attr("href", urlProduct); updateDetailProduct(price, salePrice, $(this)); }); $('[name="selectOption[0]"],[name="selectOption[1]"]').change(function () { let price = 0, salePrice = 0, chkColor = "", optionValue = $("option:selected", this).val(), divParent = $(this).parents('.thumbnail'), urlProduct = divParent.find("a:first").attr("href"), arrCombinations = divParent.attr("attr-combinations-product").split(","); urlProduct = urlProduct.split("#"); urlProduct = urlProduct[0].split("?op="); urlProduct = urlProduct[0]; //get price and saleprice option select price = $("option:selected", this).attr("attr-price"); salePrice = $("option:selected", this).attr("attr-saleprice"); //get color in item color divParent.find(".optionColors > div").each(function () { if ($(this).hasClass("chkColor")) chkColor = $(this).attr("attr-value"); }); //get id combination let chkCombination = ""; arrCombinations.forEach(function (element) { if (element.split("_")[1] === optionValue + chkColor) { chkCombination = element.split("_")[0]; return false; } }); //set new route in product if (chkColor !== "") urlProduct = urlProduct + "#" + chkColor; if (chkCombination !== "") urlProduct = urlProduct + "?op=" + chkCombination; divParent.find("a:first").attr("href", urlProduct); divParent.find(".urlProduct-" + $(this).attr('data-numselect')).attr("href", urlProduct); //optener el precio real de la combinación var info = getPriceCombination(chkCombination); price = info[0] > 0 ? info[0] : price; salePrice = info[1] > 0 ? info[1] : salePrice; updateDetailProduct(price, salePrice, divParent); }); //select option color $(".itemColors").click(function () { let chkColor = "", optionValue = "", divParent = $(this).parents('.thumbnail'), urlProduct = divParent.find("a:first").attr("href"), arrCombinations = divParent.attr("attr-combinations-product").split(","); urlProduct = urlProduct.split("#"); urlProduct = urlProduct[0].split("?op="); urlProduct = urlProduct[0]; //reset select color $(this).parent().children().each(function () { $(this).removeClass("chkColor"); }); //select new color $(this).addClass("chkColor"); //get option value size in select droplist if (divParent.find("[name='selectOption[0]']").length > 0) { $(divParent.find("[name='selectOption[0]']")).each(function () { if ($("option:selected", this).length > 0) { optionValue = $("option:selected", this).val(); } }); } else if (divParent.find("[name='selectOption[1]']").length > 0) { $(divParent.find("[name='selectOption[1]']")).each(function () { if ($("option:selected", this).length > 0) { optionValue = $("option:selected", this).val(); } }); } //get color in item color divParent.find(".optionColors > div").each(function () { if ($(this).hasClass("chkColor")) chkColor = $(this).attr("attr-value"); }); //get id combination let chkCombination = ""; arrCombinations.forEach(function (element) { if (element.split("_")[1] === optionValue + chkColor) { chkCombination = element.split("_")[0]; return false; } }); //set new route in product if (chkColor !== "") urlProduct = urlProduct + "#" + chkColor; if (chkCombination !== "") urlProduct = urlProduct + "?op=" + chkCombination; divParent.find("a:first").attr("href", urlProduct); divParent.find(".urlProduct-" + $(this).attr('numitem')).attr("href", urlProduct); //change color image product changeImgByColorSelect($(this).attr("attr-color"), $(this).attr("attr-product"), $(this).attr("numItem")); //optener el precio real de la combinación var info = getPriceCombination(chkCombination); var price = info[0] > 0 ? info[0] : $(this).attr("attr-price"); var salePrice = info[1] > 0 ? info[1] : $(this).attr("attr-saleprice"); updateDetailProduct(price, salePrice, divParent); }); //get price by combination id function getPriceCombination(chkCombination = null) { var price = 0; var salePrice = 0; $.ajax({ url: window.location.origin + "/search-price-combination", type: 'POST', async: false, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: { "comb": btoa(chkCombination), }, success: function (response) { if (response != null) { price = parseInt(response.price); salePrice = parseInt(response.salePrice); } }, fail: function (response) { console.log(response); } }); return [price, salePrice]; } //update price and saleprice by droplist option selected function updateDetailProduct(price = 0, salePrice = 0, objDiv = null) { var calPrice = parseFloat(price); var callSalePrice = parseFloat(salePrice); price = parseFloat(price).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"); salePrice = parseFloat(salePrice).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"); price = price.replace(".00", ""); salePrice = salePrice.replace(".00", ""); price = price.replace(/,/g, '.'); salePrice = salePrice.replace(/,/g, '.'); var porcentaje = (100 * (calPrice - callSalePrice) / calPrice); objDiv.find("[data-porcentaje]").text('-' + Math.round(porcentaje) + '%'); objDiv.find("[data-price]").text("$" + price); objDiv.find("[data-salePrice]").text("$" + salePrice); } //update color image in product function changeImgByColorSelect(idColor = null, product = null, numSelect = null) { $.ajax({ url: window.location.origin + "/search-img-by-collection", type: 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: { "ioc": btoa(idColor), "iop": btoa(product) }, success: function (response) { //first image var setUrlProductImg = "uploads/pullman/product_images/" + product + "/medium/" + response.image_main; var urlProductImg = window.location.origin + "/" + setUrlProductImg; $(".imgCombinationProduct-" + numSelect).attr("src", urlProductImg); $(".imgCombinationProduct-" + numSelect).attr("data-src", urlProductImg); //second image var setUrlProductImgSecond = "uploads/pullman/product_images/" + product + "/medium/" + response.image_second; var urlProductImgSecond = window.location.origin + "/" + setUrlProductImgSecond; $(".imgSecondCombinationProduct-" + numSelect).attr("src", urlProductImgSecond); $(".imgSecondCombinationProduct-" + numSelect).attr("data-src", urlProductImgSecond); }, fail: function (response) { console.log(response); } }); } /* revisa el parametros color de la url */ //hidden divLoading $(".divLoading").show(); var colorId = urlParams(); if (colorId != "") { $(".swiper-slide-product").each(function () { var imgcolor = $(this).attr("attr-color"); if (typeof imgcolor !== typeof undefined && imgcolor !== false) { if (imgcolor != colorId) $(this).css("display", "none"); else $(this).css("display", ""); } }); swiperProduct.update(); //update swiper //hidden divLoading setTimeout(function () { $(".divLoading").hide(); }, 700); } else { //hidden divLoading setTimeout(function () { $(".divLoading").hide(); }, 700); } $('#home section').each(function () { if ($(this).hasClass('top')) { $(this).css('height', wheight - 104); } else { $(this).css('height', wheight); $(this).css('line-height', wheight + 'px'); $(this).find('.white-box').css('height', wheight); } }) $('#home [rel]').each(function () { if ($(window).scrollTop() == $(this).offset().top) indexElement = parseInt($(this).attr('rel')); }) $('#home').on('mousewheel', function (event) { if (event.originalEvent.wheelDelta >= 0) { if ($('#home [rel="' + (indexElement - 1) + '"]').length > 0 && !onScroll) { indexElement--; if (indexElement == 0) scrollToElement($('header')); else scrollToElement($('#home [rel="' + indexElement + '"]')); } } else { if ($('#home [rel="' + (indexElement + 1) + '"]').length > 0 && !onScroll) { indexElement++; scrollToElement($('#home [rel="' + indexElement + '"]')); } } }) function scrollToElement(element) { onScroll = true; setTimeout(function () { onScroll = false; }, 600) $('html, body').animate({ scrollTop: element.offset().top }, 600); } $(window).load(function () { $('[data-height]').each(function () { var content = $(this).attr('data-height'); $(this).css('line-height', $(content).height() + 'px') }) }) /* Notifications */ if ($('.alert-global').length > 0) { setTimeout(function () { if ($('.alert-global').length > 0) { $('.alert-global').css('animation-name', 'bounceOutUp'); } }, 5000); } $('.alert-global').click(function () { $(this).css('animation-name', 'bounceOutUp'); }) /* Store */ $('[name="store"]').on('input', function () { var value = normalize($(this).val()).toUpperCase(); $('[data-title]').hide(); $('[data-title*="' + value + '"]').show(); $('[data-address*="' + value + '"]').show(); $('[data-city*="' + value + '"]').show(); if (value == '') $('[data-title]').show(); }) var normalize = (function () { var from = "ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç", to = "AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc", mapping = {}; for (var i = 0, j = from.length; i < j; i++) mapping[from.charAt(i)] = to.charAt(i); return function (str) { var ret = []; for (var i = 0, j = str.length; i < j; i++) { var c = str.charAt(i); if (mapping.hasOwnProperty(str.charAt(i))) ret.push(mapping[c]); else ret.push(c); } return ret.join(''); } })(); if ($('[name="store"]').length > 0) { $('[data-title]').each(function () { var title = $(this).attr('data-title') var address = $(this).attr('data-address') var city = $(this).attr('data-city') $(this).attr('data-title', normalize(title)) $(this).attr('data-address', normalize(address)) $(this).attr('data-city', normalize(city)) }) } /* Zoom */ //var $easyzoom = $('.easyzoom').easyZoom(); //var api = $easyzoom.data('easyZoom'); /* Imagen Thumb */ $('[data-image-src]').click(function () { var key = $(this).attr('data-image-src'); $('[data-image]').hide(); $('[data-image="' + key + '"]').show(); }); $('.thumbnail [name="size"]').on('change', function () { var value = $(this).val(); var price = $(this).find('option[value="' + value + '"]').eq(0).attr('price'); var sale = $(this).find('option[value="' + value + '"]').eq(0).attr('sale-price'); $(this).parent().find('[data-price]').eq(0).text(price); $(this).parent().find('[data-salePrice]').eq(0).text(sale); }); $('[name="values[0]"]').change(function () { chkCombos($(this)); //verifica si hay combos activos $('.cart-add').attr('disabled', 'disabled'); if ($('[name="values[0]"] option:selected').attr('attr-color') != '') { getCombination(1); } else { getCombination(0); } }); $('[name="values[1]"]').change(function () { chkCombos($(this)); //verifica si hay combos activos if (urlParams()) refreshSlider(); //refresco la imagenes getCombination(0); }); function chkCombos(obj) { //validar si la medida coincide en algun combo if($(".itemCombo").length > 0 && obj.attr("id") == "size_value") { let selectSizeValue = obj.val(); $(".itemCombo").each(function(){ let combovalues = $(this).attr("combovalues"); combovalues = combovalues.split(","); if (combovalues.includes(selectSizeValue)) { $(this).parent().parent().parent().removeClass("hidden"); } else { $(this).parent().parent().parent().addClass("hidden"); } }); } } function genereStrutureDataGoogle(data) { const jsonld = JSON.stringify({ "@context": "https://schema.org/", "@type": "Product", "name": "", "image": "", "description": "", "sku": "", "mpn": "", "brand": { "@type": "Brand", "name": "" }, "review": { "@type": "Review", "author": { "@type": "Organization", "name": "Pullman" } }, "offers": { "@type": "Offer", "url": "", "priceCurrency": "COP", "price": "", "itemCondition": "https://schema.org/NewCondition", "availability": "https://schema.org/InStock" } }); const arrImgGoogle = []; const obj = JSON.parse(jsonld); $(".swiper-zoom-container").each(function () { if (urlParams() == $(this).children('img').attr('attr-color')) arrImgGoogle.push($("#dt-google-urlBase").text() + $(this).children('img').attr('data-src')); }); if (arrImgGoogle.length == 0) { $(".swiper-zoom-container").each(function () { arrImgGoogle.push($("#dt-google-urlBase").text() + $(this).children('img').attr('data-src')); }); } obj.name = $("#dt-google-pname").text(); obj.image = arrImgGoogle; obj.description = $("#dt-google-pshortD").text(); obj.sku = $("#dt-google-psku").text(); obj.mpn = $("#dt-google-pidProduct").text(); obj.brand.name = $("#dt-google-pmake").text(); obj.offers.url = window.location.href; obj.offers.price = parseInt($("#dt-google-pprice").text()); if (parseInt(data.salePriceNumber) > 0) obj.offers.price = parseInt(data.salePriceNumber); else obj.offers.price = parseInt(data.priceNumber); var script = document.createElement('script'); script.type = 'application/ld+json'; script.innerHTML = JSON.stringify(obj); $("head").prepend(script); } function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + '.' + '$2'); } return x1 + x2; } function setPriceParameter(data = null) { if (Object.keys(data).length > 1) { $('.product [data-price]').text(data.price); $('.product [data-salePrice]').text(data.salePrice); $('.product [data-safe]').text('-' + (Math.round((100 * (data.priceNumber - data.salePriceNumber) / data.priceNumber))) + '%'); $('.product [name="price"]').val(data.salePriceNumber > 0 ? data.salePriceNumber : data.priceNumber); if (!$('.group-product').hasClass('active')) $('.group-product').addClass('active'); $('.cart-add').removeAttr('disabled'); //set price to widget addi if (parseInt(data.salePriceNumber) > 0) { if ((parseInt(data.salePriceNumber) >= 50000 && parseInt(data.salePriceNumber) <= 5000000)) { $("#widgetaddi").attr("price", parseInt(data.salePriceNumber)); } else { $("#widgetaddi").hide(); } } else if (parseInt(data.priceNumber) > 0) { if ((parseInt(data.priceNumber) >= 50000 && parseInt(data.priceNumber) <= 5000000)) { $("#widgetaddi").attr("price", parseInt(data.priceNumber)); } else { $("#widgetaddi").hide(); } } else { $("#widgetaddi").hide(); } //calculo de cuotas addi /*if ($("#divCrediAddi").length > 0) { if (parseInt(data.salePriceNumber) > 0) { if((parseInt(data.salePriceNumber) >= 600001 && parseInt(data.salePriceNumber) <= 1500000)) { let cuotasCrediAddi = Math.round(parseInt(data.salePriceNumber) / 3); $("#cuotasCrediAddi").text("$" + addCommas(cuotasCrediAddi)); $("#divCrediAddi").show(); }else{ $("#divCrediAddi").hide(); } } else if (parseInt(data.priceNumber) > 0) { if((parseInt(data.priceNumber) >= 600001 && parseInt(data.priceNumber) <= 1500000)) { let cuotasCrediAddi = Math.round(parseInt(data.salePriceNumber) / 3); $("#cuotasCrediAddi").text("$" + addCommas(cuotasCrediAddi)); $("#divCrediAddi").show(); }else{ $("#divCrediAddi").hide(); } } else { $("#divCrediAddi").hide(); } }*/ //add data structure google //genereStrutureDataGoogle(data); } else { $('.cart-add').prop("selected", true); } } function updatePriceProduct() { var values = []; var options = []; $('[data-option]').each(function (i) { var combOpt = $(this).val(); options[i] = $(this).attr('data-option') values[i] = combOpt; }); $.ajax({ type: 'POST', dataType: 'json', data: { values: JSON.stringify(values), options: JSON.stringify(options) }, /*NUEVO AJUSTE PARA CONTROL DE COMBINACIONES*/ success: function (data) { setPriceParameter(data); } }); } //GOOGLE function generateProductSchema(productData) { // Determinar disponibilidad basada en stock const availability = parseInt(productData.stock) > 0 ? "https://schema.org/InStock" : "https://schema.org/OutOfStock"; const arrImgGoogle = []; $(".swiper-zoom-container").each(function () { if (urlParams() == $(this).children('img').attr('attr-color')) arrImgGoogle.push($("#dt-google-urlBase").text() + $(this).children('img').attr('data-src')); }); if (arrImgGoogle.length == 0) { $(".swiper-zoom-container").each(function () { arrImgGoogle.push($("#dt-google-urlBase").text() + $(this).children('img').attr('data-src')); }); } // Construir el objeto schema const productSchema = { "@context": "https://schema.org/", "@type": "Product", "name": $("#dt-google-pname").text(), "image": arrImgGoogle, // Función auxiliar para obtener imagen "description": $("#dt-google-pshortD").text(), // Función auxiliar para descripción "sku": productData.skuCombination || '', "mpn": productData.idCombination ? productData.idCombination.toString() : '', "brand": { "@type": "Brand", "name": $("#dt-google-pmake").text(), // Asumiendo que la marca es Pullman según el review }, "review": { "@type": "Review", "reviewRating": { "@type": "Rating", "ratingValue": "5", // Valor por defecto, puedes ajustarlo "bestRating": "5" }, "author": { "@type": "Organization", "name": "Pullman" } }, "offers": { "@type": "Offer", "url": window.location.href, "priceCurrency": productData.currency || "COP", "price": productData.salePriceNumber || productData.priceNumber, "itemCondition": "https://schema.org/NewCondition", "availability": availability } }; return productSchema; } function getCombination(isColor, idCombinationUrl = null) { var values = []; var options = []; $('[data-option]').each(function (i) { var combOpt = $(this).val(); options[i] = $(this).attr('data-option') values[i] = combOpt; }); if (idCombinationUrl != null) { var match = false; arrCombProd = $("#combinationsObject").val().split(","); $(arrCombProd).each(function (index, option) { if (option.split("_")[0] == idCombinationUrl) match = true; }); if (!match) idCombinationUrl = null; } $.ajax({ type: 'POST', dataType: 'json', data: { values: JSON.stringify(values), options: JSON.stringify(options), idCombination: idCombinationUrl }, success: function(data) { // 1. Manejo inicial del stock let hasStock = true; // Generar el schema del producto const productSchema = generateProductSchema(data); // Agregar el schema al DOM const scriptTag = document.createElement('script'); scriptTag.type = 'application/ld+json'; scriptTag.text = JSON.stringify(productSchema); $("head").prepend(scriptTag); // 2. Procesar cada opción del producto Object.keys(options).forEach(o => { const optionKey = options[o]; const $select = $(`[name="values[${o}]"]`); if (o > 0) { // 2.1. Ocultar todas las opciones primero $select.find('option').addClass('hidden'); // 2.2. Procesar cada opción disponible data.optionals[optionKey].forEach(option => { const $option = $select.find(`[value="${option.idOptionValue}"]`); const isSelectedCombination = idCombinationUrl && option.idOptionValue == data.optionsValues[1]; const isOutOfStock = parseInt(option.stock) === 0; // 2.3. Manejar opciones seleccionadas o sin stock if (isSelectedCombination) { $option.removeClass("hidden").prop("selected", true); } else if (isOutOfStock) { const originalText = $option.data('original-text') || $option.text().replace(/\s*sin stock\s*/gi, '').trim(); $option.removeClass("hidden").attr("attr-stock", parseInt(option.stock)).text(`${originalText} sin stock`); // Si esta es la combinación actual, no hay stock if (data.optionsValues.includes(option.idOptionValue.toString())) { //hasStock = false; } } else { const originalText = $option.data('original-text') || $option.text().replace(/\s*sin stock\s*/gi, '').trim(); $option.removeClass("hidden").attr("attr-stock", parseInt(option.stock)).text(`${originalText}`); } }); // 2.4. Manejar selección actual inválida if ($select.find('option:selected').hasClass('hidden')) { $select.val(data.optionals[optionKey][0].idOptionValue); updatePriceProduct(); } else { setPriceParameter(data); } // 2.5. Resetear si la opción seleccionada no está disponible if ($select.find('option:selected').hasClass('hidden')) { $select.val(''); } // 2.6. Manejo especial para colores if (isColor) { const selectedVal = $select.val(); if (selectedVal && selectedVal != 0 && selectedVal != '') { $('.cart-add').prop('disabled', false); } else { $('.cart-add').prop('disabled', true); } } } else { // 3. marca las opciones sin stock let isColor = false; if($('#color_value').length > 0) { isColor = true; $('#color_value option').each(function(){ if($(this).attr("attr-stock") == 0) { const originalText = $(this).data('original-text') || $(this).text().replace(/\s*sin stock\s*/gi, '').trim(); $(this).text(`${originalText} sin stock`); } }); } if(!isColor) { $('[name="values[0]"] option').each(function(){ if($(this).attr("attr-stock") == 0) { const originalText = $(this).data('original-text') || $(this).text().replace(/\s*sin stock\s*/gi, '').trim(); $(this).text(`${originalText} sin stock`); } }); } // 3. Manejar la opción primaria if (!$('[name="values[1]"]').length) { setPriceParameter(data); } if (idCombinationUrl && data.optionsValues.length > 1) { $(`[name="values[${o}]"] [value="${data.optionsValues[0]}"]`).prop('selected', true); } } }); // 4. Actualizar estado del botón de añadir al carrito $('.cart-add').prop('disabled', !hasStock); // 5. Actualizar la interfaz refreshSlider(); // 6. Ocultar el loader después de un breve retraso setTimeout(() => $(".divLoading").hide(), 700); // 7. Manejar experiencia Mudi 3D/AR si es necesario if ($(".product-images").length) { $(".btnsMudiContainer").remove(); mudiExperience.experienceOn(data.skuCombination, document.body.querySelector('.product-images')); } //8. Valida si la opcion seleccionada no tiene stock y bloquea el botón de agregar al carrito if($('[name="values[1]"]').length > 0) { if($('[name="values[1]"] option:selected').attr('attr-stock') == 0) { $('.cart-add').prop('disabled', true); return false; } } else if($('[name="values[0]"]').length > 0 && $('[name="values[0]"] option:selected').attr('attr-stock') == 0) { $('.cart-add').prop('disabled', true); return false; } }, error: function(xhr, ajaxOptions, thrownError) { // Manejo de errores consistente $('#productPopup .modal-title').text('No se ha encontrado el modelo deseado'); $('#productPopup .modal-body').text('Intente otra combinación'); $('#productPopup').modal('show'); $('.cart-add').prop('disabled', true); return false; } }); } $('.quantity_container a').click(function () { var that = $(this).parent().closest('.quantity_container').find('span').eq(0); if (that.text() == 1 && $(this).hasClass('less')) return false; $('body').css('cursor', 'progress') var slug = $(this).parent().attr('data-slug'); var quantity = parseInt(that.text()); if ($(this).hasClass('less')) quantity--; if ($(this).hasClass('more')) quantity++; $.ajax({ type: 'POST', dataType: 'json', url: '/cart/update', data: { slug: slug, quantity: quantity }, success: function (data) { if (!data.error) { that.text(quantity); window.location.reload(); $('body').css('cursor', 'auto') } }, error: function () { return false; } }) }) $('.delete-product').click(function () { $('body').css('cursor', 'progress') var slug = $(this).attr('data-slug'); $.ajax({ type: 'POST', dataType: 'json', url: '/cart/update', data: { slug: slug, delete: true }, success: function (data) { if (!data.error) { $('body').css('cursor', 'auto') $(this).closest('tr').fadeOut(300); window.location = '/cart'; } }, error: function () { return false; } }) }) $('.btn-coupon').click(function () { var value = $('[name="coupon"]').val(); if (value == '') return false; $.ajax({ type: 'POST', url: 'validate/coupon', data: { coupon: value }, success: function (data) { if (!data.error) { $('[data-total]').text(data.cart.total); $('[data-coupon]').text(data.cart.discount); $('[data-coupon-tax]').text(data.cart.taxDiscount); $('[name="coupon"]').parent().removeClass('has-error').addClass('has-success'); $('[name="amount"]').val(data.cart.totalNumber) $('[name="tax"]').val(data.cart.taxDiscountNumber) $('[name="taxReturnBase"]').val(data.cart.subtotalTaxDiscountNumber) $('.coupon-container').show('fast'); } else { $('[name="coupon"]').parent().removeClass('has-success').addClass('has-error'); } }, error: function () { $('[name="coupon"]').parent().removeClass('has-success').addClass('has-error'); return false; } }) }) function refreshSlider() { var selectColor = $('#color_value option:selected').attr('attr-color'); if (typeof selectColor !== typeof undefined && selectColor != false && selectColor != '') { $(".swiper-slide-product").each(function () { imgcolor = $(this).attr("attr-color"); if (typeof imgcolor !== typeof undefined && imgcolor !== false) { if (imgcolor != selectColor) $(this).css("display", "none"); else $(this).css("display", ""); } }); swiperProduct.update(); //update swiper } } /* Url params */ function urlParams() { const hash = window.location.hash; const comb = hash.substring(1); // Elimina el # let colorId = ""; if (comb != "") colorId = (typeof comb.split("?op")[0] !== "undefined") ? comb.split("?op")[0] : ""; return colorId; } /* Url params by combination select */ function getUrlIdCombination() { let url = window.location.href; url = url.replace("?AR=true", ""); let optionId = (typeof url.split("?op=")[1] !== "undefined") ? url.split("?op=")[1] : ""; return optionId; } if ($('#AddToCartForm').length > 0) { if (urlParams()) { if (getUrlIdCombination()) { /*NUEVO AJUSTE PARA CONTROL DE COMBINACIONES*/ if ($('select[name="values[0]"] option[attr-combination="' + getUrlIdCombination() + '"]').length > 0) { //$('select[name="values[0]"] option[attr-combination="' + getUrlIdCombination() + '"]').attr('selected', 'selected'); //select unico de color $('select[name="values[0]"] option[attr-combination="' + getUrlIdCombination() + '"]').prop("selected", true); //con los cuadros son checked } else if ($('select[name="values[1]"] option[attr-combination="' + getUrlIdCombination() + '"]').length > 0) { //$('select[name="values[1]"] option[attr-combination="' + getUrlIdCombination() + '"]').attr('selected', 'selected'); //select multiple de medida y color $('select[name="values[1]"] option[attr-combination="' + getUrlIdCombination() + '"]').prop("selected", true); } getCombination(1, getUrlIdCombination()); } else { if ($('select[name="values[0]"] option[value="' + urlParams() + '"]').length > 0) { //$('select[name="values[0]"] option[value="' + urlParams() + '"]').attr('selected', 'selected'); //select unico de color $('select[name="values[0]"] option[value="' + urlParams() + '"]').prop("selected", true); //con los cuadros son checked } else if ($('select[name="values[1]"] option[value="' + urlParams() + '"]').length > 0) { //$('select[name="values[1]"] option[value="' + urlParams() + '"]').attr('selected', 'selected'); //select multiple de medida y color $('select[name="values[1]"] option[value="' + urlParams() + '"]').prop("selected", true); } getCombination(1); } } else { if (getUrlIdCombination()) { /*NUEVO AJUSTE PARA CONTROL DE COMBINACIONES*/ //$('select[name="values[0]"] option[attr-combination="' + getUrlIdCombination() + '"]').attr('selected', 'selected'); $('select[name="values[0]"] option[attr-combination="' + getUrlIdCombination() + '"]').prop("selected", true); getCombination(0, getUrlIdCombination()); } else { $('[name="values[0]"]').eq(0).prop("selected", true); getCombination(0); } } } })(jQuery)