const navText = [ '', '' ]; class Web { static init() { Web.initDynamicBG(); ClassVehiculos.init(); $(document).ready(function (e) { $("html").addClass("loaded"); $('.selectpicker').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { if (isSelected === null) return; $(this).removeClass("error"); }); const btnSubir = $("#btn-subir"); let toScroll = null; $(window).scroll(function () { let scrollPosition = $(window).scrollTop(); if (scrollPosition > 300) { clearTimeout(toScroll); toScroll = setTimeout(function () { btnSubir.removeClass("d-none"); }, 100); } else { clearTimeout(toScroll); btnSubir.addClass("d-none"); } btnSubir.click(function () { clearTimeout(toScroll); window.scrollTo({top: 0, behavior: 'smooth'}); $(this).addClass("d-none"); }); }); new WOW( { boxClass: "title-animation", offset: 50, callback: function (box) { $(box).addClass("animate"); } } ).init(); }); } static initInicio() { } static initVenderCoche() { $(document).ready(function () { const formId = "vender-coche"; $.mask.definitions['l'] = "[A-Za-z]"; $(`#${formId}-matricula`).mask("9999-lll"); $('#vender-coche-marca').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { if (isSelected === null) return; const modeloElement = $("#vender-coche-modelo"); modeloElement.find("option:not(.bs-title-option)").remove(); modeloElement.selectpicker("refresh"); modeloElement.selectpicker("val", ""); var successCallback = function (data, textStatus, XMLHttpRequest) { if (data["error_number"] >= 0) { $.each(data["items"], function (i, e) { modeloElement.append($("").attr("value", e["id"]).text(e["nombre"])); }); modeloElement.selectpicker("refresh"); } }; Utils.sendStandardAjax(undefined, "https://www.leadercar.es/ajax/ModelosVentas.listado.php?marca=" + $("#vender-coche-marca").val(), { successCallback: successCallback, esperePorFavor: false, }); }); $("#btn-solicitar-tasacion").click(function (e) { var extraMsg = ""; if (!$("#politica-coche").is(":checked")) { extraMsg = $("#politica-coche").attr("title"); } Utils.sendStandardAjax(formId, "https://www.leadercar.es/ajax/VenderCoche.enviar.php", { extraErroresForm: extraMsg, successCallback: null, resetFormOnSuccess: true }); }); }); } static initDynamicBG() { $(document).ready(function () { new WOW( { boxClass: "dynamic-bg", //offset: 200, callback: function (box) { $(box).addClass("loaded"); }, } ).init(); }); } static initTexto() { $("document").ready(function () { //$(".textoSeccion a").attr("target", "_blank"); $(".textoSeccion a[href^='tel']").removeAttr("target"); $(".textoSeccion img[style^='float: left'], .textoSeccion img[style^='float:left']").addClass("margin-right-20 margin-bottom-20 img-float"); $(".textoSeccion img[style^='float: right'], .textoSeccion img[style^='float:right']").addClass("margin-left-20 margin-bottom-20 img-float"); $(".textoSeccion img:not(.imagenDerecha)").addClass("img-fluid").css("max-width", "100%").css("height", "auto").css("object-fit", "cover"); }); } static initBanner() { let owl = null; let timeout = null; $(document).ready(function () { if ($('#carousel-banner').length) { owl = $('#carousel-banner').owlCarousel({ animateOut: 'fadeOut', animateIn: 'fadeIn', loop: true, lazyLoad: true, //video:true, margin: 0, nav: true, dots: false, mouseDrag: false, smartSpeed: 900, autoplay: true, autoplayTimeout: 700000000, items: 1, navText: navText, onInitialized: onTranslated, onTranslated: onTranslated }); } $("#carousel-banner").on("click", ".owl-dots .owl-dot", function () { clearTimeout(timeout); }); }); function onTranslated() { if ($(".owl-item.active video").length > 0) { $(".owl-item video").each(function (index, value) { var isPlaying = this.currentTime > 0 && !this.paused && !this.ended && this.readyState > this.HAVE_CURRENT_DATA; if (isPlaying) { this.pause(); this.currentTime = 0; } }); $(".owl-item.active video").each(function (index, value) { playVideo(this); }); } else { if (timeout != null) clearTimeout(timeout); timeout = setTimeout(function () { owl.trigger('next.owl.carousel'); }, 7000); } } function playVideo(video) { var isPlaying = video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA; if (!isPlaying) { video.play(); video.onended = function (e) { owl.trigger('next.owl.carousel'); }; } } } static initResenas() { $(document).ready(function () { const elementCarousel = $("#valoraciones"); if (elementCarousel.length > 0) { let numItems = elementCarousel.find(".item-resena").length; elementCarousel.owlCarousel({ margin: 30, nav: false, navText: navText, dots: true, lazyLoad: true, stagePadding: 3, responsive: { 0: { items: 1, loop: numItems > 1, }, 768: { items: numItems > 1, loop: numItems > 1, stagePadding: numItems > 1 ? 60 : 0 }, 992: { items: numItems > 3 ? 1.5 : 2, loop: numItems > 3, }, 1200: { items: numItems > 4 ? 2.5 : 3, loop: numItems > 6, }, 1600: { items: 3, loop: numItems > 3, } } }); $("body").on("click", ".btn-mas-valoracion", function () { var padre = $(this).parents(".item-resena"); //$(padre).find(".valoracion-texto").addClass("d-none"); //$(padre).find(".valoracion-texto-completo").removeClass("d-none"); $("#bloque-resena .textoSeccion").html(padre.find(".valoracion-texto-completo").html()); ClassBlockUI.abrirBlockUIEstandar("bloque-resena", undefined, "Reseña de " + padre.find(".item-resena-usuario").text(), "modal622"); }); $("body").on("click", "#btn-cerrar-resena", function (e) { $(".modal").modal("hide"); }); } }); } static initClientesSatisfechos() { $(document).ready(function () { const elementCarousel = $("#clientes-satisfechos-owl"); if (elementCarousel.length > 0) { let numItems = elementCarousel.find(".caja-cliente").length; elementCarousel.owlCarousel({ margin: 30, nav: false, dots: true, responsive: { 0: { items: 1, loop: numItems > 1, }, 576: { items: 1, loop: numItems > 1, stagePadding: numItems > 1 ? 80 : 0 }, 768: { items: numItems > 1, loop: numItems > 1, stagePadding: numItems > 1 ? 160 : 0 }, 992: { items: 3, loop: numItems > 3, }, 1600: { items: 4, loop: numItems > 4, } } }); } }); } static initMedios() { $(document).ready(function () { const elementCarousel = $("#medios"); if (elementCarousel.length > 0) { let numItems = elementCarousel.find(".caja-medio").length; elementCarousel.owlCarousel({ margin: 30, nav: false, dots: true, autoplay: true, autoplayTimeout: 2500, responsive: { 0: { margin: 15, items: 2, loop: numItems > 2, }, 576: { margin: 15, items: 3, loop: numItems > 3, }, 992: { items: 4, loop: numItems > 4, }, 1200: { items: 5, loop: numItems > 5, } } }); } }); } static initFiltrosBuscador({ precioMinSeleccionado = 0, precioMaxSeleccionado = 150000, precioMin = 0, precioMax = 150000, cuotaMinSeleccionado = 0, cuotaMaxSeleccionado = 800, cuotaMin = 0, cuotaMax = 800, anyoMinSeleccionado = 1959, anyoMaxSeleccionado = new Date().getFullYear(), anyoMin = 1959, anyoMax = new Date().getFullYear(), kmMinSeleccionado = 0, kmMaxSeleccionado = 300000, kmMin = 0, kmMax = 300000, } = {} ) { $(document).ready(function (e) { $("#buscar").pressEnter(function (e) { $(".btn-buscar-coches").trigger("click"); }); const elementToggleExtraFiltros = $("#btn-toggle-extra-filtros"); const elementSliderPrecio = $("#slider-range-precio"); const elementSliderCuota = $("#slider-range-cuota-mensual"); const elementSliderAnyo = $("#slider-range-anyo"); const elementSliderKm = $("#slider-range-km"); $("#btn-abrir-filtros, #btn-cerrar-filtros").click(function (e) { $("#filtros-buscador").toggleClass("open"); }); elementToggleExtraFiltros.click(function (e) { $("#filtros-buscador").toggleClass("expand"); elementToggleExtraFiltros.toggleClass("active"); if ($(window).width() < 992 && elementToggleExtraFiltros.hasClass("active")) { var $precio = $("#banner #container-filtro-precio"); var $cuota = $("#banner #container-filtro-cuota"); if ($precio.length === 0 || $cuota.length === 0) return; if ($precio.parent().is("#filtros-buscador-top")) { $("#filtros-buscador-bottom").prepend($cuota).prepend($precio); } if ($(window).width() < 576) { var $modelo = $("#banner #container-filtro-modelo"); if ($modelo.parent().is("#filtros-buscador-top")) { $("#filtros-buscador-bottom").prepend($modelo); } } } }); elementSliderPrecio.slider({ range: true, min: precioMin, max: precioMax, step: 100, values: [precioMinSeleccionado, precioMaxSeleccionado], slide: function (event, ui) { $("#precio-min-label").html(Utils.number_format(ui.values[0], { numberOfDecimals: 0, thousandSeparator: "." }) + "€"); $("#precio-max-label").html(Utils.number_format(ui.values[1], { numberOfDecimals: 0, thousandSeparator: "." }) + "€"); }, stop: function (event, ui) { $("#precio-min-label").html(Utils.number_format(ui.values[0], { numberOfDecimals: 0, thousandSeparator: "." }) + "€"); $("#precio-max-label").html(Utils.number_format(ui.values[1], { numberOfDecimals: 0, thousandSeparator: "." }) + "€"); $("#precio-min").val(elementSliderPrecio.slider("values", 0)); $("#precio-max").val(elementSliderPrecio.slider("values", 1)); } }); elementSliderCuota.slider({ range: true, min: cuotaMin, max: cuotaMax, step: 20, values: [cuotaMinSeleccionado, cuotaMaxSeleccionado], slide: function (event, ui) { $("#cuota-min-label").html(Utils.number_format(ui.values[0], { numberOfDecimals: 0, thousandSeparator: "." }) + "€"); $("#cuota-max-label").html(Utils.number_format(ui.values[1], { numberOfDecimals: 0, thousandSeparator: "." }) + "€"); }, stop: function (event, ui) { $("#cuota-min-label").html(Utils.number_format(ui.values[0], { numberOfDecimals: 0, thousandSeparator: "." }) + "€"); $("#cuota-max-label").html(Utils.number_format(ui.values[1], { numberOfDecimals: 0, thousandSeparator: "." }) + "€"); $("#cuota-min").val(elementSliderCuota.slider("values", 0)); $("#cuota-max").val(elementSliderCuota.slider("values", 1)); } }); elementSliderAnyo.slider({ range: true, min: anyoMin, max: anyoMax, step: 1, values: [anyoMinSeleccionado, anyoMaxSeleccionado], slide: function (event, ui) { $("#anyo-min-label").html(ui.values[0]); $("#anyo-max-label").html(ui.values[1]); }, stop: function (event, ui) { $("#anyo-min-label").html(ui.values[0]); $("#anyo-max-label").html(ui.values[1]); $("#anyo-min").val(elementSliderAnyo.slider("values", 0)); $("#anyo-max").val(elementSliderAnyo.slider("values", 1)); } }); elementSliderKm.slider({ range: true, min: kmMin, max: kmMax, step: 200, values: [kmMinSeleccionado, kmMaxSeleccionado], slide: function (event, ui) { $("#km-min-label").html(Utils.number_format(ui.values[0], { numberOfDecimals: 0, thousandSeparator: "." }) + "km"); $("#km-max-label").html(Utils.number_format(ui.values[1], { numberOfDecimals: 0, thousandSeparator: "." }) + "km"); }, stop: function (event, ui) { $("#km-min-label").html(Utils.number_format(ui.values[0], { numberOfDecimals: 0, thousandSeparator: "." }) + "km"); $("#km-max-label").html(Utils.number_format(ui.values[1], { numberOfDecimals: 0, thousandSeparator: "." }) + "km"); $("#km-min").val(elementSliderKm.slider("values", 0)); $("#km-max").val(elementSliderKm.slider("values", 1)); } }); $(".btn-buscar-coches").click(function (e) { const buscar = $("#buscar").val(); const marca = $("#marca").val(); const modelo = $("#modelo").val(); const carroceria = $("#carroceria").val(); const etiqueta = $("#etiqueta").val(); const loMasBuscado = $("#lo-mas-buscado").val(); const precioMinUser = $("#precio-min").val() * 1; const precioMaxUser = $("#precio-max").val() * 1; const cuotaMinUser = $("#cuota-min").val() * 1; const cuotaMaxUser = $("#cuota-max").val() * 1; const combustible = $("#combustible").val(); const anyoMinUser = $("#anyo-min").val() * 1; const anyoMaxUser = $("#anyo-max").val() * 1; const kmMinUser = $("#km-min").val() * 1; const kmMaxUser = $("#km-max").val() * 1; const cambio = $("#cambio").val(); const orden = $("#filtro-ordenar").val(); const potenciaElement = $("#potencia"); let mainUrl = 'https://www.leadercar.es/comprar-vehiculo/'; if (marca !== "" && marca !== null) mainUrl += "marca-" + marca + "/"; if (modelo !== "" && modelo !== null) mainUrl += "modelo-" + modelo + "/"; if (carroceria !== "" && carroceria !== null) mainUrl += "tipo-vehiculo-" + carroceria + "/"; if (etiqueta !== "" && etiqueta !== null) mainUrl += "etiqueta-" + etiqueta + "/"; if (loMasBuscado !== "" && loMasBuscado !== null) mainUrl += "mas-buscado-" + loMasBuscado + "/"; let url = new URL(mainUrl); if (buscar !== "" && buscar !== undefined) { url.searchParams.append("buscar", buscar); } if ((precioMinUser !== precioMin || precioMaxUser !== precioMax) && precioMaxUser > 0) { url.searchParams.append("precio", precioMinUser + "-" + precioMaxUser); } if ((cuotaMinUser !== cuotaMin || cuotaMaxUser !== cuotaMax) && cuotaMaxUser > 0) { url.searchParams.append("cuota", cuotaMinUser + "-" + cuotaMaxUser); } if ((anyoMinUser !== anyoMin || anyoMaxUser !== anyoMax) && anyoMaxUser > 0) { url.searchParams.append("anyo", anyoMinUser + "-" + anyoMaxUser); } if ((kmMinUser !== kmMin || kmMaxUser !== kmMax) && kmMaxUser > 0) { url.searchParams.append("kilometros", kmMinUser + "-" + kmMaxUser); } if (combustible !== "" && combustible !== null) { url.searchParams.append("combustible", combustible); } if (cambio !== "" && cambio !== null) { url.searchParams.append("cambio", cambio); } const potenciaMin = potenciaElement.find("option:selected").data("min"); const potenciaMax = potenciaElement.find("option:selected").data("max"); if (potenciaMin > 0) url.searchParams.append("potencia-min", potenciaMin); if (potenciaMax > 0) url.searchParams.append("potencia-max", potenciaMax); if (orden !== "" && orden !== null && orden !== undefined) { url.searchParams.append("orden", orden); } window.location.href = url.toString(); }); $('#marca').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { if (isSelected === null) return; const modeloElement = $("#modelo"); modeloElement.find("option:not(.bs-title-option)").not(":first").remove(); modeloElement.selectpicker("refresh"); modeloElement.selectpicker("val", ""); var successCallback = function (data, textStatus, XMLHttpRequest) { if (data["error_number"] >= 0) { $.each(data["items"], function (i, e) { modeloElement.append($("").attr("value", e["url"]).text(e["nombre"])); }); modeloElement.selectpicker("refresh"); } }; Utils.sendStandardAjax(undefined, "https://www.leadercar.es/ajax/Modelos.listado.php?marca=" + $("#marca").val(), { successCallback: successCallback, esperePorFavor: false, }); }); }); } static initCompartir() { $(document).ready(function (e) { $(".compartir").jsSocials({ showCount: false, showLabel: true, shareIn: "popup", shares: [ {share: "twitter", logo: "fab fa-twitter", label: "Post"}, { share: "facebook", label: "Compartir", logo: "fab fa-facebook" }, {share: "pinterest", label: "Pin it", logo: "fab fa-pinterest"}, ] }); $(".fa.fa-facebook").removeClass("fa").addClass("fab").addClass("fa-facebook-f"); $(".fa.fa-twitter").removeClass("fa").addClass("fab"); /* $(".fa.fa-google").removeClass("fa").addClass("fab").addClass("fa-google-plus-g");*/ $(".fa.fa-pinterest").removeClass("fa").addClass("fab"); //$('
' + // '' + // '' + // '//' + // '' + // '
').appendTo('.jssocials-shares'); }); } static initContacto() { $(document).ready(function (e) { $("#btnEnviarContacto").click(enviarFormulario); }); function enviarFormulario(event) { event.preventDefault(); var extraMsg = ""; if (!$("#politica").is(":checked")) { extraMsg = $("#politica").attr("title"); } Utils.sendStandardAjax("formContacto", "https://www.leadercar.es/ajax/Contacto.enviar.php", { extraErroresForm: extraMsg, successCallback: null, resetFormOnSuccess: true }); } } } function findPos(obj) { var curtop = 0; if (obj.offsetParent) { do { curtop += obj.offsetTop; } while (obj = obj.offsetParent); return [curtop]; } } function isEmail(email) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); } function preparaLugar(pais, provincia, poblacion, idInputPais, idInputProvincia, idInputLocalidad) { if (pais > 0) { if (provincia > 0) provincia = (provincia + "").padStart(2, "0"); actualizaProvincias(idInputLocalidad, idInputProvincia, idInputPais, provincia, pais, provincia, poblacion, undefined); } $('#' + idInputPais).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { //console.log(e, clickedIndex, isSelected, previousValue, $(this).val(), $('#frmServicioProvincia').val(), $('#frmServicioProvincia').selectpicker("val")); actualizaProvincias(idInputLocalidad, idInputProvincia, idInputPais, provincia, undefined, undefined, undefined, undefined, undefined, undefined, true); }); /*$("body").on("change", "#"+idInputPais, function() { actualizaProvincias(idInputLocalidad,idInputProvincia, idInputPais, provincia); });*/ if (provincia > 0) { if (poblacion > 0) poblacion = (poblacion + "").padStart(3, "0"); actualizaCiudades(idInputLocalidad, idInputProvincia, idInputPais, poblacion, pais, provincia, poblacion, $("#" + idInputProvincia).val() * 1); } $('#' + idInputProvincia).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { //console.log(e, clickedIndex, isSelected, previousValue, $(this).val(), $('#frmServicioProvincia').val(), $('#frmServicioProvincia').selectpicker("val")); if (isSelected === null) return; $('#' + idInputProvincia).removeClass("error"); actualizaCiudades(idInputLocalidad, idInputProvincia, idInputPais, undefined, $("#" + idInputPais).val() * 1, $("#" + idInputProvincia).val() * 1); }); $('#' + idInputLocalidad).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { if (isSelected === null) return; $('#' + idInputLocalidad).removeClass("error"); }); } function actualizaProvincias(idCampoLocalidad, idCampoRegion, idCampoPais, idRegionPreEstablecida, forceIdPais, forceIdRegion, forceIdLocalidad, onFinish, textoSelect, textoLoading, actualizarLocalidad) { if (forceIdPais == undefined) { forceIdPais = $("#" + idCampoPais).val(); } if (forceIdRegion == undefined) { forceIdRegion = $("#" + idCampoRegion).val(); } if (forceIdLocalidad == undefined) { forceIdLocalidad = $("#" + idCampoLocalidad).val(); } if (textoSelect == undefined) { //textoSelect = ""; textoSelect = ""; } //var textoSelectLoc = ""; var textoSelectLoc = ""; if (textoLoading == undefined) { textoLoading = ""; } var data = {idPais: forceIdPais}; $("#" + idCampoRegion).empty(); $("#" + idCampoRegion).append(""); $("#" + idCampoRegion).selectpicker("refresh"); $("#" + idCampoRegion).selectpicker('val', 0); if (actualizarLocalidad) { $("#" + idCampoLocalidad).empty(); $("#" + idCampoLocalidad).append(""); $("#" + idCampoLocalidad).selectpicker("refresh"); $("#" + idCampoLocalidad).selectpicker('val', 0); } var returned = $.ajax( { url: "https://www.leadercar.es/ajax/Ubicacion.listadoRegiones.php?CSRF=" + CSRF, type: "POST", dataType: "json", data: data, error: function (XMLHttpRequest, textStatus, errorThrown) { //ClassBlockUI.abrirBlockUIEstandarMensaje(XMLHttpRequest.responseText, true); }, success: function (data) { $("#" + idCampoRegion).empty(); $("#" + idCampoRegion).append(""); for (var index in data) { $("#" + idCampoRegion).append(""); } $("#" + idCampoRegion).selectpicker("refresh"); if (idRegionPreEstablecida != undefined && idRegionPreEstablecida != "") { $("#" + idCampoRegion).val(idRegionPreEstablecida); } else { $("#" + idCampoRegion).val(0); } $("#" + idCampoRegion).selectpicker("refresh"); if (actualizarLocalidad) { $("#" + idCampoLocalidad).empty(); $("#" + idCampoLocalidad).append(""); $("#" + idCampoLocalidad).val(0); $("#" + idCampoLocalidad).selectpicker("refresh"); } if (onFinish != undefined && typeof (onFinish) == "function") { onFinish(); } } }); } function actualizaCiudades(idCampoLocalidad, idCampoRegion, idCampoPais, idLocalidadPreEstablecida, forceIdPais, forceIdRegion, forceIdLocalidad, onFinish, textoSelect, textoLoading) { if (forceIdPais == undefined) { forceIdPais = $("#" + idCampoPais).val(); } if (forceIdRegion == undefined) { forceIdRegion = $("#" + idCampoRegion).val(); } if (forceIdLocalidad == undefined) { forceIdLocalidad = $("#" + idCampoLocalidad).val(); } if (textoSelect == undefined) { //textoSelect = ""; textoSelect = ""; } if (textoLoading == undefined) { textoLoading = ""; } var data = { idPais: forceIdPais, idRegion: forceIdRegion }; $("#" + idCampoLocalidad).empty(); $("#" + idCampoLocalidad).append(""); $("#" + idCampoLocalidad).selectpicker("refresh"); $("#" + idCampoLocalidad).selectpicker('val', 0); var returned = $.ajax( { url: "https://www.leadercar.es/ajax/Ubicacion.listadoCiudades.php?CSRF=" + CSRF, type: "POST", dataType: "json", data: data, error: function (XMLHttpRequest, textStatus, errorThrown) { //ClassBlockUI.abrirBlockUIEstandarMensaje(XMLHttpRequest.responseText, true); }, success: function (data) { $("#" + idCampoLocalidad).empty(); $("#" + idCampoLocalidad).append(""); for (var index in data) { $("#" + idCampoLocalidad).append(""); } $("#" + idCampoLocalidad).selectpicker("refresh"); if (idLocalidadPreEstablecida != undefined) { $("#" + idCampoLocalidad).val(idLocalidadPreEstablecida); } else { $("#" + idCampoLocalidad).val(0); } $("#" + idCampoLocalidad).selectpicker("refresh"); if (onFinish != undefined && typeof (onFinish) == "function") { onFinish(); } } }); } class Chatbot { constructor() { this.$chatContainer = $("#chatbot-contiene-chat"); this.$messages = $("#chatbot-contiene-chats"); this.currentStep = "start"; this.data = {}; this.flow = this.buildFlow(); this.bindHeaderButtons(); $("#btn-chatbot, .btn-chatbot").click(() => this.$chatContainer.toggleClass("d-none")); $("#chatbot-btn-cerrar, #chatbot-bienvenida-footer button, #btn-chatbot").click(() => $("#chatbot-contiene-bienvenida").remove()); $("#chatbot-bienvenida-footer button").click((event, element) => { this.$chatContainer.removeClass("d-none"); const text = $(event.currentTarget).hasClass("btn-chatbot-comprar") ? "Comprar Coche" : "Vender Coche"; const $block = this.$messages.find(".item-mensaje-opcs").last(); this.userReply(text, $block); }); } buildFlow() { const tiposVehiculo = ["Berlina","Coup\u00e9","Monovol\u00famen","4x4 Suv","Cabrio","Familiar","Industrial","Cl\u00e1sico"]; const marcas = ["Abarth","AC","Acura","Adam","Aion","Aito","Aiways","Aixam","Alfa Romeo","Alpina","Alpine","Amberauto","Ambertruck","Apal","Arcfox","Ariel","Aro","Asia","Aston Martin","ATOM","Audi","Aurus","Avatr","Baic","Bajaj","Baltijas Dzips","Baojun","Batmobile","BAW","Belgee","Bentley","Bestune","Bilenkin","Bio auto","Blaval","BMW","Borgward","Brabus","Brilliance","Bristol","Bufori","Bugatti","Buick","BYD","Byvin","Cadillac","Callaway","Caterham","Chana","Changan","ChangFeng","Changhe","Chery","CheryExeed","Chevrolet","Chrysler","Ciimo","Citroen","Coda","Coggiola","Combat","Cowin","Cupra","Dacia","Dadi","Daewoo","Daihatsu","Daimler","Dallara","Datsun","Dayun","De Tomaso","Delage","Denza","Derways","DFSK","Dodge","DongFeng","Dongfeng Forthing","Doninvest","Donkervoort","DR","DS","DW Hower","E-Car","Enoreve","Enovate","Eonyx","Everus","Evolute","EXEED","Exlantix","FAW","Fengon","Ferrari","Fiat","Fisker","Flanker","Ford","Foton","FSO","Fuqi","GAC","GAZ","Geely","Genesis","Geo","GMA","GMC","Gonow","Gordon","Great Wall","Hafei","Haima","Hanteng","Haval","Hawtai","Hedmos","Hennessey","Hindustan","HiPhi","Holden","Honda","Hongqi","Hozon","HSV","Huaihai (Hoann)","HuangHai","Huazi","Hummer","Hycan","Hyperion","Hyundai","iCar","iCaur","IM Motors (Zhiji)","Ineos","Infiniti","Invicta","Iran Khodro","Isuzu","IVECO","IZH","JAC","Jaecoo","Jaguar","Jeep","Jensen","Jetour","Jetta","Jiangnan","Jidu","Jinbei","JMC","JMEV","Jonway","Kaiyi","Kanonir","Karma","Kawei","KG Mobility","KGM","Kia","Knewstar","Koenigsegg","KTM AG","KYC","Lamborghini","Lancia","Land Rover","Landwind","Leapmotor","Letin","LEVC","Lexus","Lifan","Ligier","Lincoln","lingxi","Livan","LiXiang","Logem","Lotus","LTI","Lucid","Luxeed","Luxgen","Lynk & Co","M-Hero","Maextro","Mahindra","Maple","Marcos","Marlin","Marussia","Maruti","Maserati","Maxeed","Maxus","Maybach","Mazda","McLaren","Mega","Mercedes-Benz","Mercury","Metrocab","MG","Micro","Microcar","Minelli","Mini","Mitsubishi","Mitsuoka","Mobilize","Morgan","Moskvich","Nio","Nissan","Noble","Nordcross","Oldsmobile","Omoda","Opel","ORA","Orange","Osca","Oshan","Oting","Pagani","Panoz","Perodua","Peugeot","PGO","Plymouth","Polestar","Pontiac","Porsche","Proton","Punk","Qiantu","Qingling","Qiyuan","Qoros","Qvale","Racing car","Radar","Radford","RAM","Ravon","Renaissance","Renault","Renault Samsung","Rezvani","Rimac","Rinspeed","Rising Auto","Rivian","Roewe","Rolls-Royce","Ronart","Rossa","Rover","Rox","Saab","SAIC","Saipa","Saleen","Samsung","Sandstorm","Saturn","Scion","Scout","SEAT","Seres","Seres Aito","Shanghai Maple","Shifeng","ShuangHuan","Skoda","Skywell","Skyworth","SMA","Smart","Solaris","Sollers","Soueast","Spectre","Spyker","SsangYong","Stelato","Subaru","Suzuki","SWM","TagAZ","Tank","Tata","Tatra","Tazzari","Tenet","Tesla","Thairung","Think","Tianma","Tofas","Toyota","Tramontana","Trumpchi","TVR","UAZ","Ultima","Vauxhall","VAZ (Lada)","Vector","Venucia","VGV","VinFast","Volga","Volkswagen","Volvo","Vortex","Voyah","VUHL","W Motors","Weltmeister","WEY","Wiesmann","Wuling","Xcite","XEV","Xiaomi","XiaoPaoChe (SSC)","Xin Kai","Xpeng","Yema","Yipai","Yo-mobil","Zastava","ZAZ","Zeekr","Zenos","Zenvo","Zhido","Zibar","Zotye","ZX"]; const kilometros = [ "0 - 20.000 km", "20.000 - 40.000 km", "40.000 - 60.000 km", "60.000 - 80.000 km", "80.000 - 100.000 km", "100.000 - 125.000 km", "125.000 - 150.000 km", "150.000 - 200.000 km", "200.000 - 300.000 km", "+300.000 km" ]; const currentYear = new Date().getFullYear(); const years = Array.from( { length: currentYear - 2000 + 1 }, (_, i) => 2000 + i ); return { start: { text: "¡Hola! Bienvenid@ a Leadercar
¿Cómo podemos ayudarte?", type: "buttons", field: "accion", options: ["Comprar Coche", "Vender Coche"], next: v => v === "Comprar Coche" ? "buy_type_text1" : "sell_type_text1" }, // ===== COMPRAR ===== buy_type_text1: { text: "¡Genial, estás en el lugar correcto! ✅", type: "auto-text", next: "buy_type_question" }, buy_type_question: { text: "¿Qué tipo de vehículo te interesa?", type: "buttons", field: "tipo", options: tiposVehiculo, next: "buy_brand" }, buy_brand: { text: "Excelente, ¿En qué marca/s estás interesado?", type: "select", field: "marca", options: marcas, placeholder: "Seleccione una opción", next: "buy_model" }, buy_model: { text: "¿Qué modelo/s estás buscando?", type: "text", field: "modelo", placeholder: "Modelo", next: "buy_budget" }, buy_budget: { text: "¿Cuál es tu presupuesto?", type: "select", field: "presupuesto", options: [ "Menos de 10.000€", "10.000€ – 20.000€", "20.000€ – 30.000€", "Más de 30.000€" ], placeholder: "Seleccione una opción", next: "buy_tradein" }, buy_tradein: { text: "¿Quieres entregar un coche como parte del pago?", type: "buttons", field: "entrega_coche", options: ["Si", "No"], next: "buy_contact_intro" }, buy_contact_intro: { text: "¡Genial, ya lo tenemos! ✅
Deja tus datos de contacto aquí", type: "form", field: "contacto", next: "buy_contact_pref" }, buy_contact_pref: { text: "Por último, ¿cómo prefieres que te contactemos?", type: "buttons", field: "preferencia_contacto", options: ["Llamada", "WhatsApp"], next: "buy_contact_time" }, buy_contact_time: { text: "¿Cuándo prefieres que te llamemos?", type: "buttons", field: "horario_contacto", options: ["Por la mañana", "Por la tarde"], next: "buy_end" }, buy_end: { text: "¡Muchas gracias! Nuestro equipo comercial se pondrá en contacto contigo lo antes posible.", type: "end" }, // ===== VENDER (placeholder) ===== sell_type_text1: { text: "¡Genial, estás en el lugar correcto! ✅", type: "auto-text", next: "sell_type_text2" }, sell_type_text2: { text: "En Leadercar te ayudaremos a vender tu vehículo. Vamos a hacerte algunas preguntas sobre tu vehículo 🚗", type: "auto-text", next: "sell_brand" }, sell_brand: { text: "¿De qué marca es tu coche?", type: "select", field: "marca", options: marcas, placeholder: "Seleccione una opción", next: "sell_model" }, sell_model: { text: "¿Qué modelo es tu coche?", type: "text", field: "modelo", placeholder: "Modelo", next: "sell_licence_plate" }, sell_licence_plate: { text: "¿Cuál es la matrícula de tu vehículo?", type: "text", field: "matricula", placeholder: "Ej: 1234-ABC, V 1234 AB...", next: "sell_kilometers" }, sell_kilometers: { text: "¿Cuántos km tiene hechos el vehículo?", type: "select", field: "kilometros", options: kilometros, placeholder: "Seleccione una opción", next: "sell_year" }, sell_year: { text: "¿Cuándo se matriculó el vehículo?", type: "select", field: "anyo", options: years, placeholder: "Seleccione una opción", next: "sell_tradein" }, sell_tradein: { text: "¿Quieres vender tu coche para comprar otro a cambio?", type: "buttons", field: "vender_para_comprar", options: ["Si", "No"], next: "sell_when" }, sell_when: { text: "Por último, ¿cuándo tienes planeado vender tu vehículo?", type: "buttons", field: "cuando_planea_vender", options: ["Lo antes posible", "Dentro de un mes", "No lo sé"], next: "sell_contact_intro" }, sell_contact_intro: { text: "¡Genial, ya lo tenemos! ✅
Deja tus datos de contacto aquí", type: "form", field: "contacto", next: "sell_end" }, sell_end: { text: "¡Muchas gracias! Nuestro equipo comercial se pondrá en contacto contigo lo antes posible.", type: "end" } }; } async start() { await this.renderStep("start"); } async reset() { this.$messages.empty(); this.currentStep = "start"; this.data = {}; await this.renderStep("start"); } bindHeaderButtons() { $("#chatbot-btn-reset-chat").on("click", () => this.reset()); $("#chatbot-btn-close-chat").on("click", () => this.$chatContainer.addClass("d-none")); } addMessage(text, sender = "machine") { const html = `
${text}
`; this.$messages.append(html); this.scrollBottom(); } addMessageDelayed(text, sender = "machine", delay = 200) { return new Promise(resolve => { setTimeout(() => { this.addMessage(text, sender); resolve(); }, delay); }); } scrollBottom() { this.$messages.scrollTop(this.$messages[0].scrollHeight); } async renderStep(stepKey) { this.currentStep = stepKey; const step = this.flow[stepKey]; if (!step) return; if(step.type === "auto-text"){ await this.addMessageDelayed(step.text, "machine"); if(step.next) await this.renderStep(step.next); return; } // Mensaje normal con delay if(step.text){ await this.addMessageDelayed(step.text, "machine"); } let html = ""; if (step.type === "buttons") { html += `
`; step.options.forEach(o => { html += ``; }); html += `
`; } if (step.type === "select") { html += `
`; } if (step.type === "text") { html += `
`; } if (step.type === "form") { html += `
`; } if (html) { await this.sleep(100); this.$messages.append(html); this.bindInputEvents(step); this.scrollBottom(); } } bindInputEvents(step) { const $block = this.$messages.find(".item-mensaje-opcs").last(); if (step.type === "form") { $block.find(".item-mensaje-btn-continuar").click(() => { const data = {}; $block.find("input").each(function () { let val = $(this).val(); if($(this).is(":checkbox")){ val = $(this).is(":checked") ? 1 : 0; } data[$(this).data("field")] = val; }); var errors = ""; if (data.nombre.length < 2) errors += (errors ? "
" : "")+"Debe introducir el nombre"; if (data.apellidos.length < 2) errors += (errors ? "
" : "")+"Debe introducir sus apellidos"; if (data.telefono.length < 9) errors += (errors ? "
" : "")+"Debe introducir el número de teléfono"; if (!isEmail(data.email)) errors += (errors ? "
" : "")+"Debe introducir un e-mail correcto"; if (data.politica !== 1) errors += (errors ? "
" : "")+"Debe aceptar la Política de privacidad de Datos y la Política de Cookies"; if (errors) { ClassBlockUI.abrirBlockUIEstandarMensaje(errors, true); return; } this.userReply(data, $block); }); return; } $block.find(".item-mensaje-opc-btn").click(e => { const val = $(e.target).text(); this.userReply(val, $block); }); $block.find(".item-mensaje-btn-continuar").click(() => { let val = ""; if (step.type === "select") val = $block.find("select.item-mensaje-select").val(); if (step.type === "text") val = $block.find(".item-mensaje-inp").val(); if (!val) return; this.userReply(val, $block); }); $(".item-mensaje-select.selectpicker").selectpicker(); } userReply(val, $block) { const step = this.flow[this.currentStep]; if (step.field) { this.data[step.field] = val; } $block.remove(); let display = val; if (typeof val === "object") { display = val.nombre + " " + val.apellidos; display += "
"+val.telefono; display += "
"+val.email; } this.addMessage(display, "user"); this.goNext(val); } goNext(val) { const step = this.flow[this.currentStep]; let next = step.next; if (typeof next === "function") next = next(val); if (next) { this.renderStep(next); } if (next === "buy_end" || next === "sell_end") { this.sendLead(); } } sendLead() { let formData = objectToFormData(this.data); ClassBlockUI.abrirBlockUIEsperePorFavor(); $.ajax({ url: 'https://www.leadercar.es/ajax/Chatbot.enviar.php', type: 'POST', dataType: "json", data: formData, cache: false, contentType: false, processData: false, success: function(data) { $(".modal").modal("hide"); ClassBlockUI.abrirBlockUIEstandarMensaje(data["error_message"], true); } }); } sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } } function objectToFormData(obj, formData = new FormData(), parentKey = '') { if (obj === null || obj === undefined) return formData; Object.keys(obj).forEach((key) => { const value = obj[key]; if (value === undefined) return; const formKey = parentKey ? `${parentKey}[${key}]` : key; if ( typeof value === 'object' && !(value instanceof File) && !(value instanceof Blob) && !(value instanceof Date) ) { objectToFormData(value, formData, formKey); } else { formData.append(formKey, value); } }); return formData; } $(document).ready(async () => { const bot = new Chatbot(); await bot.start(); }); var ClassVehiculos = { init: function () { $(document).ready(function (e) { ClassVehiculos.actualizarCuentaAtras(); setInterval(ClassVehiculos.actualizarCuentaAtras, 1000); ClassVehiculos.initFavoritos(); }); }, initComprarCoche: function (filtros, page = 1) { $(document).ready(function (e) { const body = $("body"); body.on("click", ".mostrar-mas-resultados .btn-mostrar-mas", function () { $(this).prop("disabled", true); page++; cargarVehiculos(); }); body.find('.container-ordenar select.filtro-ordenar').change(function () { page = 1; cargarVehiculos(); }); $(".item-criterio-eliminar").on("click", function () { const id = $(this).attr("data-id"); $.each(id.split(","), function (i, e) { const element = $("#" + e); if (element.length > 0) { if (element.hasClass("selectpicker")) { element.val(-1); element.selectpicker("refresh"); } else if (element.is(":checkbox")) { element.prop("checked", false); } else { element.val(""); } $(".btn-buscar-coches").trigger("click"); } }); }); function cargarVehiculos() { const resultadosElement = $(".resultados-vehiculos"); const ordenElement = $("#filtro-ordenar"); const mostrarMasBloque = $(".mostrar-mas-resultados"); const btnMostrarMas = mostrarMasBloque.find(".btn-mostrar-mas"); const txtMostrarMas = mostrarMasBloque.find(".mostrar-mas-resultados-txt"); var successCallback = function (data, textStatus, XMLHttpRequest) { $(".modal").modal("hide"); if (data["error_number"] >= 0) { if (page === 1) resultadosElement.html(""); resultadosElement.append(data["vehiculos"]); $(".tooltipStandard").not(".tooltipstered").tooltipster({ animation: 'grow', interactive: true, position: 'bottom', contentAsHTML: true }); btnMostrarMas.attr("disabled", false); if (data["numPages"] <= page) { mostrarMasBloque.addClass("d-none"); } else { mostrarMasBloque.removeClass("d-none"); } txtMostrarMas.text("%numActual% de %numTotales%".replace("%numActual%", data["numMostrando"]).replace("%numTotales%", data["numTotales"])); } }; Utils.sendStandardAjax(null, "https://www.leadercar.es/ajax/Vehiculos.cargar.php", { successCallback: successCallback, esperePorFavor: false, prepareFormData: function () { let formData = new FormData(); formData.append("page", page.toString()); formData.append("orden", ordenElement.val()); formData.append("filtros", filtros); return formData; }, }); } }); }, initFicha: function (precio, datosFinanciacion) { $(document).ready(function () { $("#btn-abre-video").click(function () { let videoid = $(this).attr("data-codigo")+"?autoplay=1&rel=0"; $("#bloque-video iframe").remove(); $('') .attr("src", "https://www.youtube-nocookie.com/embed/" + videoid) .attr("allow", "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share") .appendTo("#bloque-video"); ClassBlockUI.abrirBlockUIEstandar("bloque-video", function(){$("#bloque-video iframe").remove();$("#blockUI_bloque-video").modal("hide")}, "", "modal-video"); }); $("#btn-abre-360").click(function () { const url = $(this).attr("data-url"); pannellum.viewer('panorama', { type: 'equirectangular', panorama: url, autoLoad: true }); ClassBlockUI.abrirBlockUIEstandar("modal-360", undefined, "", "modal1300 modal-video"); }); $("#btn-compartir").click(function () { ClassBlockUI.abrirBlockUIEstandar("modal-compartir", undefined, "Compartir anuncio", "modal459"); }); $(".compartir-copiar").click(function () { const url = window.location.href; const btn = this; navigator.clipboard.writeText(url).then(function () { mostrarToast('¡Enlace copiado al portapapeles!'); // Opcional: cambiar texto del botón temporalmente const textoOriginal = btn.innerHTML; btn.innerHTML = '¡Copiado!'; setTimeout(() => btn.innerHTML = textoOriginal, 1000); }).catch(function () { mostrarToast('No se pudo copiar, usa Ctrl+C', 'error'); }); }); $("#btn-abre-avisame").click(function () { $("#id-vehiculo-avisame").val($(this).attr("data-id")); ClassBlockUI.abrirBlockUIEstandar("modal-avisame", undefined, "Avisame", "modal681"); }); $("#btn-enviar-avisame").click(function () { var extraMsg = ""; if (!$("#politica-avisame").is(":checked")) { extraMsg = $("#politica-avisame").attr("title"); } Utils.sendStandardAjax("modal-avisame", "https://www.leadercar.es/ajax/Vehiculo.avisame.php", { extraErroresForm: extraMsg, successCallback: function (data, textStatus, XMLHttpRequest) { if (data["error_number"] >= 0) { $(".modal").modal("hide"); $("#modal-avisame")[0].reset(); ClassBlockUI.abrirBlockUIEstandarMensaje(data["error_message"], true); } else { ClassBlockUI.abrirBlockUIEstandarMensaje(data["error_message"], true); } }, resetFormOnSuccess: true }); }); $("#btn-abre-mas-informacion").click(function () { $("#id-vehiculo-info").val($(this).attr("data-id")); ClassBlockUI.abrirBlockUIEstandar("modal-mas-informacion", undefined, "Más Información", "modal681"); }); $("#btn-enviar-mas-informacion").click(function () { var extraMsg = ""; if (!$("#politica-info").is(":checked")) { extraMsg = $("#politica-info").attr("title"); } Utils.sendStandardAjax("modal-mas-informacion", "https://www.leadercar.es/ajax/Vehiculo.masInformacion.php", { extraErroresForm: extraMsg, successCallback: function (data, textStatus, XMLHttpRequest) { if (data["error_number"] >= 0) { $(".modal").modal("hide"); $("#modal-mas-informacion")[0].reset(); ClassBlockUI.abrirBlockUIEstandarMensaje(data["error_message"], true); } else { ClassBlockUI.abrirBlockUIEstandarMensaje(data["error_message"], true); } }, resetFormOnSuccess: true }); }); $("#entrega-leadercar, #entrega-domicilio").change(function () { const entrega = $(this).val() * 1; const entregaLeadercar = $("#entrega-leadercar"); const entregaDomicilio = $("#entrega-domicilio"); if (entrega === 1) { entregaLeadercar.prop("checked", true); entregaDomicilio.prop("checked", false); $(".consultar").addClass("d-none"); $(".gratis-gratis").removeClass("d-none"); } else if (entrega === 2) { entregaDomicilio.prop("checked", true); entregaLeadercar.prop("checked", false); $(".consultar").removeClass("d-none"); $(".gratis-gratis").addClass("d-none"); } }); const elementCarouselFotosPrincipal = $("#ficha-vehiculo-foto-principal"); let numItems = elementCarouselFotosPrincipal.find(".item-foto").length; elementCarouselFotosPrincipal.owlCarousel({ margin: 18, nav: false, dots: false, navText: navText, stagePadding: 1, lazyLoad: true, items: 1, loop: numItems > 1, drag: numItems > 1, responsive: { 0: { items: 1, nav: true, }, 576: { items: 1, } } }); const elementCarouselFotosSecundarias = $("#ficha-vehiculo-otras-fotos"); let numItemsSec = elementCarouselFotosSecundarias.find(".item-foto").length; elementCarouselFotosSecundarias.owlCarousel({ margin: 12, nav: false, navText: navText, dots: false, stagePadding: 1, //lazyLoad: true, items: 1, responsive: { 0: { items: 3, loop: numItemsSec > 3, }, 576: { items: 3, loop: numItemsSec > 3, stagePadding: numItemsSec > 3 ? 40 : 0, }, 768: { items: 4, loop: numItemsSec > 4, stagePadding: numItemsSec > 4 ? 40 : 0, }, 992: { items: 5, loop: numItemsSec > 5, stagePadding: numItemsSec > 5 ? 40 : 0, } } }); elementCarouselFotosPrincipal.on("click", ".item-foto", function (e) { e.preventDefault(); const fotoId = $(this).data("foto"); const $items = $("#gallery-dimbox a"); const $item = $items.filter(`[data-foto="${fotoId}"]`); if ($item.length === 0) return; const index = $items.index($item); const dataSource = []; $items.each(function () { const $a = $(this); dataSource.push({ src: $a.attr("href"), width: $a.data("width"), height: $a.data("height") }); }); const pswp = new PhotoSwipe({ dataSource: dataSource, index: index }); pswp.init(); }); elementCarouselFotosPrincipal.on("translated.owl.carousel", function (e) { if (elementCarouselFotosSecundarias.length === 0) return; const $fotoActual = elementCarouselFotosPrincipal.find(".owl-item.active:not(.cloned) .item-foto").first(); const fotoId = $fotoActual.data("foto"); elementCarouselFotosSecundarias.find(".item-foto").removeClass("active"); elementCarouselFotosSecundarias.find(`.item-foto[data-foto="${fotoId}"]`).addClass("active"); }); elementCarouselFotosSecundarias.on("click", ".item-foto", function (e) { e.preventDefault(); const fotoId = $(this).data("foto"); const $itemsPrincipales = elementCarouselFotosPrincipal.find(".owl-item:not(.cloned) .item-foto"); let indexReal = -1; $itemsPrincipales.each(function (i) { if ($(this).data("foto") == fotoId) { indexReal = i; return false; } }); elementCarouselFotosSecundarias.find(".item-foto").removeClass("active"); $(this).addClass("active"); elementCarouselFotosPrincipal.trigger("to.owl.carousel", [indexReal, 300, true]); }); $("body").on("click", ".btn-categoria-foto-filtrar", function (e) { e.preventDefault(); const tipo = $(this).data("tipo"); const $itemsPrincipales = elementCarouselFotosPrincipal.find(".owl-item:not(.cloned) .item-foto"); let indexReal = -1; $itemsPrincipales.each(function (i) { if ($(this).data("tipo") == tipo && indexReal == -1) { indexReal = i; return false; } }); $(".btn-categoria-foto-filtrar").removeClass("active"); $(this).addClass("active"); elementCarouselFotosPrincipal.trigger("to.owl.carousel", [indexReal, 300, true]); elementCarouselFotosSecundarias.trigger("to.owl.carousel", [indexReal, 300, true]); }); $("#rango-anyos").on("input change", calcularFinanciacion); }); function calcularFinanciacion() { const anyo = $("#rango-anyos").val() * 1; $(".anyos-financiacion").text(anyo + " años"); const importeFinanciar = Math.max(precio, 0); if (datosFinanciacion[anyo] !== undefined) { const resumenMes = Utils.number_format(importeFinanciar * (datosFinanciacion[anyo] * 1), { decimalSeparator: ",", thousandSeparator: ".", symbol: "€" }); $("#resumen-financiar span").html(resumenMes + "/mes a " + anyo + " años"); } } }, actualizarCuentaAtras: function () { $('.item-vehiculo-rebajado').each(function () { const timestamp = parseInt($(this).data('time')); const ahora = Math.floor(Date.now() / 1000); const diferencia = timestamp - ahora; if (diferencia <= 0) { $(this).html('Finalizado'); return; } const dias = Math.floor(diferencia / 86400); const horas = Math.floor((diferencia % 86400) / 3600); const minutos = Math.floor((diferencia % 3600) / 60); const segundos = diferencia % 60; $(this).find('.rebajado-dia').html(`D${String(dias).padStart(2, '0')}`); $(this).find('.rebajado-horas').html(`H${String(horas).padStart(2, '0')}`); $(this).find('.rebajado-minutos').html(`M${String(minutos).padStart(2, '0')}`); $(this).find('.rebajado-segundos').html(`S${String(segundos).padStart(2, '0')}`); }); }, initReservar: function () { $(document).ready(function () { preparaLugar(28, undefined, undefined, undefined, "reserva-provincia", "reserva-localidad"); $('#reserva-entrega').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { if (isSelected === null) return; if($(this).val() == 2) $(".form-group-entrega").removeClass("d-none"); else $(".form-group-entrega").addClass("d-none"); }); $("#btn-enviar-reserva").click(function () { var extraMsg = ""; if (!$("#politica-reserva").is(":checked")) { extraMsg = $("#politica-reserva").attr("title"); } Utils.sendStandardAjax("frm-reservar", "https://www.leadercar.es/ajax/Vehiculo.reservar.php", { extraErroresForm: extraMsg, successCallback: function (data, textStatus, XMLHttpRequest) { if (data["error_number"] >= 0) { switch (data["forma_pago"] * 1) { case 1: case 3: { $("#procesaPagoExterno").html(data["formularioFormaPago"]); ClassBlockUI.abrirBlockUIEsperePorFavor(); $("#pagoBanco").submit(); break; } case 2: { $("#procesaPagoExterno").html(data["formularioFormaPago"]); ClassBlockUI.abrirBlockUIEsperePorFavor(); $("#pagoPaypal").submit(); break; } case 4: { ClassBlockUI.abrirBlockUIEsperePorFavor(); window.location = data["formularioFormaPago"]; break; } } } else { ClassBlockUI.abrirBlockUIEstandarMensaje(data["error_message"], true); } }, resetFormOnSuccess: true }); }); }); }, initFavoritos: function () { const favoritoEmailKey = "favoritos_email"; $("body").on("click", ".item-vehiculo-favorito", function () { const email = Cookies.get_cookie(favoritoEmailKey); $("#id-favorito").val($(this).data("id")); if (isEmail(email)) { $("#email-favorito").val(email); enviarFavorito(); } else { ClassBlockUI.abrirBlockUIEstandar("modal-email-favorito", undefined, "", "modal356"); } }); $("body").on("click", "#btn-enviar-email-favorito", function () { var extraMsg = ""; if (!$("#politica-favorito").is(":checked")) { extraMsg = $("#politica-favorito").attr("title"); } enviarFavorito(extraMsg); }); function enviarFavorito(extraMsg = "") { Utils.sendStandardAjax("modal-email-favorito", "https://www.leadercar.es/ajax/Vehiculos.toggleFavorito.php", { extraErroresForm: extraMsg, successCallback: function (data, textStatus, XMLHttpRequest) { $(".modal").modal("hide"); if (data["error_number"] >= 0) { const id = $("#id-favorito").val(); if (data["favorito"]) { $(".item-vehiculo-favorito[data-id='" + id + "']").addClass("favorito"); $(".item-ficha-vehiculo-estadistica.item-vehiculo-favorito[data-id='" + id + "'] span").text("Quitar de favoritos"); } else { $(".item-vehiculo-favorito[data-id='" + id + "']").removeClass("favorito"); $(".item-ficha-vehiculo-estadistica.item-vehiculo-favorito[data-id='" + id + "'] span").text("Añadir a favoritos"); } const expires = new Date(); expires.setFullYear(expires.getFullYear() + 1); Cookies.set_cookie(favoritoEmailKey, $("#email-favorito").val(), expires); } else { ClassBlockUI.abrirBlockUIEstandarMensaje(data["error_message"], true); } } }); } } }; function mostrarToast(mensaje, tipo = 'success') { // Eliminar toast anterior si existe const toastAnterior = document.querySelector('.toast-notif'); if (toastAnterior) { toastAnterior.remove(); } // Crear nuevo toast const toast = document.createElement('div'); toast.className = `toast-notif ${tipo}`; toast.textContent = mensaje; document.body.appendChild(toast); // Animación de entrada setTimeout(() => toast.classList.add('show'), 100); // Desaparecer automáticamente setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 2500); // 2.5 segundos visible } /* ClassBlockUI.abrirBlockUIEstandar(contenedorIDAMostrar[, accionCerrar, headerText, extraClass, restaurarElemento]); ClassBlockUI.abrirBlockUIEstandarMensaje(mensaje[, isAlertOrButtons, onClose]); ClassBlockUI.abrirBlockUIConfirm(mensaje, textoBotonAceptar, accionBotonAceptar, textoBotonCancelar[, accionBotonCancelar]); //accionBotonCancelar="close" ClassBlockUI.abrirBlockUIEsperePorFavor:([mensaje]); */ var ClassBlockUI = { restaurarElemento: function () { var data = $("body").data('blockUIEstandar.history'); if (data) { data.el.style.display = data.display; data.el.style.position = data.position; if (data.parent) data.parent.appendChild(data.el); $("body").removeData('blockUIEstandar.history'); $("#" + data.generatedId).remove(); } }, abrirBlockUIEstandar: function (contenedorIDAMostrar, accionCerrar, headerText, extraClass, restaurarElemento) { if (restaurarElemento || restaurarElemento == undefined) { ClassBlockUI.restaurarElemento(); } $(".modalAutoHide").modal("hide"); if ($(".modal").length > 0) { $("body").addClass("modal-open") } if (contenedorIDAMostrar == undefined || $("#" + contenedorIDAMostrar).length == 0) { return; } //var blockUIId="blockUI_"+new Date().getTime(); var blockUIId = "blockUI_" + contenedorIDAMostrar; extraClass = extraClass == undefined ? "" : extraClass; //modal-lg var object = $("#" + contenedorIDAMostrar); var node = object[0]; var data = {}; $("body").data('blockUIEstandar.history', data); data.el = node; data.parent = node.parentNode; data.display = node.style.display; data.position = node.style.position; data.generatedId = blockUIId; data.object = object; if (data.parent) data.parent.removeChild(node); var header = headerText != undefined ? headerText : ""; const imgCerrar = extraClass.includes("modal-video") ? "cerrar2.svg" : "cerrar.svg"; var message = '' + ''; $("body").append(message); var modal = $("#" + blockUIId); modal.find(".modal-body").append(node); modal.find(".modal-dialog").addClass("fadeIn"); modal.on('hidden.bs.modal', function () { ClassBlockUI.restaurarElemento(); }) var myModal = new bootstrap.Modal($(modal)[0], { keyboard: false }) myModal.show(); if (accionCerrar == undefined) //boton cerrar tiene accion por defecto { $("#" + blockUIId + " .btnCerrarModalEquis").click(function () { myModal.hide(); if ($(".modal").length > 0) { $("body").addClass("modal-open") } }); } else if (accionCerrar == false) //oculta el boton cerrar { $("#" + blockUIId + " .btnCerrarModalEquis").hide(); } else //boton cerrar con accion especial { $("#" + blockUIId + " .btnCerrarModalEquis").click(accionCerrar); } return modal; }, abrirBlockUIEstandarMensaje: function (mensaje, isAlertOrButtons, onClose, extraClass, title) { $(".modalAutoHide").modal("hide"); if ($(".modal").length > 0) { $("body").addClass("modal-open") } var blockUIId = "blockUI_" + new Date().getTime(); extraClass = extraClass == null || extraClass == undefined ? "" : extraClass; //modal-lg title = title == null || title == undefined ? "Aviso" : title; if (isAlertOrButtons == undefined) isAlertOrButtons = false; if (onClose == undefined) onClose = false; var botonera = ""; var botoneraEspecial = false; if (isAlertOrButtons === false) { botonera = ""; } else if (isAlertOrButtons === true) { let textoBoton = "Aceptar"; botonera = `
`; } else { botoneraEspecial = true; botonera = "
"; for (var index in isAlertOrButtons) { botonera += " " + isAlertOrButtons[index]["text"] + " "; } botonera += "
"; } var message = ''; message += ''; $("body").append(message); var modal = $("#" + blockUIId); modal.find(".modal-dialog").css("animation-duration", "500ms").addClass("zoomIn"); modal.on('hidden.bs.modal', function () { modal.remove(); }) var myModal = new bootstrap.Modal($(modal)[0], { keyboard: false }); myModal.show(); //Acciones de los botones especiales if (botoneraEspecial) { for (var index in isAlertOrButtons) { if (isAlertOrButtons[index]["action"] == "close") { isAlertOrButtons[index]["action"] = function () { myModal.hide(); if ($(".modal").length > 0) { $("body").addClass("modal-open") } }; } $("#" + blockUIId + " ." + index).unbind("click").click(isAlertOrButtons[index]["action"]); } } var fnOnClose; if (onClose == false) { fnOnClose = function () { myModal.hide(); if ($(".modal").length > 0) { $("body").addClass("modal-open") } }; } else if (typeof onClose === "function") { fnOnClose = function () { onClose() }; } else if (onClose == "location") { fnOnClose = function () { window.location.reload() }; } else if (onClose == "back") { fnOnClose = function () { history.go(-1); }; } else { fnOnClose = function () { window.location = onClose }; } $("#" + blockUIId + " .btnCerrarBlockUIAlert, #" + blockUIId + " .btnCerrarModalEquis").unbind("click").click(fnOnClose); return modal; }, abrirBlockUIConfirm: function (mensaje, textoAceptar, accionAceptar, textoCancelar, accionCancelar, extraClass, title) { accionCancelar = accionCancelar == undefined ? "close" : accionCancelar; extraClass = extraClass == null || extraClass == undefined ? "" : extraClass; var buttons = { "btnAceptarBUI_CONFIRM": { "text": textoAceptar, "action": accionAceptar }, "btnCancelarBUI_CONFIRM": { "text": textoCancelar, "action": accionCancelar } }; return ClassBlockUI.abrirBlockUIEstandarMensaje(mensaje, buttons, false, extraClass, title); }, abrirBlockUIEsperePorFavor: function (mensaje) { if (mensaje == undefined) { mensaje = "
Espere por favor...
"; } ; return ClassBlockUI.abrirBlockUIEstandarMensaje(mensaje, undefined, false, "modalEspere"); } };