1 2var ajax_wc_cambio = ""; //Variable para valorar la actividad del Ajax 3var urlAjax = js_params_woo.ajaxurl; 4 5jQuery(document).ready(function ($) { 6 var isRefreshing = false; // Bandera para evitar llamadas repetidas 7 8 $(document).ajaxComplete(function (event, xhr, settings) { 9 // Detectamos si se realizó la llamada para aplicar cupón. 10 if (settings.url.indexOf("apply_coupon") !== -1 && !isRefreshing) { 11 isRefreshing = true; 12 $.ajax({ 13 url: wc_cart_fragments_params.wc_ajax_url 14 .toString() 15 .replace("%%endpoint%%", "get_refreshed_fragments"), 16 type: "POST", 17 success: function (data) { 18 if (data.fragments) { 19 $.each(data.fragments, function (key, value) { 20 $(key).replaceWith(value); 21 }); 22 } 23 isRefreshing = false; // Reiniciamos la bandera 24 }, 25 error: function () { 26 isRefreshing = false; // Reiniciamos la bandera en caso de error 27 }, 28 }); 29 } 30 }); 31}); 32 33if (typeof wc_cart_fragments_params === "undefined") { 34 var wc_cart_fragments_params = { 35 wc_ajax_url: 36 "<?php echo admin_url('admin-ajax.php'); ?>?wc-ajax=%%endpoint%%", 37 }; 38} 39 40/////////////////////////////////////////////////////////////////////////////////////////////////////////////////ARRANQUE 41jQuery(document).ready(function () { 42 //Pageview si producto view 43 if (jQuery(".single-product").length) { 44 gtm_view_product(); 45 } 46 47 //Evento si hay mensajes 48 if (jQuery(".popup-wc-info").length) { 49 jQuery("body").css({ 50 height: "100%", 51 overflow: "hidden", 52 }); 53 } 54 55 //Retiramos el desplegable del minicar si es la página de carrito 56 if (jQuery(".woocommerce-cart").length) { 57 jQuery('a[data-obj="#mini-cart"]').removeClass("desplegable-desplegar"); 58 } 59 60 //Minicart - COMENTADO: El mini-carrito ya está renderizado en servidor 61 // No necesita recargarse en cada page load, solo cuando el carrito cambia (add/remove product) 62 // cambio_minicart(); 63 // cambio_boton_minicart(); 64}); 65 66/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Actualizar precio automower 67 68document.addEventListener("DOMContentLoaded", function () { 69 // Función para convertir una cadena de precio (ej. "3.299,00") a número 70 function parsePrice(priceStr) { 71 // Quita puntos (separador de miles) y reemplaza la coma decimal por punto 72 var normalized = priceStr.replace(/\./g, "").replace(",", "."); 73 return parseFloat(normalized); 74 } 75 76 // Función para formatear un número a precio (ej. 3299 a "3.299,00") 77 function formatPrice(num) { 78 return num.toLocaleString("es-ES", { 79 minimumFractionDigits: 2, 80 maximumFractionDigits: 2, 81 }); 82 } 83 84 // Seleccionamos el select de instalaciones 85 var installationSelect = document.getElementById("instalacion"); 86 // Seleccionamos el elemento que muestra el precio base del automower. 87 // En este ejemplo, asumimos que está en una etiqueta <precioproducto>. 88 var priceElem = document.querySelector("precioproducto"); 89 if (priceElem) { 90 // Guardamos el precio base en un atributo data (para restaurarlo cuando no se seleccione instalación) 91 priceElem.dataset.basePrice = parsePrice(priceElem.textContent.trim()); 92 } 93 94 if (installationSelect) { 95 installationSelect.addEventListener("change", function () { 96 // Si no se selecciona ninguna instalación, restauramos el precio base 97 if (installationSelect.value === "") { 98 if (priceElem && priceElem.dataset.basePrice) { 99 priceElem.textContent = formatPrice( 100 parseFloat(priceElem.dataset.basePrice), 101 ); 102 } 103 return; 104 } 105 106 // Obtenemos la opción seleccionada 107 var selectedOption = 108 installationSelect.options[installationSelect.selectedIndex]; 109 // Obtenemos el precio de la instalación desde el atributo data-price 110 var installationPrice = 111 parseFloat(selectedOption.getAttribute("data-price")) || 0; 112 113 // Obtenemos el precio base almacenado 114 var basePrice = 115 priceElem && priceElem.dataset.basePrice 116 ? parseFloat(priceElem.dataset.basePrice) 117 : 0; 118 119 // Calculamos el nuevo precio 120 var newPrice = basePrice + installationPrice; 121 122 // Actualizamos el contenido del elemento con el nuevo precio formateado 123 if (priceElem) { 124 priceElem.textContent = formatPrice(newPrice); 125 } 126 });
127 } 128}); 129 130/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Añadir producto 131 132jQuery(document).on("click", ".boton-add-cart-ficha", function (e) { 133 var itemKey = jQuery(this).data("product_id"); 134 var quantity = jQuery(this).data("quantity"); 135 var variacion = ""; 136 var orig = "ficha"; 137 add_cart(itemKey, quantity, variacion, orig); 138 e.preventDefault(); 139}); 140 141// Añade al carrito modificado para que añada instalcion en los productos automower 142 143function add_cart(itemKey, quantity, variacion, orig) { 144 // Intentamos encontrar el select del producto de instalación en la ficha del producto 145 var instalacion_select = jQuery("select[name='instalaciones_automower']"); 146 var instalacion_id = null; 147 148 // Verificar si el select de instalación existe en el DOM 149 if (instalacion_select.length > 0) { 150 instalacion_id = instalacion_select.val(); 151 152 // Solo bloquear si está vacÃo (automower sin opción seleccionada) 153 if (instalacion_id === "") { 154 alert("Por favor, selecciona una instalación."); 155 return false; 156 } 157 158 // Si es "0" (sin instalación), no enviar el parámetro 159 if (instalacion_id === "0") { 160 instalacion_id = null; 161 } 162 } 163 164 // Crear el objeto de datos a enviar 165 var data = { 166 action: "add_producto", 167 product_id: itemKey, 168 quantity: quantity, 169 variation_id: variacion, 170 }; 171 172 // Solo añadir la instalación si está presente 173 if (instalacion_id) { 174 data.instalaciones_automower = instalacion_id; 175 } 176 177 // Realizar la solicitud AJAX 178 jQuery.ajax({ 179 type: "POST", 180 url: urlAjax, // Asegúrate de que 'urlAjax' está correctamente definido 181 data: data, 182 dataType: "json", // Cambiamos a 'json' para esperar una respuesta JSON 183 cache: false, 184 headers: { "cache-control": "no-cache" }, 185 beforeSend: function () { 186 // Mostrar animación de carga 187 jQuery("#mini-cart-content").html( 188 '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ml-10">Cargando</span></div>', 189 ); 190 }, 191 success: function (response) { 192 if (response.error) { 193 // Si hay un error, mostramos los avisos de WooCommerce 194 jQuery(".woocommerce-notices-wrapper").html(response.notices); 195 jQuery("#mini-cart").removeClass("show"); 196 } else { 197 // Si no hay error, actualizamos el mini-carrito y lo mostramos 198 jQuery("#mini-cart-content").html(response.mini_cart); 199 jQuery(".desplegable-lat-bloque > span").text(response.cart_count); 200 jQuery(".cart-contents .count").text(response.cart_count); 201 var $miniCart = jQuery("#mini-cart"); // Seleccionar el mini-cart 202 desplegar_desplegable($miniCart); // Mostrar el carrito lateral 203 // Actualizar contador del minicart 204 jQuery(".minicart-items-count .number").text(response.cart_count); 205 206 // Actualizar badge del header 207 const badge = jQuery(".cart-count"); 208 badge.text(response.cart_count); 209 response.cart_count > 0 210 ? badge.removeClass("d-none") 211 : badge.addClass("d-none"); 212 } 213 }, 214 error: function (error) { 215 ("Error AJAX: ", error); 216 }, 217 }); 218} 219 220jQuery(document).ready(function () { 221 // (jQuery("#pofw_product_options")); 222 if (jQuery("#pofw_product_options input").length) { 223 // ("he encontrado la variacion"); 224 setAjaxButtons(); 225 // AJAX buy button for variable products 226 function setAjaxButtons() { 227 jQuery(document).on("submit", ".add-cart-product", function (e) { 228 var target = e.target; 229 if (document.documentElement.lang == "pt-PT") { 230 jQuery("#mini-cart-content").html( 231 '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ml-10">A carregar</span></div>', 232 ); //Animación de carga 233 } else { 234 jQuery("#mini-cart-content").html( 235 '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ml-10">Cargando</span></div>', 236 ); //Animación de carga 237 } 238 desplegar_desplegable(jQuery("#mini-cart")); //Desplegamos el minicarrito 239 e.preventDefault(); 240 var dataset = jQuery(e.target).closest("form"); 241 var product_id = jQuery(e.target) 242 .closest("form") 243 .find("input[name*='product_id']"); 244 product_id = jQuery(this).data("product_id"); 245 values = dataset.serialize(); 246 values; 247 248 jQuery.ajax({ 249 type: "POST", 250 url: "?add-to-cart=" + product_id, 251 data: values, 252 success: function (response, textStatus, jqXHR) { 253 // $response = jQuery.parseHTML(response); 254 response; 255 // ($response); 256 jQuery("#mini-cart-content").html( 257 jQuery(jQuery.parseHTML(response)).find("#mini-cart-content"), 258 ); 259 cambio_boton_minicart(); 260 // loadPopup(target); // function show popup 261 // updateCartCounter(); 262 }, 263 }); 264 return false; 265 }); 266 } 267 } else { 268 jQuery(document).on("submit", ".add-cart-product", function (e) { 269 var itemKey = jQuery(this).data("product_id"); 270 var quantity = jQuery(this).find(".qty").val(); 271 var variacion = ""; 272 if (jQuery(this).find(".variation_id").length) { 273 variacion = jQuery(this).find(".variation_id").val(); 274 } 275 var orig = "product"; 276 "id: " + 277 itemKey + 278 " -- can: " + 279 quantity + 280 " -- var: " + 281 variacion + 282 " -- orig: " + 283 orig; 284 add_cart(itemKey, quantity, variacion, orig); 285 e.preventDefault(); 286 });
287 } 288}); 289 290jQuery(document).on("click", ".product-qty-cambio", function (e) { 291 var input = jQuery(this).siblings(".quantity").find(".qty"); 292 var cambio = parseInt(jQuery(this).data("accion")); 293 cambio_cantidad(input, cambio); 294}); 295 296jQuery(document).on("change", ".item-cantidad-contador", function (e) { 297 var input = jQuery(this); 298 var cambio = parseInt(jQuery(this).val()); 299 cambio_cantidad(input); 300}); 301 302function cambio_cantidad(input, cambio) { 303 // Leer el valor actual del input, asegurando que sea un entero (por defecto 1) 304 var total = parseInt(input.val(), 10) || 1; 305 306 // Si se pasó un cambio (por ejemplo, al hacer clic en + o -), se suma al valor actual 307 if (typeof cambio !== "undefined") { 308 total = total + cambio; 309 } 310 311 // Asegurarse de que no sea menor que 1 312 if (total < 1) { 313 total = 1; 314 } 315 316 // Si existe un atributo "max", respetarlo 317 if (input.attr("max")) { 318 var maxVal = parseInt(input.attr("max"), 10); 319 if (total > maxVal) { 320 total = maxVal; 321 } 322 } 323 324 // Actualizar el valor del input y opcionalmente guardar el valor actual en data("val") 325 input.val(total); 326 input.data("val", total); 327 328 // Si el input se encuentra en el mini-cart o carrito, actualizar el Ãtem correspondiente 329 if (input.data("type") === "mini-cart" || input.data("type") === "cart") { 330 var miniCartItem = input.closest(".mini-cart-item"); 331 332 // Si es un automower (no tiene el atributo data-installation) 333 if (!miniCartItem.attr("data-installation")) { 334 var automowerKey = miniCartItem.data("cart_item_key"); 335 // Buscar el Ãtem de instalación asociado (que tiene data-installation="1") 336 var installationItem = jQuery( 337 '#mini-cart-content .mini-cart-item[data-installation="1"]', 338 ); 339 var installationKey = installationItem.length 340 ? installationItem.data("cart_item_key") 341 : ""; 342 // Actualizar ambos Ãtems (automower e instalación) con la misma cantidad 343 actualizar_par(automowerKey, installationKey, total); 344 } else { 345 // Si se modifica el Ãtem de instalación (normalmente el campo está disabled) 346 cambio_cantidad_cart(miniCartItem.data("cart_item_key"), total); 347 } 348 } 349} 350 351function cambio_cantidad_cart(itemKey, total) { 352 if (ajax_wc_cambio != "") { 353 ajax_wc_cambio.abort(); 354 } 355 var data = { 356 action: "cambio_cantidad", 357 id: itemKey, 358 quantity: total, 359 }; 360 ajax_wc_cambio = jQuery.ajax({ 361 type: "POST", 362 url: urlAjax, 363 data: data, 364 dataType: "html", 365 cache: false, 366 headers: { "cache-control": "no-cache" }, 367 beforeSend: function (response) { 368 jQuery(".item-anim-carga-" + itemKey).css({ 369 opacity: 1, 370 display: "flex", 371 }); 372 }, 373 success: function (response) { 374 ajax_wc_cambio = ""; 375 jQuery(".item-anim-carga").css({ opacity: 0, display: "none" }); 376 if (response.error) { 377 } else { 378 jQuery("#mini-cart-content").html(response); 379 if (jQuery(".woocommerce-cart").length) { 380 //Si estoy en el carrito 381 cambio_cart(); 382 } 383 cambio_boton_minicart(); 384 } 385 }, 386 error: function (response) { 387 response; 388 }, 389 }); 390} 391 392function actualizar_par(automowerKey, installationKey, quantity) { 393 jQuery.ajax({ 394 type: "POST", 395 url: urlAjax, 396 data: { 397 action: "update_both_items", 398 automower: automowerKey, 399 installation: installationKey, 400 quantity: quantity, 401 }, 402 dataType: "json", 403 success: function (response) { 404 if (response.success) { 405 // Actualizamos el mini-cart de una sola vez 406 jQuery("#mini-cart-content").html(response.data.mini_cart); 407 cambio_boton_minicart(); 408 cambio_cart(); 409 } else { 410 } 411 }, 412 error: function (err) { 413 }, 414 }); 415} 416 417/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Borrar elementos 418jQuery(document).on("click", "#mini-cart-content .remove", function (e) { 419 e.preventDefault(); 420 421 // Capturamos el cart_item_key del producto (automower) que se quiere borrar 422 var removeButton = jQuery(this);
423 var automowerKey = removeButton.data("cart_item_key"); 424 425 // Antes de limpiar el miniâcarrito, buscamos si existe un Ãtem de instalación asociado 426 var installationKey = null; 427 var installationItem = jQuery( 428 '#mini-cart-content .mini-cart-item[data-installation="1"]', 429 ); 430 if (installationItem.length) { 431 installationKey = installationItem.data("cart_item_key"); 432 } 433 434 // Mostramos el indicador de carga en el miniâcarrito 435 var loadingText = 436 document.documentElement.lang == "pt-PT" 437 ? '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ml-10">A carregar</span></div>' 438 : '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ml-10">Cargando</span></div>'; 439 jQuery("#mini-cart-content").html(loadingText); 440 441 // Preparamos las llamadas AJAX de borrado sin actualizar el miniâcarrito de forma individual 442 var ajaxCalls = []; 443 444 // Llamada para borrar el automower 445 ajaxCalls.push( 446 jQuery.ajax({ 447 type: "POST", 448 url: urlAjax, 449 data: { action: "borrar_producto", id: automowerKey }, 450 dataType: "html", 451 cache: false, 452 headers: { "cache-control": "no-cache" }, 453 }), 454 ); 455 456 // Si se encontró una instalación asociada, preparamos su borrado también 457 if (installationKey) { 458 ajaxCalls.push( 459 jQuery.ajax({ 460 type: "POST", 461 url: urlAjax, 462 data: { action: "borrar_producto", id: installationKey }, 463 dataType: "html", 464 cache: false, 465 headers: { "cache-control": "no-cache" }, 466 }), 467 ); 468 } 469 470 // Una vez finalicen ambas llamadas, actualizamos el miniâcarrito en una sola llamada 471 jQuery.when 472 .apply(jQuery, ajaxCalls) 473 .done(function () { 474 jQuery.ajax({ 475 type: "POST", 476 url: urlAjax, 477 data: { action: "cambio_minicart" }, 478 success: function (response) { 479 jQuery("#mini-cart-content").html(response); 480 cambio_boton_minicart(); 481 cambio_cart(); 482 }, 483 }); 484 }) 485 .fail(function (error) { 486 }); 487 488 return false; 489}); 490 491// Confirmar compra en minicart 492jQuery(document).on( 493 "click", 494 "#mini-cart-content .confirmar-minicart", 495 function (e) { 496 e.preventDefault(); 497 498 var checkoutUrl = jQuery(this).attr("href"); 499 500 var loadingText = 501 document.documentElement.lang == "pt-PT" 502 ? '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ms-10">A carregar</span></div>' 503 : '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ms-10">Cargando</span></div>'; 504 505 jQuery("#mini-cart-content").html(loadingText); 506 507 window.location.href = checkoutUrl; 508 }, 509); 510 511jQuery(document).on("click", ".mini-cart .remove", function (e) { 512 e.preventDefault(); 513 514 // Capturamos el cart_item_key del producto (automower) que se quiere borrar 515 var removeButton = jQuery(this); 516 var automowerKey = removeButton.data("cart_item_key"); 517 518 // Antes de limpiar el miniâcarrito, buscamos si existe un Ãtem de instalación asociado 519 var installationKey = null; 520 var installationItem = jQuery( 521 '.mini-cart .mini-cart-item[data-installation="1"]', 522 ); 523 if (installationItem.length) { 524 installationKey = installationItem.data("cart_item_key"); 525 } 526 527 // Mostramos el indicador de carga en el miniâcarrito 528 var loadingText = 529 document.documentElement.lang == "pt-PT" 530 ? '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ml-10">A carregar</span></div>' 531 : '<div class="mini-cart-anim-carga"><span class="fas fa-spinner fa-spin"></span> <span class="d-ib ml-10">Cargando</span></div>'; 532 jQuery(".mini-cart").html(loadingText); 533 534 // Preparamos las llamadas AJAX de borrado sin actualizar el miniâcarrito de forma individual 535 var ajaxCalls = []; 536 537 // Llamada para borrar el automower 538 ajaxCalls.push( 539 jQuery.ajax({ 540 type: "POST", 541 url: urlAjax,
542 data: { action: "borrar_producto", id: automowerKey }, 543 dataType: "html", 544 cache: false, 545 headers: { "cache-control": "no-cache" }, 546 }), 547 ); 548 549 // Si se encontró una instalación asociada, preparamos su borrado también 550 if (installationKey) { 551 ajaxCalls.push( 552 jQuery.ajax({ 553 type: "POST", 554 url: urlAjax, 555 data: { action: "borrar_producto", id: installationKey }, 556 dataType: "html", 557 cache: false, 558 headers: { "cache-control": "no-cache" }, 559 }), 560 ); 561 } 562 563 // Una vez finalicen ambas llamadas, actualizamos el miniâcarrito en una sola llamada 564 jQuery.when 565 .apply(jQuery, ajaxCalls) 566 .done(function () { 567 jQuery.ajax({ 568 type: "POST", 569 url: urlAjax, 570 data: { action: "cambio_minicart" }, 571 success: function (response) { 572 jQuery(".mini-cart").html(response); 573 cambio_boton_minicart(); 574 cambio_cart(); 575 }, 576 }); 577 }) 578 .fail(function (error) { 579 }); 580 581 return false; 582}); 583 584/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Cambio de variación
585jQuery(document).on("click", ".cambio-variacion-alt", function (e) { 586 jQuery(this) 587 .siblings(".cambio-variacion-alt-select") 588 .removeClass("cambio-variacion-alt-select"); 589 jQuery(this).addClass("cambio-variacion-alt-select"); 590 var obj = "#" + jQuery(this).data("obj"); 591 var variation = jQuery(this).data("variation"); 592 jQuery(obj).val(variation); 593 jQuery(obj).change(); 594}); 595 596/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Cambio minicart 597 598function cambio_minicart() { 599 jQuery.ajax({ 600 type: "POST", 601 url: urlAjax, 602 data: { action: "cambio_minicart" }, 603 beforeSend: function (xhr) {}, 604 success: function (msg) { 605 jQuery("#mini-cart-content").html(msg); 606 }, 607 error: function (msg) { 608 msg; 609 }, 610 }); 611} 612 613/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Cambio minicart 614 615function cambio_cart() { 616 jQuery.ajax({ 617 type: "POST", 618 url: urlAjax, 619 data: { action: "cambio_cart" }, 620 beforeSend: function (xhr) {}, 621 success: function (msg) { 622 jQuery("#cart-total-content").html(msg); 623 }, 624 error: function (msg) { 625 msg; 626 }, 627 }); 628} 629 630/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Control boton carrito 631 632function cambio_boton_minicart() { 633 jQuery.ajax({ 634 type: "POST", 635 url: urlAjax, 636 data: { action: "cambio_boton_minicart" }, 637 beforeSend: function (xhr) { 638 jQuery(".mini-cart-btn-total").find(".label").css("display", "none"); 639 jQuery(".mini-cart-btn-cantidad").find(".label").css("display", "none"); 640 jQuery(".mini-cart-btn-total").find(".anim").css("display", "inherit"); 641 jQuery(".mini-cart-btn-cantidad").find(".anim").css("display", "inherit"); 642 }, 643 success: function (response) { 644 jQuery(".mini-cart-btn-total").find(".label").css("display", "inherit"); 645 jQuery(".mini-cart-btn-cantidad") 646 .find(".label") 647 .css("display", "inherit"); 648 jQuery(".mini-cart-btn-total").find(".label").html(response.total); 649 jQuery(".mini-cart-btn-cantidad").find(".label").html(response.cantidad); 650 jQuery(".mini-cart-btn-total").find(".anim").css("display", "none"); 651 jQuery(".mini-cart-btn-cantidad").find(".anim").css("display", "none"); 652 653 jQuery(".minicart-items-count .number").text(response.cantidad); 654 const badge = jQuery(".cart-count"); 655 badge.text(response.cantidad); 656 response.cantidad > 0 657 ? badge.removeClass("d-none") 658 : badge.addClass("d-none"); 659 660 //Actualizamos el chekout 661 if (jQuery(".woocommerce-checkout").length) { 662 jQuery(document.body).trigger("update_checkout"); 663 } 664 }, 665 error: function (msg) { 666 msg; 667 }, 668 }); 669} 670 671/////////////////////////////////////////////////////////////////////////////////////////////////////////////////Login 672 673jQuery(document).on("submit", ".woocommerce-form-login", function (e) { 674 var user = jQuery(this).find("#username").val(); 675 var pass = jQuery(this).find("#password").val(); 676 677 jQuery.ajax({ 678 type: "POST", 679 dataType: "json", 680 url: urlAjax, 681 data: { action: "woo_login", user: user, pass: pass }, 682 beforeSend: function (xhr) { 683 jQuery(".woocommerce-form-login-msj-corto").slideUp("fast"); 684 jQuery(".woocommerce-form-login__submit") 685 .find(".item-anim-carga") 686 .css("opacity", "1"); 687 }, 688 success: function (msg) { 689 jQuery(".woocommerce-form-login__submit") 690 .find(".item-anim-carga") 691 .css("opacity", "0"); 692 693 if (msg.loggedin == true) { 694 jQuery(".woocommerce-form-login-msj-corto").addClass( 695 "woocommerce-msj-corto-ok", 696 ); 697 } else { 698 jQuery(".woocommerce-form-login-msj-corto").addClass( 699 "woocommerce-msj-corto-error", 700 ); 701 } 702 703 jQuery(".woocommerce-form-login-msj-corto").html(msg.message); 704 jQuery(".woocommerce-form-login-msj-corto").slideDown("fast"); 705 706 if (msg.loggedin == true) { 707 eventLogintUser(msg.user); //Bysidecar 708 document.location.href = window.location; 709 } 710 }, 711 error: function (msg) { 712 msg; 713 }, 714 }); 715 716 e.preventDefault(); 717}); 718
719/////////////////////////////////////////////////////////////////////////////////////////////////////////////////GTM Productos 720 721var lista = "Lista genérica"; 722jQuery(document).ready(function () { 723 //Listas de productos 724 if (jQuery(".gtm-product-ficha").length) { 725 var products = []; 726 var products = []; 727 var pos = 1; 728 729 //Origen de la lista 730 if (jQuery(".single-product").length) { 731 lista = "Producto relacionado"; 732 } else if (jQuery(".search").length) { 733 lista = "Buscador"; 734 } else if (jQuery(".single-post").length) { 735 lista = "Blog"; 736 } 737 738 jQuery(".gtm-product-ficha").each(function (index) { 739 products.push({ 740 name: jQuery(this).data("gtm-product-name"), 741 id: jQuery(this).data("gtm-product-id"), 742 price: jQuery(this).data("gtm-product-price"), 743 category: jQuery(this).data("gtm-product-cat"), 744 position: pos, 745 list: lista, 746 stocklevel: jQuery(this).data("gtm-product-stocklevel"), 747 }); 748 749 pos++; 750 }); 751 752 dataLayer.push({ 753 event: "gtm-woo-impression", 754 ecommerce: { 755 currencyCode: "EUR", 756 impressions: products, 757 }, 758 }); 759 } 760}); 761 762//Click de producto 763jQuery(document).on("click", ".gtm-product-link", function (e) { 764 var datos_product = get_datos_product(jQuery(this).data("item-key")); 765 dataLayer.push({ 766 event: "gtm-woo-clickProduct", 767 ecommerce: { 768 click: { 769 actionField: { list: lista }, 770 products: [ 771 { 772 name: datos_product["name"], 773 id: datos_product["id"], 774 price: datos_product["price"], 775 category: datos_product["category"], 776 stocklevel: datos_product["stocklevel"], 777 }, 778 ], 779 }, 780 }, 781 }); 782}); 783 784//Vista de producto 785function gtm_view_product() { 786 var product = jQuery(".gtm-product-detalle"); 787 dataLayer.push({ 788 event: "gtm-woo-viewProduct", 789 ecommerce: { 790 detail: { 791 products: [ 792 { 793 name: product.data("gtm-product-name"), 794 id: product.data("gtm-product-id"), 795 price: product.data("gtm-product-price"), 796 category: product.data("gtm-product-cat"), 797 stocklevel: product.data("gtm-product-stocklevel"), 798 //'variant': variacion, 799 }, 800 ], 801 }, 802 }, 803 }); 804} 805 806function gtm_add_to_cart(itemKey, quantity) { 807 var datos_product = get_datos_product(itemKey); 808 dataLayer.push({ 809 event: "gtm-woo-addCart", 810 ecommerce: { 811 currencyCode: "EUR", 812 add: { 813 products: [ 814 { 815 name: datos_product["name"], 816 id: datos_product["id"], 817 price: datos_product["price"], 818 category: datos_product["category"], 819 quantity: quantity, 820 }, 821 ], 822 }, 823 }, 824 }); 825} 826 827// function gtm_remove_to_cart(itemKey) { 828// var datos_product = get_datos_product(itemKey); 829// dataLayer.push({ 830// event: "gtm-woo-removeCart", 831// ecommerce: { 832// remove: { 833// products: [ 834// { 835// name: datos_product["name"], 836// id: datos_product["id"], 837// price: datos_product["price"], 838// category: datos_product["category"], 839// quantity: datos_product["cantidad"], 840// }, 841// ], 842// }, 843// }, 844// }); 845// } 846 847//Recuperar datos de productos 848function get_datos_product(itemKey) { 849 var product = jQuery(".gtm-product-datos-" + itemKey); 850 var product_data = []; 851 product_data["name"] = product.data("gtm-product-name"); 852 product_data["id"] = product.data("gtm-product-id"); 853 product_data["price"] = product.data("gtm-product-price"); 854 product_data["category"] = product.data("gtm-product-cat"); 855 ((product_data["list"] = "Lista genérica"), 856 (product_data["stocklevel"] = product.data("gtm-product-stocklevel"))); 857 product_data["cantidad"] = product.data("gtm-product-cantidad"); 858 859 return product_data; 860} 861 862///////////////////////////////////////////////////////////////////////////////////////////////////////////Redimensionar slider accesorios en móvil 863jQuery(document).on( 864 "click", 865 'a[aria-controls="collapseAccesorios"]', 866 function (e) { 867 jQuery("#collapseAccesorios .slick-slider").slick("refresh"); 868 }, 869); 870 871jQuery(document).ready(function () { 872 // Cuando se encuentra una variación (al seleccionar una opción válida) 873 jQuery(document).on( 874 "found_variation", 875 ".variations_form", 876 function (event, variation) { 877 // Si la variación está en stock, ocultamos el mensaje 878 if (variation.is_in_stock) { 879 jQuery(".mensaje-variacion-agotada").hide(); 880 } else { 881 jQuery(".mensaje-variacion-agotada").show(); 882 } 883 }, 884 ); 885 886 // Cuando se reinicia la selección de variaciones 887 jQuery(document).on("reset_data", ".variations_form", function () { 888 jQuery(".mensaje-variacion-agotada").hide(); 889 }); 890}); 891 892jQuery(window).load(function () { 893 jQuery(".variations select").trigger("change"); 894}); 895// Actualizacion de CP de distribuidor 896jQuery(document).ready(function ($) { 897 // Función para encontrar el distribuidor más cercano 898 function obtenerDistribuidorCercano(postcode, distribuidoresFiltrados) { 899 var distribuidorMasCercano = null; 900 var distanciaMinima = Infinity; 901 902 // Recorremos los distribuidores para encontrar el más cercano 903 $.each(distribuidoresFiltrados, function (index, distribuidor) { 904 var distancia = Math.abs(distribuidor.codigo_postal - postcode); 905 906 if (distancia < distanciaMinima) { 907 distanciaMinima = distancia; 908 distribuidorMasCercano = distribuidor; 909 } 910 });
911 912 return distribuidorMasCercano ? distribuidorMasCercano.id : null; 913 } 914 915 // Escuchar cambios en el campo de código postal 916 $("#billing_postcode").on("change", function () { 917 var billing_postcode = $(this).val(); 918 919 // Asegurarse de que el código postal sea numérico 920 if ($.isNumeric(billing_postcode)) { 921 // Obtener el distribuidor más cercano 922 var distribuidorCercanoID = obtenerDistribuidorCercano( 923 billing_postcode, 924 distribuidores, 925 ); 926 927 // Actualizar el campo select de distribuidor si se encuentra uno cercano 928 if (distribuidorCercanoID) { 929 $("#order_distribuidor_referencia") 930 .val(distribuidorCercanoID) 931 .trigger("change"); 932 } 933 } 934 }); 935}); 936document.addEventListener("click", function (e) { 937 const toggle = e.target.closest(".combustion-info-toggle"); 938 if (!toggle) return; 939 940 const targetId = toggle.dataset.target; 941 const infoDiv = document.getElementById(targetId); 942 const chevron = toggle.querySelector(".combustion-chevron"); 943 if (!infoDiv) return; 944 945 const isOpen = infoDiv.style.display !== "none"; 946 infoDiv.style.display = isOpen ? "none" : "block"; 947 if (chevron) chevron.style.transform = isOpen ? "" : "rotate(180deg)"; 948}); 949// jQuery(document).ready(function ($) { 950// // Al cargar la página, oculta el botón de "Añadir al carrito" 951// $(".single_variation_wrap").hide(); 952 953// // Detecta cambios en las variaciones seleccionadas 954// $("form.variations_form").on("change", ".variations select", function () { 955// var allSelected = true; 956 957// // Verifica si todas las variaciones han sido seleccionadas 958// $("form.variations_form .variations select").each(function () { 959// if ($(this).val() === "") { 960// allSelected = false; 961// } 962// }); 963 964// // Si todas las variaciones están seleccionadas, muestra el botón de "Añadir al carrito" 965// if (allSelected) { 966// $(".single_variation_wrap").show(); 967// } else { 968// // Oculta el botón si falta alguna selección 969// $(".single_variation_wrap").hide(); 970// } 971// }); 972// });
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.