// load scripts for replaced elements var isExecuteLoad = false; document.addEventListener('swup:pageView', function(e) { $( document ).trigger('inizialize'); if (isExecuteLoad) { $( document ).trigger('executeReady'); $( window ).trigger('load'); } else { $('.transition-fade').addClass('finished'); } isExecuteLoad = true; }); document.addEventListener('swup:transitionStart', function(e) { $('.transition-fade').removeClass('finished'); $(document).trigger('removeEvent'); }); document.addEventListener("swup:transitionEnd", function(e){ $('.transition-fade').addClass('finished'); }); $.fn.isInViewport = function(offset) { var $el = $(this); if (offset === undefined) offset = 50; var elementTop = $el.offset().top; var elementBottom = elementTop + ($el.outerHeight() * offset / 100); var viewportHeight = $(window).height(); var viewportToll = 15; var viewportTop = $(window).scrollTop() - viewportToll; var viewportBottom = viewportTop + viewportHeight + (viewportToll * 2.0); if (offset < 0) return elementTop < viewportBottom && elementBottom < viewportBottom; else { return elementBottom >= viewportTop && elementTop < viewportBottom && elementBottom < viewportBottom; } }; var loadScript = function (path, id) { var result = $.Deferred(); var script = document.createElement("script"); if (id !== undefined) { script.id = id } script.async = "async"; script.type = "text/javascript"; script.src = path; script.onload = script.onreadystatechange = function(_, isAbort) { if (!script.readyState || /loaded|complete/.test(script.readyState)) { if (isAbort) result.reject(); else result.resolve(); } }; script.onerror = function () { result.reject(); }; $("head")[0].appendChild(script); return result.promise(); } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie.replace(/\+/g, ' ')); var ca = decodedCookie.split(';'); for(var i = 0; i ') }); $('.clm-recaptcha').each(function( index ) { recaptcha_form = $(this).closest("form"); // recupera la callback success per il recaptcha di google del form, // se non esiste mette quella di default if (recaptcha_form.data('gcallback') === undefined) gcallback = onSuccessRecaptcha; else gcallback = window[recaptcha_form.data('gcallback')]; // render il recaptcha clmrecaptchaID[index] = this.id; clmrecaptchaFunc[index] = grecaptcha.render(this.id, { 'sitekey' : '6Lc_G_EqAAAAAApZX6JdW-yEMzZT9gavizXRw8vK', 'callback' : gcallback, 'error-callback' : onErrorRecaptcha, 'size' : 'invisible' }); }); }; $(window).on("load resize scroll", function() { if ($(".googlemaps").length > 0) { if ($(".googlemaps").isInViewport(0) && !isMapsLoaded) { isMapsLoaded = true; var lang = getCookie('lang'); loadScript("https://www.cantinailpignetto.com/js/gmap.js.php").then(function() { var googleMap = document.createElement("script"); googleMap.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyA2iem8z8DkVtRIaCuSGxUc1L70orLQPU8&callback=mapsCallback&language="+lang; googleMap.async = true; googleMap.defer = true; document.body.appendChild(googleMap); }); } } }); function adsBlocked(callback){ var testURL = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js' var myInit = { method: 'HEAD', mode: 'no-cors' }; try { var myRequest = new Request(testURL, myInit); fetch(myRequest).then(function(response) { return response; }).then(function(response) { callback(false) }).catch(function(e){ callback(true) }); } catch (e) { callback(false) }; } function showStatusCookie() { var policyCookieConsent = getCookie('policyCookieConsent'); var policyCookiePreferences = getCookie('policyCookiePreferences'); var policyCookieStatistics = getCookie('policyCookieStatistics'); var policyCookieMarketing = getCookie('policyCookieMarketing'); var policyCookieUnique = getCookie('policyCookieUnique'); var policyCookieLanguage = 0; if (getCookie('lang_id') != 1) policyCookieLanguage = 1; var txtPolicyCookieStatusDeclineDef = ['Rifiuta', 'Reject']; var txtPolicyCookieStatusConfirmDef = ['Accetta selezionati', 'Allow selection']; var txtPolicyCookieStatusNecessaryDef = ['Tecnici', 'Technical']; var txtPolicyCookieStatusPreferencesDef = ['Preferenze', 'Preference']; var txtPolicyCookieStatusStatisticsDef = ['Statistici', 'Statistical']; var txtPolicyCookieStatusMarketingDef = ['Marketing', 'Marketing']; var txtPolicyCookieStatus = "---"; var txtPolicyCookieStatusSelect = ""; var txtPolicyCookieDate = '---'; var txtPolicyCookieUnique = '---'; if (policyCookieConsent == "") { $('.cookie-btn-erase').hide(); } else if (policyCookieConsent == "0") { txtPolicyCookieStatus = txtPolicyCookieStatusDeclineDef[policyCookieLanguage]; txtPolicyCookieStatusSelect = '('+txtPolicyCookieStatusNecessaryDef[policyCookieLanguage]+')'; txtPolicyCookieDate = getCookie('policyCookieDate'); } else if (policyCookieConsent == "1") { txtPolicyCookieStatus = txtPolicyCookieStatusConfirmDef[policyCookieLanguage]; txtPolicyCookieStatusSelect = '('+txtPolicyCookieStatusNecessaryDef[policyCookieLanguage]; if (policyCookiePreferences == "1") txtPolicyCookieStatusSelect += ', '+txtPolicyCookieStatusPreferencesDef[policyCookieLanguage]; if (policyCookieStatistics == "1") txtPolicyCookieStatusSelect += ', '+txtPolicyCookieStatusStatisticsDef[policyCookieLanguage]; if (policyCookieMarketing == "1") txtPolicyCookieStatusSelect += ', '+txtPolicyCookieStatusMarketingDef[policyCookieLanguage]; txtPolicyCookieStatusSelect += ')'; txtPolicyCookieDate = getCookie('policyCookieDate'); } if (policyCookieUnique != "") txtPolicyCookieUnique = policyCookieUnique; $('.statusConsent').html(txtPolicyCookieStatus + ' ' +txtPolicyCookieStatusSelect); $('.dateConsent').html(txtPolicyCookieDate); $('.dateUniqueId').html(txtPolicyCookieUnique); } $(window).on("load", function() { showStatusCookie(); $(window).off('eventCookieUpdate'); $(window).on('eventCookieUpdate', function() { var policyCookieUnique = getCookie('policyCookieUnique'); var sendInfo = { 'p': !window.policyCookiePreferences, 's': !window.policyCookieStatistics, 'm': !window.policyCookieMarketing, 'i': '80.88.87.142', 'u': 'www.cantinailpignetto.com', 't': 0, }; if (policyCookieUnique != "") sendInfo['uq'] = policyCookieUnique; if (policyCookieRequired1 == '0') sendInfo['d'] = true; $.ajax({ type: "PUT", url: 'https://registro-cookie.colombo3000.com/api/update', beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer t-7614f875-8423-4f20-a674-d7cf3096290e'); }, data: JSON.stringify(sendInfo), contentType: "application/json; charset=utf-8", }) .done(function(datiJSON){ SetCookie('policyCookieUnique', datiJSON.uq, 365); $('.dateUniqueId').html(datiJSON.uq); }) .fail(function(data, textStatus, errorThrown) { }); }); var lang = getCookie('lang'); $('form input, form select, form textarea, form button').bind('focus.recaptcha', function() { loadScript("https://www.cantinailpignetto.com/js/recaptcha.js.php?20261030080920").then(function() { var googleRecaptcha = document.createElement("script"); googleRecaptcha.src = "https://www.google.com/recaptcha/api.js?hl="+lang+"&onload=onloadCallback&render=explicit"; googleRecaptcha.async = true; googleRecaptcha.defer = true; document.body.appendChild(googleRecaptcha); adsBlocked(function(blocked){ var exdate = new Date() var n = document.location.hostname.split("."); var e = n.slice(1).join("."); exdate.setDate(exdate.getDate() + 1) var value = 0; if (blocked) value = 1; document.cookie = "adblock=" + escape(value) + ";path=/;expires="+exdate.toGMTString(); }) }); $('form input, form select, form textarea, form button').unbind('focus.recaptcha'); }); }); lazyExecute = function(el, force) { if (force === undefined) force = false; var instance = $(el).lazy({ chainable: !force, delay:-1, afterLoad: function(element) { $.event.trigger({ type: "lazyAfterLoad", time: new Date(), element : element }); $(window).trigger('resize'); }, onFinishedAll: function() { $.event.trigger({ type: "lazyComplete", time: new Date() }); $(window).trigger('resize'); } }); if (force) instance.force($(el)); } var tmrHandleVideoLazy; handleVideoLazy = function() { var isMobile = window.innerWidth < 768; $('.v-lazy-wrapper').each(function () { var $container = $(this); var $videoPlay; if (isMobile) { $videoPlay = $container.find('.v-mobile .v-lazy'); } else { $videoPlay = $container.find('.v-desktop .v-lazy'); } if (!$videoPlay.attr('data-src')) { lazyExecute($videoPlay[0]); } }); } $(window).on('load', function() { $('.lazy').each(function() { if ($(this).closest('.waitLazyLoad').length == 0) { lazyExecute(this); } }); handleVideoLazy(); }); $(window).on('resize', function () { clearTimeout(tmrHandleVideoLazy); tmrHandleVideoLazy = setTimeout(handleVideoLazy, 250); }); // lunghezza calcolata al caricamento della pagina e ad ogni resize della schermata var actualWidth; $( document ).ready(function() { $(document).trigger('executeReady'); }); $( document ).on('executeReady', function() { $(document).off('change', '[type="radio"]'); $(document).on('change', '[type="radio"]', function() { var name = $(this).attr('name'); $('[name="'+name+'"]').removeAttr('required'); }); $(document).off('change', 'select'); $(document).on('change', 'select', function() { if ($(this).val() !== "") { $(this).addClass('selected'); } else { $(this).removeClass('selected'); } }); $("#bottom-to-top").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; }); $('[data-toggle="tooltip"]').tooltip(); $( ".table" ).each(function( index ) { if (!$(this).parent().hasClass("table-responsive")) { $(this).wrap( "
" ); } }); $('.carousel').carousel(); $('.modal').modal('hide'); $('.dropdown-submenu > a').on("click", function(e) { e.preventDefault(); var submenu = $(this); var isShow = submenu.next('.dropdown-menu').hasClass('show'); $('.dropdown-submenu .dropdown-menu').removeClass('show'); if (!isShow) { submenu.next('.dropdown-menu').addClass('show'); } e.stopPropagation(); }); $('.dropdown').on("hidden.bs.dropdown", function() { // hide any open menus when parent closes $('.dropdown-menu.show').removeClass('show'); }); execute_animated(); // Effect input $(document).on("blur", 'form input, form textarea, form select', function(){ if($(this).val().length !== 0) { $(this).addClass('filled'); } else { $(this).removeClass('filled'); } }); }); function execute_animated() { $(document).find('.animated:not([data-delay],[data-order])').each(function() { var element = this.element; if (element === undefined) $element = $(this); else $element = $(element); var offset = $element.data('offset'); if (typeof offset === 'undefined') offset = 80; var context = window; var horizontal = false; var data_context = $element.data('context'); if (data_context !== undefined) { context = document.getElementById(data_context) horizontal = true; } $(this).waypoint(function() { var element = this.element; if (element === undefined) $element = $(this); else $element = $(element); var myAnimated = $element.data('animated'); var oneSomeAnimated = $element.data('oneanimated'); if (typeof myAnimated === 'undefined') myAnimated = 'in-view'; // animazione da eseguire una singola volta if (oneSomeAnimated == true) { // animazione non e' stata gia' eseguita in tal caso la esegue if (!($element.hasClass(myAnimated))) $element.toggleClass(myAnimated).css("opacity", "1"); // animazione da eseguire sempre } else $element.toggleClass(myAnimated); }, { offset: offset+'%', context: context, horizontal: horizontal, }); }); $(document).find('.animated[data-order="0"]').each(function() { var element = this.element; if (element === undefined) $element = $(this); else $element = $(element); var offset = $element.data('offset'); if (typeof offset === 'undefined') offset = 80; var context = window; var horizontal = false; var data_context = $element.data('context'); if (data_context !== undefined) { context = document.getElementById(data_context) horizontal = true; } $(this).waypoint(function() { var element = this.element; if (element === undefined) $element = $(this); else $element = $(element); if ($element.hasClass('execute')) return; var myAnimated = $element.data('animated'); var group = $element.data('group'); if (typeof myAnimated === 'undefined') myAnimated = 'in-view'; $element.addClass("execute").addClass(myAnimated).css("opacity", "1"); $('[data-group="'+group+'"]').each(function( index ) { var el = $(this); var delay = el.data('delay') * el.data('order'); setTimeout( function() { var elAnimated = el.data('animated'); if (typeof elAnimated === 'undefined') elAnimated = 'in-view'; el.addClass("execute").addClass(elAnimated).css("opacity", "1"); }, delay, el); }); }, { offset: offset+'%', context: context, horizontal: horizontal, }); }); $(document).find('.animated[data-delay="0"]').each(function() { var element = this.element; if (element === undefined) $element = $(this); else $element = $(element); var offset = $element.data('offset'); if (typeof offset === 'undefined') offset = 80; var context = window; var horizontal = false; var data_context = $element.data('context'); if (data_context !== undefined) { context = document.getElementById(data_context) horizontal = true; } $(this).waypoint(function() { var element = this.element; if (element === undefined) $element = $(this); else $element = $(element); if ($element.hasClass('execute')) return; var myAnimated = $element.data('animated'); var group = $element.data('group'); if (typeof myAnimated === 'undefined') myAnimated = 'in-view'; $element.addClass("execute").addClass(myAnimated).css("opacity", "1"); $('[data-group="'+group+'"]').each(function( index ) { var el = $(this); var delay = el.data('delay'); setTimeout( function() { var elAnimated = el.data('animated'); if (typeof elAnimated === 'undefined') elAnimated = 'in-view'; el.addClass("execute").addClass(elAnimated).css("opacity", "1"); }, delay, el); }); }, { offset: offset+'%', context: context, horizontal: horizontal, }); }); } // Inizializza l'effetto input function init_form(form_id) { $.each($('input, textarea, select', '#'+form_id),function(e){ if($(this).val().length !== 0) { $(this).addClass('filled'); } else { $(this).removeClass('filled'); } }) } var sendVirtualEvent = function(eventForce, eventItem) { if (eventForce === undefined) eventForce = ""; if (eventItem === undefined) eventItem = null; $.post({ url: "https://www.cantinailpignetto.com/admin/includes/ajax/ajax_frontend.php", data: { "type": "sendVirtualEvent", "url" : window.location.href, "lang" : getCookie('lang'), "eventForce" : eventForce, "eventItem" : eventItem, } }) .done(function(data ) { datiJSON = JSON.parse(data); if (datiJSON.event != "") { window.dataLayer.push({ event: datiJSON.event, event_name: datiJSON.event_name, item: datiJSON.item, }); } }); } $( window ).on('load', function() { if ($(".popup-maker-modal").length > 0) { loadScript("https://www.cantinailpignetto.com/js/popup_maker.js.php").then(function() {}); } }); $(window).on("load", function() { $(document).find('.carousel').each(function () { var $carousel = $(this); if ($carousel.attr('data-ride') === 'carousel') { return; } var $firstItem = $carousel.find('.carousel-item.active').first(); var $media = $firstItem.find('img, video').first(); var interval = parseInt($carousel.attr('data-interval'), 10); if (isNaN(interval)) { interval = 5000; } function startCarousel() { $carousel.carousel({ interval: interval, ride: 'carousel', pause: false }); } if ($media.length) { // Caso immagine if ($media.is('img')) { $media.on('load', function () { startCarousel(); }); // se già caricata da cache if ($media[0].complete) { $media.trigger('load'); } } // Caso video if ($media.is('video')) { if ($media[0].readyState >= 3) { startCarousel(); } else { $media.on('loadeddata', function () { startCarousel(); }); } } } else { // nessun media → parte subito startCarousel(); } }); }); var supportsCssVariables = (window.CSS && window.CSS.supports && window.CSS.supports('--fake-var', 0)); function functionOffset() { var offsetH = $('#top_content').outerHeight(true); return offsetH; }; $(window).on('load', function() { slider = document.getElementById("slide"); if ($('.pswp').length > 0) { loadScript("https://www.cantinailpignetto.com/js/jquery.photoswipe.min.js").then(function() { loadScript("https://www.cantinailpignetto.com/js/simple-gallery.min.js").then(function() {}); }); } $('#navbarNav').on('show.bs.collapse', function () { $(this).parents("#top_content").first().addClass("top-collapsed-open"); }); $('#navbarNav').on('hidden.bs.collapse', function () { $(this).parents("#top_content").first().removeClass("top-collapsed-open"); }); /*NAVBAR SCROLLING EFFECT*/ if($(window).scrollTop() > 50) { $("#top_content").addClass("top-scrolling"); } else { $("#top_content").removeClass("top-scrolling"); } /*NAVBAR COLLAPSED CLICK BUTTON*/ isMenuOpen = false; $(document).off("click", ".navbar-toggler"); $(document).on("click", ".navbar-toggler", function() { var nav = $(this).parents("#top_content").first(); var page = $(".pages"); if (!isMenuOpen) { isMenuOpen = true; nav.addClass("top-collapsed-open"); page.addClass("menu-open"); } else { isMenuOpen = false; nav.removeClass("top-collapsed-open"); page.removeClass("menu-open"); } }); const roamingDivs = document.querySelectorAll(".roaming-div"); if(roamingDivs.length > 0) { roamingDivs.forEach(roaminDiv => { const innerLink = roaminDiv.querySelector("a"); innerLink.addEventListener('mouseenter', (e) => { roaminDiv.classList.add("hover"); }); innerLink.addEventListener('mouseleave', (e) => { roaminDiv.classList.remove("hover"); }); }); } const textRevealBoxes = document.querySelectorAll(".text-reveal"); if(textRevealBoxes.length > 0) { textRevealBoxes.forEach(text => { const buttonReveal = text.closest(".text-reveal-box").querySelector(".reveal-btn"); const buttonHide = text.closest(".text-reveal-box").querySelector(".hide-btn"); const ellipsis = text.querySelector(".ellipsis-txt"); if(buttonReveal) { buttonReveal.addEventListener('click', (e) => { buttonReveal.classList.add("d-none"); if(ellipsis) { text.querySelector(".ellipsis-txt").classList.add("d-none"); } if(buttonHide) { buttonHide.classList.remove("d-none"); } $(text.querySelector(".hidden-txt")).slideDown(); }); } if(buttonHide) { buttonHide.addEventListener('click', (e) => { buttonHide.classList.add("d-none"); if(ellipsis) { text.querySelector(".ellipsis-txt").classList.remove("d-none"); } if(buttonReveal) { buttonReveal.classList.remove("d-none"); } $(text.querySelector(".hidden-txt")).slideUp(); }); } }); } /* $('#navbarNav').on('show.bs.collapse', function () { $(this).parents("#top_content").first().addClass("top-collapsed-open"); }); $('#navbarNav').on('hidden.bs.collapse', function () { $(this).parents("#top_content").first().removeClass("top-collapsed-open"); });*/ /* GESTIONE CAMPI "Altro" */ const checkboxsFormOther = document.querySelectorAll(".other_field_handler"); if(checkboxsFormOther.length > 0) { checkboxsFormOther.forEach(checkbox => { checkbox.addEventListener('input', (e) => { const el = e.target; const inputType = el.type; const parentContainer = el.closest('.form-list-container'); const hiddenOtherInput = parentContainer.querySelectorAll(".input_other"); const revealBox = parentContainer.querySelector(".input_other_container"); if(el.checked != '') { if(inputType == "radio" && el.classList.contains("radio-disable")) { hiddenOtherInput.forEach(hiddenInput => { hiddenInput.classList.add("no-send"); hiddenInput.removeAttribute("required"); $(hiddenInput).slideUp(); if(revealBox) { $(revealBox).slideUp(); } }); } else { hiddenOtherInput.forEach(hiddenInput => { hiddenInput.classList.remove("no-send"); hiddenInput.setAttribute("required","required"); $(hiddenInput).slideDown(); if(hiddenInput.classList.contains("num_preferenze")) { const inputEvent = new Event('input', { bubbles: true }); hiddenInput.dispatchEvent(inputEvent); } }); if(revealBox) { $(revealBox).slideDown(); } } } else { hiddenOtherInput.forEach(hiddenInput => { hiddenInput.classList.add("no-send"); hiddenInput.removeAttribute("required"); $(hiddenInput).slideUp(); }); if(revealBox) { $(revealBox).slideUp(); } } }); }); } /* GESTIONE GRUPPI CAMPI NASCOSTI */ const checkboxesFormReveal = document.querySelectorAll(".reveal-inputs-container_handler"); const selectsFormReveal = document.querySelectorAll(".reveal-inputs-container-select_handler"); if(checkboxesFormReveal.length > 0) { checkboxesFormReveal.forEach(checkbox => { checkbox.addEventListener('input', (e) => { const el = e.target; const inputType = el.type; const parentContainer = el.closest('.reveal-inputs-main-container').querySelector('.reveal-inputs-container'); const hiddenInputs = parentContainer.querySelectorAll(".form-fields"); if(el.checked != '') { if(inputType == "radio" && el.classList.contains("radio-disable")) { hiddenInputs.forEach(input => { input.classList.add("no-send"); if(input.classList.contains("is-required")) { input.removeAttribute("required"); } }); $(parentContainer).slideUp(); } else { hiddenInputs.forEach(input => { input.classList.remove("no-send"); if(input.classList.contains("is-required")) { input.setAttribute("required","required"); } }); $(parentContainer).slideDown(); } } else { hiddenInputs.forEach(input => { input.classList.add("no-send"); if(input.classList.contains("is-required")) { input.removeAttribute("required"); } }); $(parentContainer).slideUp(); } }); }); } if(selectsFormReveal.length > 0) { selectsFormReveal.forEach(select => { select.addEventListener('input', (e) => { const el = e.target; const selectValue = el.options[el.selectedIndex]; const revealAttr = selectValue.getAttribute("data-field-reveal"); const parentContainer = el.closest('.reveal-inputs-main-container').querySelector('.reveal-inputs-col'); const hiddenInputs = parentContainer.querySelectorAll(".form-fields"); if(revealAttr == "true") { hiddenInputs.forEach(input => { input.classList.remove("no-send"); if(input.classList.contains("is-required")) { input.setAttribute("required","required"); } }); $(parentContainer).show(); } else { hiddenInputs.forEach(input => { input.classList.add("no-send"); if(input.classList.contains("is-required")) { input.removeAttribute("required"); } }); $(parentContainer).hide(); } }); }); } /* GESTIONE DEGUSTAZIONI */ const gotoBookTastingBtn = document.querySelectorAll(".goto_booking"); const gotoGiftTastingBtn = document.querySelectorAll(".goto_gift_tasting"); if(gotoBookTastingBtn.length > 0) { const tastingForm = document.querySelector("#tasting-form #form_degustazione_ajax"); const tastingSelect = tastingForm.querySelector("#tasting_paths"); gotoBookTastingBtn.forEach(button => { button.addEventListener('click', (e) => { const tastingId = e.target.getAttribute("data-tasting-id"); tastingSelect.querySelector(`option[data-idx="${tastingId}"]`).selected="selected"; }); }); } if(gotoGiftTastingBtn.length > 0) { const tastingForm = document.querySelector("#gift_tasting-form #form_contact_gift_tasting_ajax"); const tastingSelect = tastingForm.querySelector("#gift_tasting_paths"); gotoGiftTastingBtn.forEach(button => { button.addEventListener('click', (e) => { const changeEvent = new Event("change", { bubbles: true }); const tastingId = e.target.getAttribute("data-tasting-id"); tastingSelect.querySelector(`option[data-idx="${tastingId}"]`).selected="selected"; tastingSelect.dispatchEvent(changeEvent); }); }); } /* GESTIONE MAPPA INTERATTIVA */ const mapItem = document.querySelector("#territorio .container-map"); if(mapItem) { const mapTrigger = mapItem.querySelector(".trigger-box"); mapTrigger.addEventListener('mouseenter', (e) => { mapItem.classList.add("map-hover"); }); mapTrigger.addEventListener('mouseleave', (e) => { mapItem.classList.remove("map-hover"); }); "data-reveal-status"} /* GESTIONE CAMPI REVEAL CON ID*/ const boxRevealTriggers = document.querySelectorAll(".reveal-section-field"); if(boxRevealTriggers.length > 0) { boxRevealTriggers.forEach(trigger => { if(trigger.nodeName == "SELECT") { trigger.addEventListener('change', (e) => { const el = e.target; const boxToReveal = document.getElementById(el.getAttribute("data-reveal-box")); const otionSelected = el.options[el.selectedIndex]; const optionAction = otionSelected.getAttribute("data-reveal-action"); switch(optionAction) { case 'hide': if(boxToReveal.getAttribute("data-reveal-status") == "shown") { $(boxToReveal).slideUp(); boxToReveal.setAttribute("data-reveal-status", "hidden"); } break; case 'show': if(boxToReveal.getAttribute("data-reveal-status") == "hidden") { $(boxToReveal).slideDown(); boxToReveal.setAttribute("data-reveal-status", "shown"); } break; default: break; } }) } }); } }); $(window).on('load resize', function() { /* GESTIONE SLIDER STORIA */ const storiaSliderItem = document.getElementById("storia-slider-container"); if(storiaSliderItem) { const storiaSliderSlides = storiaSliderItem.querySelectorAll(".storia-slide"); let totalHeight = 0; if(storiaSliderSlides.length > 0) { storiaSliderSlides.forEach(slide => { totalHeight += slide.offsetHeight; }); } storiaSliderItem.style.height = totalHeight+"px"; } }); $(window).on('scroll', function() { /*NAVBAR SCROLLING EFFECT*/ if($(window).scrollTop() > 50) { $("#top_content").addClass("top-scrolling"); } else { $("#top_content").removeClass("top-scrolling"); } }); $(window).on('resize', function () { if (window.innerWidth > 767 && ($('.top-collapsed-open').length)) { $(".navbar-toggler").trigger("click"); } }); /* LANDING PAGE NAV WITH ANCHORS AND LINK*/ $(window).on('load', function() { // SE NON SIAMO NELLA INDEX DA VALUTARE if ($(".menu-anchor").length) { $("#menu-top .nav-item").each(function() { const innerLink = $(this).find(".nav-link").first(); if (!innerLink.hasClass('dropdown-toggle')) { const innerLinkHref = innerLink.attr('href'); // SE SONO PRESENTI ANCHOR NE LINK if(innerLinkHref.indexOf("#") > -1) { // SI INSERISCE UN LINK CHE RIMANDA ALL'ANCHOR DELL'HOMEPAGE (O PAGINA SPECIFICA) const anchorToGo = innerLinkHref.split("#")[1]; innerLink.attr('href', "https://www.cantinailpignetto.com/it/cantine-lago-di-garda" + "#" + anchorToGo); } } }); } }); let slideH; let slider; const overTheSlideElements = [ { selector: '.contact-fixed-wrapper', case: 'slide' },{ selector: '.container-color', case: 'css', range: { rangeElement: window, rangeStart: 1500, //rangeStopAtPercentage: XX }, start: 0, end: 100, css: 'background: color-mix(in srgb, #25421a VAL%, #ffffff)', secondary_targets: [ { selector: '.text-color', css: 'color: color-mix(in srgb, #ffffff VAL%, #000000)' }, { selector: '.text-color-2', css: 'color: color-mix(in srgb, #ffffff VAL%, #736a62)' } ] },{ selector: '.floating-img', case: 'css', range: { rangeElement: window, }, start: 100, end: 0, css: 'transform: translateY(VALpx)' },{ selector: '.floating-img-2', case: 'css', range: { rangeElement: window, }, start: 0, end: -100, css: 'transform: translateY(VALpx)' },{ selector: '.floating-img-3', case: 'css', range: { rangeElement: window, }, start: 0, end: -50, css: 'transform: translateY(VALpx)' },{ selector: '.scaling-bg-elem', case: 'css', range: { rangeElement: window, }, start: 1, end: 1.1, css: 'transform: scale(VAL)' },{ selector: '#storia-slider-container', child: '.storia-slider', case: 'scroll-slider', range: { rangeElement: window, }, css: 'transform: translateX(VALpx)' },{ selector: '#storia-slide-wrapper-1', case: 'scroll-h', range: { rangeElement: window, }, start: 0, end: 100, css: 'background: color-mix(in srgb, #ffffff VAL%, #ebf0e9)', },{ selector: '#storia-slide-wrapper-2', case: 'scroll-h', range: { rangeElement: window, }, start: 0, end: 100, css: 'background: color-mix(in srgb, #ffffff VAL%, #26431b)', },{ selector: '.scroll-h-elem', case: 'scroll-h', range: { rangeElement: window, } },{ selector: '#storia-mobile-wrapper-1', case: 'css', range: { rangeElement: window, }, start: 0, end: 100, css: 'background: color-mix(in srgb, #ffffff VAL%, #26431b)', secondary_targets: [ { selector: '.text-color', css: 'color: color-mix(in srgb, #736a62 VAL%, #ffffff)' } ] },{ selector: '#storia-mobile-wrapper-2', case: 'css', range: { rangeElement: window, }, start: 0, end: 100, css: 'background: color-mix(in srgb, #ffffff VAL%, #26431b)', secondary_targets: [ { selector: '.text-color', css: 'color: color-mix(in srgb, #736a62 VAL%, #ffffff)' } ] } ]; /* ,{ selector: '#storia-slide-wrapper-1', case: 'css', range: { rangeElement: window, }, start: 0, end: 100, css: 'background: color-mix(in srgb, #ebf0e9 VAL%, #ffffff)', } */ function getScrollPercentage(range, element, startParam, endParam) { const elemRect = element.getBoundingClientRect(); let percentage = ((range.totalRange - elemRect.top) / (range.totalRange * (range.stopAtPercentage / 100))) * 100; percentage = Math.max(0, Math.min(100, percentage)); const mappedValue = startParam + (percentage / 100) * (endParam - startParam); return mappedValue; } function getFullScrollPercentage(element, startParam, endParam) { const rect = element.getBoundingClientRect(); const viewportHeight = window.innerHeight; const totalDistance = viewportHeight - rect.height; const currentProgress = rect.top; let percentage = totalDistance !== 0 ? (currentProgress / totalDistance) * 100 : 0; percentage = Math.max(0, Math.min(100, percentage)); const mappedValue = startParam + (percentage / 100) * (endParam - startParam); return mappedValue; } function getHorizontalScrollPercentage(element, startParam, endParam) { const rect = element.getBoundingClientRect(); const viewportWidth = window.innerWidth; const totalDistance = rect.width; const currentProgress = viewportWidth - rect.left; let percentage = (currentProgress / totalDistance) * 100; percentage = Math.max(0, Math.min(100, percentage)); if(percentage > 50) { element.classList.add("in-view"); } else if(percentage == 0) { element.classList.remove("in-view"); } const mappedValue = startParam + (percentage / 100) * (endParam - startParam); return mappedValue; } function handleElements() { overTheSlideElements.forEach(config => { const elements = document.querySelectorAll(config.selector); switch (config.case) { // Over the slide trigger case 'slide': elements.forEach(element => { const elementRecTop = element.getBoundingClientRect(); const scrolled = window.scrollY; const slider = document.getElementById("slide"); if(slider) { slideH = slider.getBoundingClientRect().height; } else { slideH = 0; } if((elementRecTop.top + scrolled) > slideH) { element.classList.add("active"); } else { element.classList.remove("active"); } }); break; // CSS transition case 'css': case 'scroll-slider': elements.forEach(element => { let range = { totalRange: config.range.rangeElement.innerHeight, stopAtPercentage: 100, }; if (config.range.rangeStart) { range.totalRange -= config.range.rangeStart; } if (config.range.rangeStopAtPercentage) { range.stopAtPercentage = config.range.rangeStopAtPercentage; } let value; if(config.case == 'scroll-slider') { const innerSlider = document.querySelector(config.child); const elemWidth = (innerSlider.scrollWidth) - (innerSlider.clientWidth); value = getFullScrollPercentage(element, 0, -elemWidth); } else { value = getScrollPercentage(range, element, config.start, config.end); } const cssValue = config.css.replace('VAL', value); const [property, val] = cssValue.split(':').map(s => s.trim()); const camelProperty = property.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase()); let targetElement = element; if (config.child) { const childElement = element.querySelector(config.child); if (childElement) { targetElement = childElement; } } if(config.secondary_targets) { config.secondary_targets.forEach(config => { const innerElements = element.querySelectorAll(config.selector); innerElements.forEach(innerElement => { const cssValue = config.css.replace('VAL', value); const [property, val] = cssValue.split(':').map(s => s.trim()); const camelProperty = property.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase()); let targetinnerElement = innerElement; targetinnerElement.style[camelProperty] = val; }); }); } targetElement.style[camelProperty] = val; }); break; // Horizontal scroll case 'scroll-h': elements.forEach(element => { let range = { totalRange: config.range.rangeElement.clientWidth, stopAtPercentage: 100, }; if (config.range.rangeStart) { range.totalRange -= config.range.rangeStart; } if (config.range.rangeStopAtPercentage) { range.stopAtPercentage = config.range.rangeStopAtPercentage; } value = getHorizontalScrollPercentage(element, config.start, config.end); let targetElement = element; if (config.css) { const cssValue = config.css.replace('VAL', value); const [property, val] = cssValue.split(':').map(s => s.trim()); const camelProperty = property.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase()); targetElement.style[camelProperty] = val; } if (config.child) { const childElement = element.querySelector(config.child); if (childElement) { targetElement = childElement; } } if(config.secondary_targets && config.css) { config.secondary_targets.forEach(config => { const innerElements = document.querySelectorAll(config.selector); innerElements.forEach(innerElement => { const cssValue = config.css.replace('VAL', value); const [property, val] = cssValue.split(':').map(s => s.trim()); const camelProperty = property.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase()); let targetinnerElement = innerElement; targetinnerElement.style[camelProperty] = val; }); }); } }); break; default: break; } }); } // Quando il DOM è pronto e completamente caricato document.addEventListener('DOMContentLoaded', () => { handleElements(); window.addEventListener('scroll', handleElements, { passive: true }); window.addEventListener('resize', handleElements, { passive: true }); }); /* -------------------- ROAMING ELEMENTS ----------------------- */ $(window).on('load', function() { if($(".roaming-elem").length > 0) { // roaming elements const cursors = document.querySelectorAll(".roaming-elem"); // variables let mouseX = 0; let mouseY = 0; let lastWindowY = 0; document.addEventListener("mousemove", function (e) { // Get mouse X position relative to the page mouseX = e.pageX; // Get mouse Y position relative to the page mouseY = e.pageY; // Get the last window.scrollY after moving lastWindowY = window.scrollY; cursors.forEach(cursor => { // cursor container const cursorContainer = cursor.closest(".roaming-container"); const cursorContainerRect = cursorContainer.getBoundingClientRect(); // apply X pos to the cursor cursor.style.left = (mouseX - cursorContainerRect.left) + "px"; // apply Y pos to the cursor minus the offset top of the container cursor.style.top = (mouseY - window.scrollY - cursorContainerRect.top) + "px"; const halfArrowContainer = cursor.closest(".half-roaming-arrow-container"); if(halfArrowContainer) { const cursorLeft = cursor.getBoundingClientRect().left; const halfPageWidth = window.innerWidth/2; if(cursorLeft > halfPageWidth) { halfArrowContainer.classList.add("right"); halfArrowContainer.classList.remove("left"); } else { halfArrowContainer.classList.remove("right"); halfArrowContainer.classList.add("left"); } } }); }); window.addEventListener("scroll", function () { cursors.forEach(cursor => { // cursor container const cursorContainer = cursor.closest(".roaming-container"); const cursorContainerRect = cursorContainer.getBoundingClientRect(); if(window.innerWidth > 767) { // apply X pos to the cursor cursor.style.left = (mouseX - cursorContainerRect.left) + "px"; // apply Y pos to the cursor minus the offset top of the container cursor.style.top = (mouseY - window.scrollY - cursorContainerRect.top) + "px"; } }); }); } }); $(window).on('load', function() { const navLinks = document.querySelectorAll("#menu-top .nav-link"); navLinks.forEach(link => { const topContent = link.closest("#top_content"); link.addEventListener("mouseenter", function() {topContent.classList.add("hover");}); link.addEventListener("mouseleave", function() {topContent.classList.remove("hover");}); }); }); // PARALLAX $(window).on('load', function () { window.addEventListener('scroll', function () { const windowHeight = window.innerHeight; const scrolled = window.scrollY; if ($('.parallax').length > 0) { document.querySelectorAll('.parallax').forEach(function (parallax) { const container = parallax.parentElement; const containerTop = container.getBoundingClientRect().top + scrolled; const containerHeight = container.offsetHeight; const parallaxHeight = parallax.offsetHeight; // Calcolo la posizione del container all'interno della viewport // Da 0 a 1 const progress = (scrolled + windowHeight - containerTop) / (containerHeight + windowHeight); // Aggiustamente del translateY per mantenere l'immagine centrata const translateY = Math.min(Math.max(progress * (parallaxHeight - containerHeight), 0), parallaxHeight - containerHeight); parallax.style.transform = `translateY(-${translateY}px) translateX(-50%)`; }); } }); }); /* -------------------- NEWSLETTER ----------------------- */ function newsletter_positive_response(element, datiJSON, value_class_hide) { $('#modal_newsletter').modal('hide'); $('#form_newsletter_ajax')[0].reset(); // sistema la sidebar $('#modal_result_newsletter .modal-body').html(datiJSON.positive_response); $('#modal_result_newsletter').modal('show'); setTimeout(function() {$('#modal_result_newsletter').modal('hide');}, 3000); } var isGliderLoaded = false; $( document ).on('inizialize', function() { isGliderLoaded = false; }); /* -------------------- GLIDER SLIDER ----------------------- */ $(window).on("load resize scroll", function() { if ($(".glider").length > 0) { if ($(".glider").isInViewport(-10) && !isGliderLoaded) { $('', { rel: 'stylesheet', type: 'text/css', href: 'https://www.cantinailpignetto.com/css/glider.min.css' }).appendTo('head'); isGliderLoaded = true; loadScript("https://www.cantinailpignetto.com/js/glider.min.js").then(function() { loadScript("https://www.cantinailpignetto.com/js/glider.clm.min.js.php").then(function() {}); }); } } }); /* -------------------- SLICK SLIDER ----------------------- */ let isSliderLoaded = false; $( document ).on('inizialize', function() { isSliderLoaded = false; }); $(window).on("load resize scroll", function() { if ($(".slider").length > 0) { if ($(".slider").isInViewport(-10) && !isSliderLoaded) { $('', { rel: 'stylesheet', type: 'text/css', href: 'https://www.cantinailpignetto.com/css/slick.min.css' }).appendTo('head'); $('', { rel: 'stylesheet', type: 'text/css', href: 'https://www.cantinailpignetto.com/css/slick-theme.min.css' }).appendTo('head'); isSliderLoaded = true; loadScript("https://www.cantinailpignetto.com/js/slick.min.js").then(function() { loadScript("https://www.cantinailpignetto.com/js/slick.clm.min.js.php").then(function() {}); }); } } }); /* ----------------------- FAQ -------------------------- */ $(window).on('load', function() { const faqBox = document.getElementById('box_faq'); if(faqBox) { faqBox.querySelectorAll('.card')[0].classList.add('open'); $(faqBox).on('show.bs.collapse', function(e) { const accordion = e.target.closest(".card"); accordion.classList.add('open'); }); $(faqBox).on('hide.bs.collapse', function(e) { const accordion = e.target.closest(".card"); accordion.classList.remove('open'); }); } }); /* ----------------------- CAMPI DATE -------------------------- */ $(window).on('load', function() { if ($('.cmsdate').length > 0) { var lang = getCookie('lang'); $('', { rel: 'stylesheet', type: 'text/css', href: 'https://www.cantinailpignetto.com/css/bootstrap-datepicker.min.css' }).appendTo('head'); loadScript("https://www.cantinailpignetto.com/js/bootstrap-datepicker.min.js").then(function() { loadScript("https://www.cantinailpignetto.com/js/bootstrap-datepicker."+lang+".min.js").then(function() { loadScript("https://www.cantinailpignetto.com/js/cmsdate.min.js.php").then(function() {}); }); }); } }); // CARICA FILE let $filesToUploadContainer = undefined; let $filesToUploadList = undefined; let $filesToUploadInput = undefined; let $filesToUploadInputArray = undefined; $(document).on('inizialize', function() { $filesToUploadContainer = undefined; $filesToUploadList = undefined; $filesToUploadInput = undefined; $filesToUploadInputArray = undefined; }); function setFilesToUploadElement(el) { $filesToUploadContainer = $(el).closest('[data-type="filesToUpload"]'); $filesToUploadList = $filesToUploadContainer.find('[data-id="fileList"]'); $filesToUploadInputArray = $filesToUploadContainer.find('[data-id="filesToUpload"]'); } function updateFileList() { $filesToUploadList.html(''); if ($filesToUploadInputArray.length == 1) { $filesToUploadList.append('
  • Nessun file trovato
  • '); } else { for (let i = 0; i < $filesToUploadInputArray.length - 1; i++) { $value = $filesToUploadInputArray[i]; files = $value.files[0]; files.idx = i; if (files.type.match('image.*')) { let reader = new FileReader(); reader.onload = (function(theFile) { return function(e) { $filesToUploadList.append('
  • x
  • '); }; })(files); // Read in the image file as a data URL. reader.readAsDataURL(files); } else { $filesToUploadList.append('
  • ' + files.name + ' x
  • '); } }; } } $(document).on('click', '[data-id="fileList"] li.success span', function() { setFilesToUploadElement(this); const indexLi = $(this).attr('data-id'); element = $filesToUploadInputArray[indexLi]; $(element).detach(); setFilesToUploadElement(this); updateFileList(); }); function errorFileList(msg) { // cancella elemento caricato $filesToUploadInput.val(''); updateFileList(); $filesToUploadList.append('
  • ' + msg + '
  • '); } // carica l'immagine $(document).on('change', '[data-id="filesToUpload"]', function(event) { // recupero elementi associati all'input $filesToUploadInput = $(this); setFilesToUploadElement(this); const currentFiles = event.target.files; const num_files = currentFiles.length; let max_files = $filesToUploadContainer.attr('data-max-files'); let max_size = $filesToUploadContainer.attr('data-max-size'); let type_mime = ""; if (max_files === undefined) { max_files = 1; } if (max_size === undefined) { max_size = 5; } if ((($filesToUploadInputArray.length - 1) + num_files) > max_files) { let txt_max_files = 'ERRORE: Puoi caricare massimo {num} file'; txt_max_files = txt_max_files.replace("{num}", max_files); errorFileList(txt_max_files); return; } for (i = 0; i < num_files; i++) { const file = event.target.files[i]; if (file.size >= max_size*1024*1024) { let txt_max_size = 'ERRORE: Dimensione massima di {num} Mb'; txt_max_size = txt_max_size.replace("{num}", max_size); errorFileList('File: '+file.name+' - '+txt_max_size); return; } const matchAccepter = $filesToUploadInput.attr('accept').split(','); let accept_ok = false; for (a=0; a < matchAccepter.length; a++) { if (file.type.match(matchAccepter[a])) accept_ok = true; } if (!accept_ok) { errorFileList('File: '+file.name+' - ERRORE: Formato del file non valido'); return; } $clone = $filesToUploadInput.clone(); $filesToUploadInput.parent().append($clone); $filesToUploadInput.removeClass('no-send'); setFilesToUploadElement(this); } updateFileList(); }); /* GESTIONE CALENDARIO DEGUSTAZIONI */ $(window).on('load', function () { setTimeout(function() { if ($('.cmsvisite').length > 0) { getDatesDisabled(new Date()); $('.cmsvisite').datepicker().on('changeYear', function (e) { getDatesDisabled(new Date(e.date)); }); $('.cmsvisite').datepicker().on('changeMonth', function (e) { getDatesDisabled(new Date(e.date)); }); } },500); }); function getDatesDisabled(dtDate) { const currMonth = dtDate.getMonth() + 1; const currYear = dtDate.getFullYear(); $.ajax({ type: "POST", url: 'https://www.cantinailpignetto.com/admin/includes/ajax/ajax_frontend.php', cache: false, // To unable request pages to be cached data: { module: "calendar", type: "get_datesdisabled", month: currMonth, year: currYear }, dataType: 'text' }).done(function (data) { dataJSON = JSON.parse(data); $('.cmsvisite').datepicker('setDatesDisabled', dataJSON); $('.cmsvisite').datepicker('_setDate', dtDate, 'view'); }); }$(window).on('load', function(){ /*const wineMainContent = wineItem.querySelector('.container-wine-top'); const categoryColor = wineMainContent.attributes['data-category-color']['value']; wineMainContent.style.backgroundColor = categoryColor;*/ });$(window).on('load', function(){ const tastingForm = document.getElementById("tasting-form"); if(tastingForm) { const tastingPathField = tastingForm.querySelector("#tasting_paths"); const tastingGuestsField = tastingForm.querySelector("#partecipanti"); const tastingNonDrinkersField = tastingForm.querySelector("#non-bevitori"); const tastingKidsField = tastingForm.querySelector("#bambini"); const preferencesFields = document.querySelectorAll(".num_preferenze"); if(preferencesFields.length > 0) { preferencesFields.forEach(field => { field.addEventListener('input', (e) => { doTastingSummary(tastingForm); }); }); } if(tastingPathField) { tastingPathField.addEventListener('input', (e) => { if(tastingGuestsField && tastingGuestsField.value != '') { doTastingSummary(tastingForm); tastingForm.querySelector("#tasting-summary").classList.add("visible"); } else { tastingForm.querySelector("#tasting-summary").classList.remove("visible"); } }); } if(tastingGuestsField) { tastingGuestsField.addEventListener('input', (e) => { if(tastingPathField && tastingPathField.value != '') { doTastingSummary(tastingForm); tastingForm.querySelector("#tasting-summary").classList.add("visible"); } else { tastingForm.querySelector("#tasting-summary").classList.remove("visible"); } }); } if(tastingNonDrinkersField) { tastingNonDrinkersField.addEventListener('input', (e) => { doTastingSummary(tastingForm); }); } if(tastingKidsField) { tastingKidsField.addEventListener('input', (e) => { doTastingSummary(tastingForm); }); } } const giftTastingForm = document.getElementById("gift_tasting-form"); if(giftTastingForm) { const giftTastingListField = document.getElementById("gift_tasting_paths"); const priceField = giftTastingForm.querySelector("#importo_buono"); giftTastingListField.addEventListener('change', (e) => { const el = e.target; const tastingSelected = el.options[el.selectedIndex]; const tastingPrice = parseInt(tastingSelected.getAttribute("data-price")); const numVouchers = parseInt(giftTastingForm.querySelector("#numero_buoni").value); let totalAmount = 0; if(!isNaN(numVouchers)) { totalAmount = tastingPrice*numVouchers; } giftTastingForm.querySelector("#numero_buoni").setAttribute("data-voucher-price",tastingPrice); giftTastingForm.querySelector('input[name="voucher_amount"]').value = totalAmount; const keyupEvent = new KeyboardEvent("keyup", { key: "Enter", code: "Enter", keyCode: 13, // Per compatibilità con script più vecchi bubbles: true, cancelable: true }); priceField.value = totalAmount; priceField.dispatchEvent(keyupEvent); }); const voucherNumField = giftTastingForm.querySelector("#numero_buoni"); if(voucherNumField) { voucherNumField.addEventListener("input", (e) => { const el = e.target; const numVouchers = parseInt(el.value); const voucherPrice = parseInt(el.getAttribute("data-voucher-price")); let totalAmount = 0; if(!isNaN(numVouchers)) { totalAmount = numVouchers*voucherPrice; } giftTastingForm.querySelector('input[name="voucher_amount"]').value = totalAmount; priceField.value = totalAmount; }); } } const giftVoucherForm = document.getElementById("giftCard"); if(giftVoucherForm) { const priceField = giftVoucherForm.querySelector("#importo_buono"); priceField.addEventListener("input", (e) => { const el = e.target; const voucherVal = parseInt(el.value); document.querySelector('input[name="voucher_amount"]').value = voucherVal; }); } }); function doTastingSummary(form) { const tastinForm = form; const tastingSummaryBox = tastinForm.querySelector("#tasting-summary"); const tastingName = tastinForm.querySelector("#tasting_paths"); const tastingGuests = parseInt(tastinForm.querySelector("#partecipanti").value) || 0; const tastingSelected = tastingName.options[tastingName.selectedIndex]; /* MAIN GUEST ROW */ const mainGuestRow = tastinForm.querySelector("#guest-row"); const tastingPrice = parseInt(tastingSelected.getAttribute("data-price")); const mainGuestTotalPrice = tastingPrice*tastingGuests; mainGuestRow.querySelector(".tasting-recap-name").innerHTML=tastingName.value; mainGuestRow.querySelector(".tasting-recap-single-price").innerHTML="("+tastingPrice+" €)"; mainGuestRow.querySelector(".tasting-recap-guests").innerHTML=tastingGuests; mainGuestRow.querySelector(".tasting-pretotal-value").innerHTML=mainGuestTotalPrice; /* NON-DRINKERS ROW */ const nonDrinkersRow = tastinForm.querySelector("#nonDrinkers-row"); const nonDrinkersNum = parseInt(tastinForm.querySelector("#non-bevitori").value) || 0; let nonDrinkersTotalPrice = 0; if(!isNaN(nonDrinkersNum) && nonDrinkersNum > 0) { const nonDrinkersSinglePrice = parseInt(nonDrinkersRow.querySelector(".tasting-recap-single-price").getAttribute("data-non-drinkers-price")); nonDrinkersTotalPrice = nonDrinkersSinglePrice*nonDrinkersNum; nonDrinkersRow.querySelector(".tasting-pretotal-value").innerHTML=nonDrinkersTotalPrice; nonDrinkersRow.querySelector(".tasting-recap-guests").innerHTML=nonDrinkersNum; nonDrinkersRow.classList.remove("not-visible-row"); } else { if(!nonDrinkersRow.classList.contains("not-visible-row")) { nonDrinkersRow.classList.add("not-visible-row"); } } /* KIDS ROW */ const kidsRow = tastinForm.querySelector("#kids-row"); const kidsNum = parseInt(tastinForm.querySelector("#bambini").value) || 0; let kidsTotalPrice = 0; if(!isNaN(kidsNum) && kidsNum > 0) { const kidsSinglePrice = parseInt(kidsRow.querySelector(".tasting-recap-single-price").getAttribute("data-kids-price")); kidsTotalPrice = kidsSinglePrice; kidsRow.querySelector(".tasting-pretotal-value").innerHTML=kidsTotalPrice; kidsRow.querySelector(".tasting-recap-guests").innerHTML=kidsNum; kidsRow.classList.remove("not-visible-row"); } else { if(!kidsRow.classList.contains("not-visible-row")) { kidsRow.classList.add("not-visible-row"); } } /* PREFERENCES ROW */ const preferencesFields = document.querySelectorAll(".num_preferenze"); const totalGuests = tastingGuests + nonDrinkersNum + kidsNum; let preferencesNum = 0; if(preferencesFields.length > 0) { preferencesFields.forEach(field => { if(!field.classList.contains("no-send")) { preferencesNum += parseInt(field.value); } }); } /* TOTAL ROW */ const totalRow = tastinForm.querySelector("#total-row"); const totalPrice = mainGuestTotalPrice+nonDrinkersTotalPrice; totalRow.querySelector(".tasting-total-value").innerHTML=totalPrice; tastinForm.querySelector("input[name='voucher_amount']").value=totalPrice; /* ALERT SECTION */ const tastingMinGuests = parseInt(tastingSelected.getAttribute("data-min-guests")); const tastingMaxGuests = parseInt(tastingSelected.getAttribute("data-max-guests")); tastinForm.querySelector("input[name='num_people']").value=tastingGuests+nonDrinkersNum+kidsNum; if(tastingMinGuests != '' && tastingGuests < tastingMinGuests) { tastinForm.classList.add("alert-min"); tastingSummaryBox.querySelector(".tasting-summary-alert-min-val").innerHTML=tastingMinGuests; } else { tastinForm.classList.remove("alert-min"); } if(tastingMaxGuests != '' && tastingGuests > tastingMaxGuests) { tastinForm.classList.add("alert-max"); tastingSummaryBox.querySelector(".tasting-summary-alert-max-val").innerHTML=tastingMaxGuests; } else { tastinForm.classList.remove("alert-max"); } if(preferencesNum > totalGuests) { tastinForm.classList.add("alert-preferences"); } else { tastinForm.classList.remove("alert-preferences"); } } let formOrdersContainer; let winesTotalField; let summaryList; let summaryTotal; $(window).on('load', function () { const countrySelect = document.getElementById('countries'); const prefixField = document.getElementById('prefisso'); if (countrySelect) { countrySelect.addEventListener('input', (e) => { const selectedOption = e.target.selectedOptions[0]; const prefix = selectedOption.getAttribute("data-prefix"); if (prefixField) { prefixField.value = prefix; } }); } formOrdersContainer = document.getElementById('orderForm'); if(formOrdersContainer) { const formOrders = formOrdersContainer.querySelector('.form-panels-container'); winesTotalField = document.getElementById("totale_bottiglie"); summaryList = document.getElementById("summaryList"); summaryTotal = document.getElementById("summaryTotal"); document.querySelectorAll('.next-step-btn').forEach(button => { button.addEventListener('click', function (e) { e.preventDefault(); const currentStep = this.closest('.form-panel'); const inputs = currentStep.querySelectorAll('input, select, textarea'); let allValid = false; switch(e.target.getAttribute('id')) { case 'btn-step-1': let goOn = true; for (let input of inputs) { if (!input.checkValidity()) { input.reportValidity(); // <--- Forza la comparsa del fumetto di sistema goOn = false; break; // Ci fermiamo al primo errore per non mostrare 10 fumetti insieme } } if(goOn) { allValid = true; } else { allValid = false; } break; case 'btn-step-2': const numBottles = parseInt(winesTotalField.value); // Calcolo se il numero di bottiglie è maggiore di 6 e multiplo di 6 allValid = !isNaN(numBottles) && numBottles >= 6 && numBottles % 6 === 0; if (!allValid) { $("#errTotalBottles").fadeIn(); } else { $("#errTotalBottles").fadeOut(); } break; case 'btn-step-3': break; default: break; } if (allValid) { $('#orderForm_anchor')[0].scrollIntoView({ behavior: 'smooth', block: 'start' }); goToNextStep(parseInt(currentStep.getAttribute("data-panel"))); } else { e.stopPropagation(); } }); }); document.querySelectorAll('.prev-step-btn').forEach(button => { button.addEventListener('click', function (e) { goToPrevStep(); }); }); document.querySelectorAll('.wine-selector-btn').forEach(button => { button.addEventListener('click', function (e) { const wineWrapper = this.closest(".wine-selector"); const wineField = wineWrapper.querySelector(".form-fields"); const wineFieldToSend = wineWrapper.querySelector(".wine-bottles-num"); const wineFieldVal = parseInt(wineField.value); const winesTotalFieldVal = parseInt(winesTotalField.value); if(this.classList.contains("winePlus")) { wineField.value = wineFieldVal + 1; wineFieldToSend.value = wineFieldVal + 1; winesTotalField.value = winesTotalFieldVal + 1; wineFieldToSend.classList.remove("no-send"); } else { if(wineFieldVal > 0) { wineField.value = wineFieldVal - 1; wineFieldToSend.value = wineFieldVal - 1; if(winesTotalFieldVal > 0) { winesTotalField.value = winesTotalFieldVal - 1; } if(wineFieldVal == 1) { wineFieldToSend.value = ""; wineFieldToSend.classList.add("no-send"); } } } }); }); } }); function goToNextStep(currentStep) { switch(currentStep) { case 1: formOrdersContainer.classList.remove("step-1"); $("#form-panel-1").hide(); formOrdersContainer.classList.add("step-2"); $("#form-panel-2").fadeIn(); break; case 2: formOrdersContainer.classList.remove("step-2"); $("#form-panel-2").hide(); formOrdersContainer.classList.add("step-3"); $("#form-panel-3").fadeIn(); summaryList.innerHTML = ""; summaryTotal.innerHTML = ""; document.querySelectorAll('.wine-bottles-num').forEach(field => { const fieldVal = parseInt(field.value); if(fieldVal > 0 && fieldVal != undefined) { const wineName = field.getAttribute("data-label"); const wineRow = '
    '+wineName+'
    '+fieldVal+'
    '; summaryList.insertAdjacentHTML('beforeend', wineRow); summaryTotal.innerHTML = parseInt(winesTotalField.value); } }); break; default: break; } } function goToPrevStep() { const formOrdersClasses = formOrdersContainer.classList; if(formOrdersClasses.contains("step-3")) { formOrdersClasses.remove("step-3"); $("#form-panel-3").hide(); formOrdersClasses.add("step-2"); $("#form-panel-2").fadeIn(); } else if(formOrdersClasses.contains("step-2")) { formOrdersClasses.remove("step-2"); $("#form-panel-2").hide(); formOrdersClasses.add("step-1"); $("#form-panel-1").fadeIn(); } }$(window).on('load', function(){ });$(window).on('load', function(){ }); $(window).scroll(function () { if($("#blog-sing").length > 0 && window.innerWidth > 991) { var topHeight = $("#top_content").height(); var imgHeight = $(".img-blog").height(); var actualScroll = $(window).scrollTop() + topHeight; var formOffsetTop = ($(".blog-cat").offset().top) + ($(".blog-cat").innerHeight()); var endPoint = ($(".article-form-side").offset().top) + ($(".article-form-side").innerHeight()); if (actualScroll > formOffsetTop && (actualScroll + window.innerHeight) < endPoint) { var addedTop = actualScroll - topHeight - imgHeight; $("#moveAnalisiAside").css({"top": addedTop + "px"}); } else if (actualScroll <= formOffsetTop) { $("#moveAnalisiAside").css({"top":"auto"}); } } /* var $blog_cat = $('.blog-cat'); var $header = $('header'); var $main = $('main'); var $box_analisi = $('#moveAnalisiAside'); if ($box_analisi.length == 0) { return; } var top = $blog_cat.outerHeight() + $blog_cat.offset().top; var width = $(window).width(); if ($(this).scrollTop() > top) { if (width < 992) { $box_analisi.css('top', "auto"); $box_analisi.css('bottom', 'auto'); } else if (width < 1200) { if (($(this).scrollTop() + $box_analisi.outerHeight()) >= $main.outerHeight()) { $box_analisi.css('top', 'auto'); $box_analisi.css('bottom', '0'); } else { $box_analisi.css('top', $(this).scrollTop()-$box_analisi.outerHeight()+50+"px"); $box_analisi.css('bottom', 'auto'); } } else { if (($(this).scrollTop() + $box_analisi.outerHeight()) >= $main.outerHeight()) { $box_analisi.css('top', 'auto'); $box_analisi.css('bottom', '0'); } else { $box_analisi.css('top', $(this).scrollTop()-$box_analisi.outerHeight()+"px"); $box_analisi.css('bottom', 'auto'); } } } else { $box_analisi.css('top', "auto"); $box_analisi.css('bottom', 'auto'); }*/ });