jQuery(document).ready(function($) { let sailingDaysData = []; // To store all sailing day data // Retrieve the default departure port from the data attribute // const departurePort = $('#sailing-schedule-widget').data('departure-port'); const departurePort = $('#sailing-schedule-widget').data('departure-port') || 'default-port'; let currentStartDate = new Date(); // console.log("Initial Departure Port:", departurePort); // For debugging // Function to fetch and render sailing data for the carousel function fetchSailingData() { $.ajax({ url: ajax_object.ajaxUrl, // Use the ajaxUrl variable defined in PHP method: 'POST', data: { action: 'get_sailing_day_data', departure_port: departurePort, start_date: currentStartDate.toISOString().split('T')[0], // Format to YYYY-MM-DD }, success: function(response) { if (response.success && response.data.length > 0) { sailingDaysData = response.data; renderCarousel(sailingDaysData); } else { console.warn("No data returned from AJAX"); } }, error: function(xhr, status, error) { console.error("AJAX Error:", status, error); } }); } // Function to render the carousel with sailing day data function renderCarousel(data) { carouselSlides.empty(); data.forEach(day => { // const formattedDate = new Date(day.title).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: '2-digit' }); const formattedDate = new Date(day.title.substring(0, 10)).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: '2-digit' }); const dayContent = day.has_day_sailing ? 'Day' : ''; const nightContent = day.has_night_sailing ? 'Night' : ''; carouselSlides.append(` `); }); // Bind click events to each carousel slide to update panel content $('.carousel-slide').on('click', function () { const postId = $(this).data('post-id'); const selectedDay = sailingDaysData.find(day => day.post_id === postId); if (selectedDay) { updatePanelContent(selectedDay); setActiveBorder(this); } }); if (data.length > 0) { $('.carousel-slide').first().click(); } } // Carousel scrolling functionality $('#carousel-prev').on('click', function() { carouselSlides.animate({ scrollLeft: '-=' + slideWidth }, 300); // Scroll left by one slide }); $('#carousel-next').on('click', function() { carouselSlides.animate({ scrollLeft: '+=' + slideWidth }, 300); // Scroll right by one slide }); // Function to update the panel content based on the selected day data function updatePanelContent(dayData) { function formatTime(datetime) { if (!datetime) return '-'; const date = new Date(datetime); return isNaN(date) ? '-' : date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); } document.querySelector('.daydepart').innerText = formatTime(dayData.daydeparturetime); document.querySelector('.nightdepart').innerText = formatTime(dayData.nightdeparturetime); document.querySelector('.dayarrive').innerText = formatTime(dayData.dayarrivaltime); document.querySelector('.nightarrive').innerText = formatTime(dayData.nightarrivaltime); } function setActiveBorder(selectedItem) { $('.carousel-slide').css('border', 'none'); $(selectedItem).css('border', '1px solid black'); } fetchSailingData(); // Initial fetch }); const sailingDayWidget = { departsLocationCurrent: null, departsLocationSwitch: null, listingElement: null, eventSailingHandler: null, init: function () { let self = this; self.listingElement = jQuery('#query-sailing-by-departsfrom'); if(!self.listingElement.length) return; self.departsLocationCurrent = departsLocationCurrent ?? ''; self.departsLocationSwitch = departsLocationSwitch ?? ''; self.setupSailingSlider(); // self.setupFilterTypeSelect(); // self.setupFilterTypeSelectTrigger(); self.setupFilterTypeSearchTrigger(); self.setupFilterDate(); }, setupSailingSlider: function () { let self = this; const slider = self.listingElement.find('.jet-listing-grid__items'); self.listingElement.on('init', '.jet-listing-grid__items', function (event, slick, direction) { setTimeout(() => { // jQuery(event.target).slick('slickSetOption', 'centerPadding', '0px', true); if (window.innerWidth > 1024) { jQuery(event.target).slick('slickSetOption', 'centerPadding', '0px', true); } self.setupSailingEvent(); }, 500); }); self.listingElement.on('afterChange', function(event, slick, currentSlide){ self.listingElement.find(`.jet-listing-grid__item[data-slick-index="${currentSlide}"]`).trigger('click'); }); }, setupSailingEvent: function () { let self = this; if (self.eventSailingHandler) { self.listingElement.off('click', '.jet-listing-grid__item.slick-slide', self.eventSailingHandler); } self.eventSailingHandler = function (event) { const _this = this; const postId = jQuery(_this).data('post-id'); self.updatePanelContent(postId); const slider = self.listingElement.find('.slick-initialized'); if (slider.length > 0) { const slickIndex = jQuery(_this).data('slick-index'); const centerMode = slider.slick('slickGetOption', 'centerMode'); if (window.innerWidth > 1024) { if (slickIndex > 2) { if (!centerMode) { slider.slick('slickSetOption', 'centerMode', true, true); } } else { if (centerMode) { slider.slick('slickSetOption', 'centerMode', false, true); } } } slider.slick('slickGoTo', slickIndex); } }; self.listingElement.on('click', '.jet-listing-grid__item.slick-slide', self.eventSailingHandler); // mane let today = new Date(); today.setDate(today.getDate() - 1); let todayFormatted = today.toISOString().split("T")[0]; let selectedItem = self.listingElement.find(`.jet-listing-grid__item [data-post-slug*="${todayFormatted}"]`); if (selectedItem.length > 0) { selectedItem.trigger('click'); } else { self.listingElement.find('.jet-listing-grid__item[data-slick-index="0"]').trigger('click'); } // self.listingElement.find('.jet-listing-grid__item[data-slick-index="0"]').trigger('click'); }, // setActiveItem: function (current) { // let self = this; // self.listingElement.find('.jet-listing-grid__item').removeClass('sailing-day-active').filter(current).addClass('sailing-day-active'); // jQuery(current).addClass('sailing-day-active'); // }, // setupFilterTypeSelect: function () { // let self = this; // const searchText = self.departsLocationCurrent; // const selectFilter = jQuery('#departs-location-filter').find('select.jet-select__control'); // selectFilter.find('option').each(function () { // const option = jQuery(this); // if (option.text().trim().toLowerCase() === searchText.trim().toLowerCase()) { // option.prop('selected', true); // return false; // } // }); // }, // setupFilterTypeSelectTrigger: function () { // let self = this; // const btnTrigger = jQuery('#departs-location-filter-trigger'); // const selectFilter = jQuery('#departs-location-filter').find('select.jet-select__control'); // let valueByText = ''; // btnTrigger.on('click', function () { // const searchText = self.departsLocationSwitch; // selectFilter.find('option').each(function () { // const option = jQuery(this); // if (option.text().trim().toLowerCase() === searchText.trim().toLowerCase()) { // valueByText = option.val(); // return false; // } // }); // selectFilter.val(valueByText).trigger('change'); // self.departsLocationSwitch = self.departsLocationCurrent; // self.departsLocationCurrent = searchText; // jQuery('#departs-location-text-current .elementor-heading-title').text(self.departsLocationCurrent); // jQuery('#departs-location-text-switch .elementor-heading-title').text(self.departsLocationSwitch); // }); // }, setupFilterDate: function () { let self = this; const btnChooseDate = jQuery('#choose-date-sailing'); // btnChooseDate // .find('.jet-date-period__datepicker-button') // .html(' Choose Date '); if (window.innerWidth <= 768) { btnChooseDate .find('.jet-date-period__datepicker-button') .html(' Choose your sailing date to view times '); } else { btnChooseDate .find('.jet-date-period__datepicker-button') .html(' Choose Date '); } btnChooseDate.on('change', '.jet-date-period__datepicker-input', function () { const _this = this; let value = jQuery(this).val(); const [year, month, day] = value.split('.'); value = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`; // console.log(value); self.listingElement.find(`.jet-listing-grid__item [data-post-slug*="${value}"]`).trigger('click'); btnChooseDate .find('.jet-date-period__datepicker-button') .html(' Choose Date '); if (window.innerWidth <= 768) { btnChooseDate .find('.jet-date-period__datepicker-button') .html(' Choose your sailing date to view times'); } else { btnChooseDate .find('.jet-date-period__datepicker-button') .html(' Choose Date '); } }); }, setupFilterTypeSearchTrigger: function () { let self = this; let currentSlickIndex = null; const btnTrigger = jQuery('#departs-location-filter-trigger'); const searchFilterInput = jQuery('#departs-location-filter .jet-search-filter__input'); const searchFilterSubmit = jQuery('#departs-location-filter .jet-search-filter__submit'); btnTrigger.on('click', function () { jQuery('#loading-gif').show(); jQuery('#container_gif').addClass('show-gif'); const searchText = self.departsLocationSwitch; searchFilterInput.val(searchText); searchFilterSubmit.click(); self.departsLocationSwitch = self.departsLocationCurrent; self.departsLocationCurrent = searchText; jQuery('#departs-location-text-current .elementor-heading-title').text(self.departsLocationCurrent); jQuery('#departs-location-text-switch .elementor-heading-title').text(self.departsLocationSwitch); self.listingElement.on('click', '.jet-listing-grid__item.slick-slide', function () { currentSlickIndex = jQuery(this).data('slick-index'); }); self.listingElement.on('afterChange', function(event, slick, currentSlide) { if (currentSlickIndex !== null && currentSlide === currentSlickIndex) { jQuery('#loading-gif').hide(); jQuery('#container_gif').removeClass('show-gif'); } }); // }); }, // Function to update panel content updatePanelContent: function (postId) { let self = this; fetch(`/wp-json/custom/v1/acf-data/${postId}`) .then((response) => response.json()) .then((data) => { // Update the panel with formatted ACF field times document.querySelector('.daydepart').innerText = self.formatTime(data.daydeparturetime); document.querySelector('.nightdepart').innerText = self.formatTime(data.nightdeparturetime); // console.log('Night departure time (formatted):', self.formatTime(data.nightdeparturetime)); document.querySelector('.dayarrive').innerText = self.formatTime(data.dayarrivaltime); document.querySelector('.nightarrive').innerText = self.formatTime(data.nightarrivaltime); // Conditionally add "From " if the date is not the fallback const dayDisembarkText = self.formatTime(data.dayarrivaltime); document.querySelector('.daydisembark').innerText = dayDisembarkText === '-' ? dayDisembarkText : `From ${dayDisembarkText}`; const nightDisembarkText = self.formatTime(data.nightarrivaltime); document.querySelector('.nightdisembark').innerText = nightDisembarkText === '-' ? nightDisembarkText : `From ${nightDisembarkText}`; }) .catch((error) => console.error('Error fetching post data:', error)); }, // Helper function to format datetime to HH:MM formatTime: function (datetime) { if (!datetime) return '-'; // console.log(datetime); // Split date and time parts (e.g., "31/10/2024 4:30 pm") const [datePart, timePart, meridiem] = datetime.split(' '); const [day, month, year] = datePart.split('/'); let [hours, minutes] = timePart.split(':'); // Convert hours to 24-hour format based on AM/PM const timePartC = `${timePart} ${meridiem}`; // console.log('period:', timePartC); const period = timePartC.slice(-2).toLowerCase(); hours = parseInt(hours, 10); if (period === 'pm' && hours < 12) hours += 12; if (period === 'am' && hours === 12) hours = 0; // Create a new date string in a format JavaScript can parse const formattedDate = `${year}-${month}-${day}T${String(hours).padStart(2, '0')}:${minutes.slice(0, 2)}`; // Parse the reformatted string and return just the time (HH:MM) const date = new Date(formattedDate); // return isNaN(date) ? '-' : date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); return isNaN(date) ? '-' : date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true, hourCycle: 'h23', }); }, }; document.addEventListener('DOMContentLoaded', function () { sailingDayWidget.init(); return; }); jQuery(document).ready(function($){ const badgeWrapper = document.querySelectorAll(".badge-wrapper"); badgeWrapper.forEach((wrap)=>{ const bgColor = wrap.querySelector(".badge-color .elementor-shortcode"); if(bgColor) wrap.style.backgroundColor = bgColor.innerHTML; }); }); (($) => { const form_container_id = 'form-group-booking'; const showThisFieldIf = { return_journey_date: [ { input: 'journey_type', operator: '!=', value: 'One Way' } ] }; function setupConditions($form) { for (const [conditionalInputID, conditions] of Object.entries(showThisFieldIf)) { conditions.forEach(({ input: inputID }) => { const $input = getInput($form, inputID); console.log($input); $input.on('change input', () => { console.log('b'); toggleField($form, conditionalInputID, conditions); }); toggleField($form, conditionalInputID, conditions); console.log('c'); }); } } function toggleField($form, conditionalInputID, conditions) { let matched = conditions.every(({ input: inputID, operator, value }) => { const $input = getInput($form, inputID); const val = $input.val(); if (Array.isArray(val)) { return val.some(v => evaluateCondition(v, operator, value)); } else { return evaluateCondition(val, operator, value); } }); const $conditionalFieldGroup = getInput($form, conditionalInputID).closest('.elementor-field-group'); if (matched) { $conditionalFieldGroup.show(); } else { resetInput(getInput($form, conditionalInputID)); $conditionalFieldGroup.hide(); } } function evaluateCondition(val, operator, expected) { switch (operator) { case '==': return val == expected; case '!=': return val != expected; case '>': return parseFloat(val) > parseFloat(expected); case '<': return parseFloat(val) < parseFloat(expected); case '>=': return parseFloat(val) >= parseFloat(expected); case '<=': return parseFloat(val) <= parseFloat(expected); case 'in': return Array.isArray(expected) ? expected.includes(val) : false; case 'not in': return Array.isArray(expected) ? !expected.includes(val) : false; default: console.warn(`Unsupported operator: ${operator}`); return false; } } function getInput($form, ID) { let input = $form.find(`[name="form_fields[${ID}]"]`); if (!input.length) { input = $form.find(`[name="form_fields[${ID}][]"]`); } return input; } function resetInput($input) { if (!$input || !$input.length) return; $input.each(function () { const $el = $(this); const type = $el.attr('type'); const tag = this.tagName.toLowerCase(); if (type === 'radio' || type === 'checkbox') { $el.prop('checked', false); } else if (tag === 'select') { $el.val('').trigger('change'); } else if (type === 'number' || type === 'text') { $el.val(''); } else { $el.val(''); } }); } $(document).ready(function () { const $form = $(`#${form_container_id} form`); if ($form.length) { setupConditions($form); } }); $( document ).on( 'elementor/popup/show', (event, id, instance) => { const $popup = $(`#elementor-popup-modal-${id}`); const $form = $popup.find(`#${form_container_id} form`); if ($form.length === 1) { setupConditions($form); console.log('Popup form setup done'); } }); })(jQuery);