const wpAdmin = jQuery('body.wp-admin');
const GC_UTM_PARAMETERS = [
    // Standard UTM
    "utm_source",
    "utm_medium",
    "utm_campaign",
    "utm_content",
    "utm_term",
    "utm_id",
    "utm_source_platform",
    "utm_creative_format",
    "utm_marketing_tactic",
    // Google
    "gclid",
    "gbraid",
    "wbraid",
    "gad_source",
    "gad_campaignid",
    "dclid",
    "gclsrc",
    // "_gl", // saved as checkout parameter
    // Meta
    "fbclid",
    // Other ad platforms
    "msclkid",
    "ttclid",
    "twclid",
    "li_fat_id",
    // Gocars custom
    "aaid",
    "ap",
    "tm",
    "plugin_referrer"
];

/**
 * Read the current Consent Mode v2 state from window.dataLayer and return
 * URL query-string fragments for the booking engine,
 * e.g. "&gc_c_analytics=1&gc_c_advertising=0".
 *
 * Works with any banner that calls gtag('consent', 'update', {...}) —
 * including GocarsCookieBanner, Cookiebot, OneTrust, etc.
 * Returns '' when dataLayer is absent or contains no consent entries at all
 * (i.e. the site has no consent setup), so nothing is sent needlessly.
 *
 * gtag() pushes Arguments objects, so entries have numeric keys:
 *   entry[0] = 'consent', entry[1] = 'default'|'update', entry[2] = { ... }
 * Later 'update' entries override earlier 'default' ones.
 */
function gcReadConsentParams() {
    if (!window.dataLayer || typeof window.dataLayer.forEach !== 'function') return '';

    var state = {
        analytics_storage: null,
        ad_storage: null,
        functionality_storage: null,
    };
    var hasConsentEntry = false;

    window.dataLayer.forEach(function (entry) {
        if (!entry) return;
        var cmd = entry[0];
        var type = entry[1];
        var values = entry[2];
        if (cmd === 'consent' && (type === 'default' || type === 'update') && values && typeof values === 'object') {
            hasConsentEntry = true;
            if ('analytics_storage' in values) state.analytics_storage = values.analytics_storage;
            if ('ad_storage' in values) state.ad_storage = values.ad_storage;
            if ('functionality_storage' in values) state.functionality_storage = values.functionality_storage;
        }
    });

    if (!hasConsentEntry) return '';

    return '&gc_c_necessary=1'
        + '&gc_c_preferences=' + (state.functionality_storage === 'granted' ? '1' : '0')
        + '&gc_c_analytics=' + (state.analytics_storage === 'granted' ? '1' : '0')
        + '&gc_c_advertising=' + (state.ad_storage === 'granted' ? '1' : '0');
}

// Issue using jQuery(document).on('ready', function ($) {
jQuery(document).ready(function ($) {
    if (wpAdmin.length == 0) {
        jQuery('form[data-shortcode]').each(function () {
            var shortcodeID = jQuery(this).attr('data-shortcode');
            var shortcodeType = jQuery(this).attr('data-shortcode_type');
            var shortcodeAtrr = '[data-shortcode="' + shortcodeID + '"]';
            var domain = jQuery('form' + shortcodeAtrr).attr('data-domain');

            var agentCode,
                pickupID,
                returnID,
                vehicleType = '';
            var searchParams = new URLSearchParams(window.location.search);
            if (searchParams.has('agent_code')) {
                agentCode = searchParams.get('agent_code');
            }
            if (searchParams.has('pickup_id')) {
                pickupID = searchParams.get('pickup_id');
            }
            if (searchParams.has('return_id')) {
                returnID = searchParams.get('return_id');
            }
            if (searchParams.has('vehicle_type')) {
                vehicleType = searchParams.get('vehicle_type');
            }

            if (shortcodeType == 'fleet') {
                return;
            }

            var width = jQuery(window).width();

            //standard variables
            var defaultHour = jQuery(shortcodeAtrr + ' [name="default_hour"]').val();

            (timepickerSelect = jQuery(shortcodeAtrr + ' select.timepick')), (timepickerInput = jQuery(shortcodeAtrr + ' input.timepick'));

            function maxWidthFields() {
                var maxWidth = jQuery(shortcodeAtrr + ' .search_form-body').width() + 'px';
                jQuery(shortcodeAtrr + ' .search_form-body .select2-container .select2-selection--single .select2-selection__rendered').css('max-width', maxWidth);
            }

            function trimFields() {
                var field = jQuery(shortcodeAtrr + ' .search_form-body .select2-container .select2-selection--single .select2-selection__rendered');
                var title = field.attr('title');
                if (title) {
                    field.attr('title', title.trim());
                }
            }

            function moveKeyPoints() {
                var headerWidth = 0;
                jQuery(shortcodeAtrr + ' .search_form-header').each(function () {
                    headerWidth = parseFloat(headerWidth) + jQuery(this).outerWidth();
                });

                if (jQuery('form' + shortcodeAtrr).hasClass('horizontal') && jQuery(shortcodeAtrr + ' .keypoints-wrapper').length > 0 && jQuery(window).width() > 1024) {
                    jQuery(shortcodeAtrr + ' .keypoints-wrapper').css({
                        left: headerWidth + 'px',
                        width: jQuery('form' + shortcodeAtrr).outerWidth() - headerWidth + 'px'
                    });
                }
            }

            jQuery(window).on('resize', function () {
                if (jQuery(this).width() !== width) {
                    maxWidthFields();
                }
                moveKeyPoints();
            });

            moveKeyPoints();

            if (jQuery('#different_location-' + shortcodeID).prop('checked') == false) {
                jQuery('#return_id-' + shortcodeID).val(jQuery('#pickup_id-' + shortcodeID).val());
            }
            if (jQuery(shortcodeAtrr + ' .input-group,' + shortcodeAtrr + ' .form-control').val() == '' || jQuery(shortcodeAtrr + ' .input-group,' + shortcodeAtrr + ' .form-control').val() == null) {
                jQuery(this).addClass('placeholder-color');
            } else {
                jQuery(this).removeClass('placeholder-color');
            }

            jQuery(shortcodeAtrr + '.gc-search-form .required').each(function () {
                if (jQuery(this).val() != '' && jQuery(this).val() != null) {
                    jQuery(this).removeClass('placeholder-color');
                }
            });

            jQuery(shortcodeAtrr + ' .search_form-field.location-wrap').removeClass('input-opacity blur-effect');

            // Capture UTM parameters from the landing page URL into hidden form inputs once on load
            if (gocars_ajax.utm_tracking_enabled === '1') {
                var landingParams = new URLSearchParams(window.location.search);
                GC_UTM_PARAMETERS.forEach(function (param) {
                    if (landingParams.has(param)) {
                        jQuery(shortcodeAtrr + ' .gc-utm-inputs').append(
                            '<input type="hidden" class="gc-utm-param" name="' + param + '" value="' + encodeURIComponent(landingParams.get(param)) + '">'
                        );
                    }
                });
            }

            // Re-build the search URL whenever the user changes their consent choices
            document.addEventListener('gc:consent_changed', function () {
                updateUrl(shortcodeAtrr);
            });

            updateUrl(shortcodeAtrr);

            jQuery('#age_group_id-' + shortcodeID).on('input', function (e) {
                jQuery(this).removeClass('placeholder-color');
            });

            jQuery('#different_location-' + shortcodeID).on('click', function (e) {
                if (jQuery('#different_location-' + shortcodeID).prop('checked') == true) {
                    jQuery(shortcodeAtrr + ' .dropoff-field')
                        .stop()
                        .slideToggle(200);
                    jQuery('#different_location-' + shortcodeID).val(1);
                } else {
                    jQuery('#return_id-' + shortcodeID)
                        .val(jQuery('#pickup_id-' + shortcodeID).val())
                        .trigger('change');
                    jQuery(shortcodeAtrr + ' .dropoff-field')
                        .stop()
                        .slideToggle(200);
                    jQuery('#different_location-' + shortcodeID).val(0);
                }
            });

            jQuery('#pickup_id-' + shortcodeID).on('change', function (e) {
                if (jQuery('#different_location-' + shortcodeID).prop('checked') == false) {
                    jQuery('#return_id-' + shortcodeID)
                        .val(jQuery('#pickup_id-' + shortcodeID).val())
                        .trigger('change');
                    jQuery(this).removeClass('placeholder-color');
                }
            });

            jQuery(shortcodeAtrr + ' .date-group .form-control').on('focus', function () {
                jQuery(this).parents('.date-group').addClass('focused-border');
                if (jQuery(this).hasClass('timepick')) {
                    jQuery(this).addClass('focused-border');
                }
            });
            jQuery(shortcodeAtrr + ' .date-group .form-control').on('blur', function () {
                jQuery(this).parents('.date-group').removeClass('focused-border');
                jQuery(this).removeClass('focused-border');
            });

            // on change vehicle type
            jQuery(shortcodeAtrr + ' [name="vehicle"]').on('change click', function () {
                jQuery(shortcodeAtrr + ' [name="vehicle_type"]')
                    .val(jQuery(this).val())
                    .change();
                var vehicleLabel = jQuery('label[title="' + jQuery(this).val() + '"]').text();

                jQuery(shortcodeAtrr + ' .label-button').removeClass('active');
                jQuery(shortcodeAtrr + ' .label-button[title="' + jQuery(this).val() + '"]').addClass('active');
            });

            jQuery(shortcodeAtrr + ' .search-submit').on('mouseover', function (e) {
                updateUrl(shortcodeAtrr);
            });

            // SEARCH BUTTON
            jQuery(shortcodeAtrr + ' .search-submit').on('click', function (e) {
                var emptyField = false;
                checkDates(domain, shortcodeAtrr, false);

                jQuery(shortcodeAtrr + '.gc-search-form .required').each(function () {
                    if (jQuery(this).val() == '' || jQuery(this).val() == null) {
                        emptyField = true;
                        jQuery(this).addClass('has-error');
                        jQuery(this).addClass('placeholder-color');
                        jQuery(this).parents('.form-group').addClass('has-error-content');
                        jQuery(this).parents('.search_form-field').find('.error-message-content').show();
                    }
                });
                if (emptyField == true) {
                    e.preventDefault();
                    return;
                }

                if (
                    new Date(jQuery(shortcodeAtrr + ' [name="date_from"]').datepicker('getDate') + 'T' + jQuery(shortcodeAtrr + ' [name="time_from"]').val()).getTime() <
                    new Date(
                        jQuery(shortcodeAtrr + ' [name="reservation_starts_after"]')
                            .val()
                            .replace(' ', 'T')
                    ).getTime()
                ) {
                    e.preventDefault();
                    return;
                }

                if (
                    new Date(jQuery(shortcodeAtrr + ' [name="date_to"]').datepicker('getDate') + 'T' + jQuery(shortcodeAtrr + ' [name="time_to"]').val()).getTime() <
                    new Date(
                        jQuery(shortcodeAtrr + ' [name="minimum_reservation_datetime"]')
                            .val()
                            .replace(' ', 'T')
                    ).getTime()
                ) {
                    e.preventDefault();
                    return;
                }
            });

            if (jQuery('.vehicles-swiper').length > 0) {
                var vehiclesSwiper = new Swiper(shortcodeAtrr + ' .vehicles-swiper', {
                    slidesPerView: 'auto',
                    // spaceBetween: 10,
                    freeMode: true,
                });
            }

            // select first vehicle type // to be removed
            // if (jQuery(shortcodeAtrr + ' .vehicles-group').length > 0) {
            //     jQuery(shortcodeAtrr + ' .vehicles-group').each(function () {
            //         var hasChecked = false;

            //         jQuery(shortcodeAtrr + ' [name="vehicle"]').each(function () {
            //             if (jQuery(this).attr('checked')) {
            //                 hasChecked = true;
            //             } 
            //         });

            //         if (!hasChecked) {
            //             var vehicleValue = jQuery(shortcodeAtrr + ' [name="vehicle"]').first().val();
            //             var id = jQuery(shortcodeAtrr + ' [name="vehicle"]').first().attr('id');

            //             jQuery(shortcodeAtrr + ' label[for="'+id+'"]').trigger('click').addClass('active');
            //             jQuery('#'+id+'[name="vehicle"]').attr('checked', true);
            //             jQuery(shortcodeAtrr + ' [name="vehicle_type"]').val(vehicleValue);

            //         }
            //     });
            // }

            jQuery(shortcodeAtrr + '.gc-search-form .required').on('change', function () {
                updateUrl(shortcodeAtrr);
            });

            jQuery(shortcodeAtrr + ' [name="time_from"],' + shortcodeAtrr + ' [name="time_to"]').on('blur', function () {
                updateUrl(shortcodeAtrr);
            });

            document.addEventListener(
                'click',
                function (event) {
                    if (!event.target.closest(shortcodeAtrr + ' .search-submit')) {
                        jQuery(shortcodeAtrr + '.gc-search-form .required').each(function () {
                            if (!jQuery(this).val() == '' || !jQuery(this).val() == null) {
                                jQuery(this).parents('.form-group').removeClass('has-error-content');
                                jQuery(this).removeClass('has-error');
                                jQuery(this).removeClass('placeholder-color');
                                jQuery(this).parents('.search_form-field').find('.error-message-content').hide();
                                if (jQuery(this).parents('.form-group').find('.required').hasClass('has-error')) {
                                    jQuery(this).parents('.form-group').addClass('has-error-content');
                                    jQuery(this).parents('.search_form-field').find('.error-message-content').show();
                                }
                            }
                        });
                    }
                },
                false
            );

            // select location
            jQuery('.select-2-item').on('select2:select', function (e) {
                jQuery(this).parents('.form-group').removeClass('has-error-content');
                jQuery(this).removeClass('has-error');
                jQuery(this).parents('.search_form-field').find('.error-message-content').hide();

                jQuery(this).removeClass('placeholder-color');

                trimFields();
            });
            jQuery('.select-2-item').select2({
                placeholder: jQuery(this).attr('data-label')
            });
            jQuery(document).on('select2:open', function () {
                document.querySelector('.select2-search__field').focus();
            });

            maxWidthFields();
            trimFields();

            //--------------------------------------------------------

            //TIME PICKER

            jQuery(shortcodeAtrr + ' select.timepick').on('change', function () {
                var pickupDatetime = new Date(jQuery(shortcodeAtrr + ' [name="date_from"]').datepicker('getDate')),
                    dropOffDatetime = new Date(jQuery(shortcodeAtrr + ' [name="date_to"]').datepicker('getDate'));

                var pickupDateTime = pickupDatetime;
                if (jQuery(shortcodeAtrr + ' .timepick[name="time_from"]').val() != null) {
                    var pickupTime = jQuery(shortcodeAtrr + ' .timepick[name="time_from"]')
                        .val()
                        .split(':');
                    pickupDateTime.setHours(pickupTime[0]);
                    pickupDateTime.setMinutes(pickupTime[1]);
                }

                var dropOffDateTime = dropOffDatetime;
                if (jQuery(shortcodeAtrr + ' .timepick[name="time_to"]').val() != null) {
                    var dropOffTime = jQuery(shortcodeAtrr + ' .timepick[name="time_to"]')
                        .val()
                        .split(':');
                    dropOffDateTime.setHours(dropOffTime[0]);
                    dropOffDateTime.setMinutes(dropOffTime[1]);
                }

                timepickerChange(pickupDateTime, dropOffDateTime, jQuery(this));
            });

            function timepickerChange(pickupDate, dropOffDate, timepicker) {
                if (timepicker.attr('name') == 'time_to') return;

                var dropoffTime = jQuery(shortcodeAtrr + ' .timepick[name="time_to"]').val();
                var minDropoffDate = new Date(pickupDate);
                addHours(minDropoffDate, parseInt(jQuery(shortcodeAtrr + ' [name="min_length_hours"]').val()));

                var minHour =
                    (minDropoffDate.getHours() < 10 ? '0' + minDropoffDate.getHours() : minDropoffDate.getHours()) +
                    ':' +
                    (minDropoffDate.getMinutes() < 10 ? '0' + minDropoffDate.getMinutes() : minDropoffDate.getMinutes());

                if (defaultHour != null) {
                    var updatedDefaultHour = minHour > defaultHour ? minHour : defaultHour;
                    updatedDefaultHour = dropoffTime > updatedDefaultHour && defaultHour < updatedDefaultHour ? dropoffTime : updatedDefaultHour;
                } else {
                    var updatedDefaultHour = minHour;
                }

                var currentDateDif = new Date(
                    new Date(
                        jQuery(shortcodeAtrr + ' [name="current_datetime_rounded"]')
                            .val()
                            .replace(' ', 'T')
                    )
                );
                currentDateDif.setHours(0);
                currentDateDif.setMinutes(0);

                var minDropoffDateDif = new Date(minDropoffDate);
                minDropoffDateDif.setHours(0);
                minDropoffDateDif.setMinutes(0);

                var dateAfterMin = Math.ceil(Math.abs(daysDifference(currentDateDif, minDropoffDateDif)));
                jQuery(shortcodeAtrr + ' [name="date_to"]').datepicker('option', 'minDate', dateAfterMin);

                //same day with min start selected
                if (dropOffDate.getFullYear() <= minDropoffDate.getFullYear() && dropOffDate.getMonth() <= minDropoffDate.getMonth() && dropOffDate.getDate() <= minDropoffDate.getDate()) {
                    jQuery(shortcodeAtrr + ' .mobile-datepicker').mobiscroll('setVal', [pickupDate, new Date(minDropoffDate)]);

                    if (timepickerSelect.length > 0) {
                        jQuery(shortcodeAtrr + ' [name="time_to"] option').each(function (index, option) {
                            //hide options prior start date time
                            jQuery(this).prop('hidden', true);
                            if (jQuery(this).val() >= minHour) jQuery(this).prop('hidden', false);
                            // if (jQuery(this).val() == updatedDefaultHour) jQuery(this).prop('selected', true);
                            if (jQuery(this).val() == updatedDefaultHour && (defaultHour != '' || jQuery(shortcodeAtrr + ' select[name="time_from"]').val() != null))
                                jQuery(this).prop('selected', true);
                            if (defaultHour == '') {
                                jQuery(this).prop('selected', false);
                            }
                        });
                        if (defaultHour == '') {
                            jQuery(shortcodeAtrr + ' [name="time_to"] option:first-child').prop('selected', true);
                        }
                    }

                    if (timepickerInput.length > 0) {
                        jQuery(shortcodeAtrr + ' [name="time_to"]').timeselector('option', {
                            min: minHour,
                            max: jQuery(shortcodeAtrr + ' [name="default_max_hour"]').val()
                        });
                        jQuery(shortcodeAtrr + ' [name="time_to"]')
                            .val(updatedDefaultHour)
                            .timeselector('refresh');
                    }
                }
            }

            //----------------------------------------------------------------

            // INPUT TIMEPICKER

            if (timepickerInput.length > 0) {
                jQuery(shortcodeAtrr + ' input[name="time_from"]').timeselector({
                    min: jQuery(shortcodeAtrr + ' [name="time_from"]').attr('data-min_hour'),
                    max: jQuery(shortcodeAtrr + ' [name="time_from"]').attr('data-max_hour'),
                    step: jQuery(shortcodeAtrr + ' [name="time_space"]').val(),
                    hours12: false
                });
                jQuery(shortcodeAtrr + ' input[name="time_to"]').timeselector({
                    min: jQuery(shortcodeAtrr + ' [name="time_to"]').attr('data-min_hour'),
                    max: jQuery(shortcodeAtrr + ' [name="time_to"]').attr('data-max_hour'),
                    step: jQuery(shortcodeAtrr + ' [name="time_space"]').val(),
                    hours12: false
                });
            }

            jQuery(shortcodeAtrr + ' input.timepick').on('mousedown', function () {
                jQuery('.timepick').parents('.select-item-wrap').removeClass('timepicker-opened');
                jQuery(this).parents('.select-item-wrap').addClass('timepicker-opened');

                var searchFormDisplay = jQuery(this).attr('data-display');
                searchFormDisplay = searchFormDisplay == 'H' ? 'horizontal' : 'vertical';

                jQuery('.timeselector').addClass(searchFormDisplay);
                jQuery('.timeselector').width(jQuery(this).outerWidth());

                var dateTime = new Date();
                var timepickerTime = roundTime(dateTime);
                var minLengthHours = parseInt(jQuery('[name="min_length_hours"]').val());

                if (defaultHour == '' && jQuery(this).attr('name') == 'time_from' && jQuery(this).val() == '') {
                    jQuery(this).val(timepickerTime).timeselector('refresh');
                }

                if (defaultHour == '' && jQuery(this).attr('name') == 'time_to' && jQuery(shortcodeAtrr + ' [name="time_from"]').val() != '' && jQuery(this).val() == '') {
                    addHours(dateTime, minLengthHours);
                    timepickerTime = roundTime(dateTime);
                    jQuery(this).timeselector('option', {
                        min: timepickerTime,
                        max: jQuery('[name="default_max_hour"]').val()
                    });
                    jQuery(this).val(timepickerTime).timeselector('refresh');
                }
            });

            document.addEventListener(
                'mousedown',
                function (event) {
                    if (!event.target.closest('input.timepick, .timeselector')) {
                        jQuery('input.timepick').parents('.select-item-wrap').removeClass('timepicker-opened');
                        jQuery('.timeselector').removeClass('vertical horizontal');
                    }
                },
                false
            );

            timepickerInput.on('blur', function () {
                var pickupDatetime = new Date(jQuery(shortcodeAtrr + ' [name="date_from"]').datepicker('getDate')),
                    dropOffDatetime = new Date(jQuery(shortcodeAtrr + ' [name="date_to"]').datepicker('getDate'));

                var pickupDateTime = pickupDatetime;
                var pickupTime = jQuery(shortcodeAtrr + ' input.timepick[name="time_from"]')
                    .val()
                    .split(':');
                pickupDateTime.setHours(pickupTime[0]);
                pickupDateTime.setMinutes(pickupTime[1]);

                var dropOffDateTime = dropOffDatetime;
                var dropOffTime = jQuery(shortcodeAtrr + ' input.timepick[name="time_to"]')
                    .val()
                    .split(':');
                dropOffDateTime.setHours(dropOffTime[0]);
                dropOffDateTime.setMinutes(dropOffTime[1]);

                timepickerChange(pickupDateTime, dropOffDateTime, jQuery(this));
            });

            //----------------------------------------------------------------

            //connect desktop datepicker to mobile datepicker
            jQuery('#start-' + shortcodeID).on('change', function () {
                jQuery(shortcodeAtrr + ' .form-control[name="date_from"]')
                    .val(jQuery('#start-' + shortcodeID).val())
                    .change();
                updateUrl(shortcodeAtrr);
            });
            jQuery('#end-' + shortcodeID).on('change', function () {
                jQuery(shortcodeAtrr + ' .form-control[name="date_to"]')
                    .val(jQuery('#end-' + shortcodeID).val())
                    .change();
                updateUrl(shortcodeAtrr);
            });

            //mobile calendar
            jQuery(shortcodeAtrr + ' .form-control[name="date_from"]').on('focus', function (e) {
                e.preventDefault();

                // jQuery('.mobile-datepicker').mobiscroll('setOptions', { min: __pickupReservationStartDatetime });
                jQuery(shortcodeAtrr + ' .mobile-datepicker').mobiscroll('setActiveDate', 'start');
                jQuery(shortcodeAtrr + ' .datepicker-modal').addClass('open');
            });

            jQuery(shortcodeAtrr + ' .form-control[name="date_to"]').on('focus', function (e) {
                e.preventDefault();

                jQuery(shortcodeAtrr + ' .mobile-datepicker').mobiscroll('setActiveDate', 'end');
                jQuery(shortcodeAtrr + ' .datepicker-modal').addClass('open');
            });

            jQuery(shortcodeAtrr + ' .close-datepicker-btn').on('click', function () {
                jQuery(shortcodeAtrr + ' .datepicker-modal').removeClass('open');
            });

            // Safari 3.0+ "[object HTMLElementConstructor]"
            var isSafari =
                /constructor/i.test(window.HTMLElement) ||
                (function (p) {
                    return p.toString() === '[object SafariRemoteNotification]';
                })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));

            if ((navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) && isSafari == true && document.documentElement.clientWidth < 360) {
                if (document.cookie.indexOf('iphone_redirect=false') == -1) {
                    jQuery(shortcodeAtrr + ' .datepicker-modal').addClass('responsive-closed');
                }
            }

            initDatepicker(shortcodeAtrr, shortcodeID);

            setTimeout(() => {
                checkDates(domain, shortcodeAtrr);
            }, 50);
        });

        function initDatepicker(shortcodeAtrr, shortcodeID) {
            if (jQuery(shortcodeAtrr + ' [name="current_datetime_rounded"]').length > 0) {
                datepickerSetup(shortcodeAtrr, shortcodeID);
            } else {
                setTimeout(() => {
                    initDatepicker(shortcodeAtrr, shortcodeID);
                }, 50);
            }
        }

        function timepickerToRequest(updatedHour) {
            if (timepickerRequestTo) return updatedHour;
            var urlParams = new URLSearchParams(window.location.search);
            updatedHour = urlParams.get('time_from') != null && urlParams.get('time_to') != null ? urlParams.get('time_to') : updatedHour;
            timepickerRequestTo = true;
            return updatedHour;
        }

        function timepickerFromRequest(updatedHour) {
            if (timepickerRequestFrom) return updatedHour;
            var urlParams = new URLSearchParams(window.location.search);
            updatedHour = urlParams.get('time_from') != null && urlParams.get('time_to') != null ? urlParams.get('time_from') : updatedHour;
            timepickerRequestFrom = true;
            return updatedHour;
        }

        function datepickerSetup(shortcodeAtrr, shortcodeID) {
            // Safari 3.0+ "[object HTMLElementConstructor]"
            var isSafari =
                /constructor/i.test(window.HTMLElement) ||
                (function (p) {
                    return p.toString() === '[object SafariRemoteNotification]';
                })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));

            // datepicker
            jQuery(document).ready(function ($) {
                var currentDateDif = new Date(
                    new Date(
                        jQuery(shortcodeAtrr + ' [name="current_datetime_rounded"]')
                            .val()
                            .replace(' ', 'T')
                    )
                );

                currentDateDif.setHours(0);
                currentDateDif.setMinutes(0);
                var reservationStartDateDif = new Date(
                    new Date(
                        jQuery(shortcodeAtrr + ' [name="pickup_reservation_start_datetime"]')
                            .val()
                            .replace(' ', 'T')
                    )
                );
                reservationStartDateDif.setHours(0);
                reservationStartDateDif.setMinutes(0);
                var minDropoffDateDif = new Date(
                    new Date(
                        jQuery(shortcodeAtrr + ' [name="minimum_reservation_datetime"]')
                            .val()
                            .replace(' ', 'T')
                    )
                );
                minDropoffDateDif.setHours(0);
                minDropoffDateDif.setMinutes(0);

                var startBookingMindate = Math.ceil(Math.abs(daysDifference(currentDateDif, reservationStartDateDif)));
                var minLengthBooking = Math.ceil(Math.abs(daysDifference(currentDateDif, minDropoffDateDif)));

                var locale = 'en';
                if (jQuery(shortcodeAtrr + ' [name="language"]').length > 0) {
                    locale = jQuery(shortcodeAtrr + ' [name="language"]').val();
                }

                if (locale == 'el') {
                    $.datepicker.setDefaults($.datepicker.regional['el']);
                } else if (locale == 'de') {
                    $.datepicker.setDefaults($.datepicker.regional['de']);
                } else if (locale == 'it') {
                    $.datepicker.setDefaults($.datepicker.regional['it']);
                } else {
                    $.datepicker.setDefaults($.datepicker.regional['en']);
                }

                jQuery(shortcodeAtrr + ' .form-control[name="date_from"]').datepicker({
                    minDate: startBookingMindate,
                    dateFormat: 'dd/mm/yy',
                    numberOfMonths: 1,
                    firstDay: 1,
                    maxDate: '+2y',
                    beforeShow: function (input) {
                        jQuery('#ui-datepicker-div').off();
                        jQuery('.ui-datepicker').addClass('notranslate visible').attr('data-shortcode', shortcodeID);

                        if ((navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) && isSafari == true && document.documentElement.clientWidth < 360) {
                            if (document.cookie.indexOf('iphone_redirect=false') == -1) {
                                jQuery('.ui-datepicker').addClass('responsive-opened');
                            }
                        }
                    },
                    beforeShowDay: function (date) {
                        if (jQuery(shortcodeAtrr + ' [name="date_from"]').val()) {
                            var dateFrom = jQuery(shortcodeAtrr + ' [name="date_from"]').val();
                            var d1 = dateFrom.split('/');
                            var from = new Date(d1[2], parseInt(d1[1]) - 1, d1[0]);
                            var dateTo = jQuery(shortcodeAtrr + ' [name="date_to"]').val();
                            if (jQuery(shortcodeAtrr + ' [name="date_to"]').val()) {
                                dateTo = jQuery(shortcodeAtrr + ' [name="date_to"]').val();
                            }
                            var d2 = dateTo.split('/');
                            var to = new Date(d2[2], parseInt(d2[1]) - 1, d2[0]);
                            if (new Date(date).getTime() === new Date(from).getTime() && new Date(to).getTime() === new Date(from).getTime() && new Date(date).getTime() === new Date(to).getTime()) {
                                return [true, 'booking-first booking-last', ''];
                            } else if (new Date(date).getTime() === new Date(to).getTime()) {
                                return [true, 'booking-last', ''];
                            } else if (new Date(date).getTime() === new Date(from).getTime()) {
                                return [true, 'booking-first', ''];
                            } else if (new Date(date).getTime() < new Date(to).getTime() && new Date(date).getTime() > new Date(from).getTime()) {
                                return [true, 'in-range-date', ''];
                            } else {
                                return [true, '', ''];
                            }
                        } else {
                            return [true, '', ''];
                        }
                    },

                    onSelect: function (dateText, inst) {
                        if (jQuery(shortcodeAtrr + ' [name="date_from"]').val() && jQuery(shortcodeAtrr + ' [name="date_to"]').val() !== null) {
                            var pickupDatetime = new Date(jQuery(shortcodeAtrr + ' [name="date_from"]').datepicker('getDate'));

                            pickupDateSameMinStart(
                                shortcodeAtrr,
                                pickupDatetime,
                                new Date(
                                    jQuery('body ' + shortcodeAtrr + ' [name="pickup_reservation_start_datetime"]')
                                        .val()
                                        .replace(' ', 'T')
                                )
                            );

                            var dateAfterMin = new Date(jQuery(shortcodeAtrr + ' [name="date_from"]').datepicker('getDate'));
                            if (jQuery(shortcodeAtrr + ' [name="time_from"]').val() != null) {
                                var dateAfterMinTime = jQuery(shortcodeAtrr + ' [name="time_from"]')
                                    .val()
                                    .split(':');
                                dateAfterMin.setHours(dateAfterMinTime[0]);
                                dateAfterMin.setMinutes(dateAfterMinTime[1]);
                            }

                            addHours(dateAfterMin, parseInt(jQuery(shortcodeAtrr + ' [name="min_length_hours"]').val()));

                            var dateAfterDefaultlength = new Date(jQuery(shortcodeAtrr + ' [name="date_from"]').datepicker('getDate'));
                            addHours(dateAfterDefaultlength, parseInt(jQuery(shortcodeAtrr + ' [name="default_length_hours"]').val()));

                            jQuery(shortcodeAtrr + ' [name="date_to"]').datepicker('option', 'minDate', dateAfterMin);

                            //set date date_to to default after days
                            jQuery(shortcodeAtrr + ' [name="date_to"]').datepicker('setDate', dateAfterDefaultlength);
                            jQuery(shortcodeAtrr + ' [name="date_to"]').removeClass('has-error placeholder-color');
                            if (!jQuery(shortcodeAtrr + ' [name="time_to"]').hasClass('has-error')) {
                                jQuery(shortcodeAtrr + ' [name="time_to"]')
                                    .parents('.form-group')
                                    .removeClass('has-error-content');
                                jQuery(shortcodeAtrr + ' [name="time_to"]')
                                    .parents('.search_form-field')
                                    .find('.error-message-content')
                                    .hide();
                            }
                            dropoffMinDateTime(
                                shortcodeAtrr,
                                pickupDatetime,
                                new Date(jQuery(shortcodeAtrr + ' [name="date_to"]').datepicker('getDate')),
                                new Date(
                                    jQuery('body ' + shortcodeAtrr + ' [name="minimum_reservation_datetime"]')
                                        .val()
                                        .replace(' ', 'T')
                                )
                            );

                            setTimeout(function () {
                                //open date_to datepicker
                                jQuery(shortcodeAtrr + ' .form-control[name="date_to"]').datepicker('show');
                            }, 200);
                        }
                        jQuery(this).removeClass('has-error placeholder-color');
                        if (!jQuery(shortcodeAtrr + ' [name="time_from"]').hasClass('has-error')) {
                            jQuery(shortcodeAtrr + ' [name="time_from"]')
                                .parents('.form-group')
                                .removeClass('has-error-content');
                            jQuery(shortcodeAtrr + ' [name="time_from"]')
                                .parents('.search_form-field')
                                .find('.error-message-content')
                                .hide();
                        }
                        updateUrl(shortcodeAtrr);
                    },
                    onClose: function (dateText, inst) {
                        jQuery('.ui-datepicker').removeClass('visible');
                        if (jQuery('.ui-datepicker').hasClass('responsive-opened')) {
                            jQuery('.ui-datepicker').removeClass('responsive-opened');
                        }
                    }
                });

                jQuery(shortcodeAtrr + ' .form-control[name="date_to"]').datepicker({
                    minDate: minLengthBooking,
                    dateFormat: 'dd/mm/yy',
                    numberOfMonths: 1,
                    firstDay: 1,
                    maxDate: '+2y',
                    beforeShowDay: function (date) {
                        if (jQuery(shortcodeAtrr + ' [name="date_from"]').val()) {
                            var dateFrom = jQuery(shortcodeAtrr + ' [name="date_from"]').val();
                            var d1 = dateFrom.split('/');
                            var from = new Date(d1[2], parseInt(d1[1]) - 1, d1[0]);
                            var dateTo = jQuery(shortcodeAtrr + ' [name="date_from"]').val();
                            if (jQuery(shortcodeAtrr + ' [name="date_to"]').val()) {
                                dateTo = jQuery(shortcodeAtrr + ' [name="date_to"]').val();
                            }
                            var d2 = dateTo.split('/');
                            var to = new Date(d2[2], parseInt(d2[1]) - 1, d2[0]);
                            if (new Date(date).getTime() === new Date(from).getTime() && new Date(to).getTime() === new Date(from).getTime() && new Date(date).getTime() === new Date(to).getTime()) {
                                return [true, 'booking-first booking-last', ''];
                            } else if (new Date(date).getTime() === new Date(to).getTime()) {
                                return [true, 'booking-last', ''];
                            } else if (new Date(date).getTime() === new Date(from).getTime()) {
                                return [true, 'booking-first', ''];
                            } else if (new Date(date).getTime() < new Date(to).getTime() && new Date(date).getTime() > new Date(from).getTime()) {
                                return [true, 'in-range-date', ''];
                            } else {
                                return [true, '', ''];
                            }
                        } else {
                            return [true, '', ''];
                        }
                    },
                    onSelect: function (dateText, inst) {
                        var pickupDatetime = new Date(jQuery(shortcodeAtrr + ' .form-control[name="date_from"]').datepicker('getDate')),
                            dropOffDatetime = new Date(jQuery(shortcodeAtrr + ' .form-control[name="date_to"]').datepicker('getDate'));

                        jQuery(this).removeClass('has-error placeholder-color');

                        dropoffMinDateTime(
                            shortcodeAtrr,
                            pickupDatetime,
                            dropOffDatetime,
                            new Date(
                                jQuery(shortcodeAtrr + ' [name="minimum_reservation_datetime"]')
                                    .val()
                                    .replace(' ', 'T')
                            )
                        );
                        updateUrl(shortcodeAtrr);
                        setTimeout(function () {
                            // close date_to datepicker
                            jQuery(shortcodeAtrr + ' .form-control[name="date_to"]').datepicker('hide');
                        }, 200);
                    },
                    beforeShow: function (input) {
                        jQuery('.ui-datepicker').addClass('notranslate visible').attr('data-shortcode', shortcodeID);
                        if ((navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) && isSafari == true && document.documentElement.clientWidth < 360) {
                            if (document.cookie.indexOf('iphone_redirect=false') == -1) {
                                jQuery('.ui-datepicker').addClass('responsive-opened');
                            }
                        }

                        if (input.id == 'date_to-' + shortcodeID) {
                            jQuery('#ui-datepicker-div')
                                .on('mouseenter', 'td', function () {
                                    jQuery(this).parent().addClass('final-row');
                                    jQuery('.final-row').prevAll().find('td:not(.ui-datepicker-unselectable)').addClass('highlight');
                                    jQuery(this).prevAll('td:not(.ui-datepicker-unselectable)').addClass('highlight');
                                    if (jQuery(this).parents('table').find('td.booking-first').length == 0) {
                                        jQuery('.ui-datepicker-group.ui-datepicker-group-first')
                                            .find('table')
                                            .find('tr')
                                            .addClass('final-row')
                                            .find('td:not(.ui-datepicker-unselectable)')
                                            .addClass('highlight');
                                    }
                                })
                                .on('mouseleave', 'td', function () {
                                    jQuery('.final-row').removeClass('final-row');
                                    jQuery('.ui-datepicker-calendar td').removeClass('highlight');
                                });
                        }
                    },
                    onClose: function (dateText, inst) {
                        jQuery('.ui-datepicker').removeClass('visible');
                        if (jQuery('.ui-datepicker').hasClass('responsive-opened')) {
                            jQuery('.ui-datepicker').removeClass('responsive-opened');
                        }
                    }
                });

                mobiscroll.setOptions({
                    theme: 'ios',
                    themeVariant: 'light'
                });

                var fromLabel = jQuery(shortcodeAtrr + ' .date_from-label').attr('data-label'),
                    toLabel = jQuery(shortcodeAtrr + ' .date_to-label').attr('data-label');

                var minStartDif = new Date(
                    new Date(
                        jQuery(shortcodeAtrr + ' [name="minimum_reservation_datetime"]')
                            .val()
                            .replace(' ', 'T')
                    )
                );
                minStartDif.setHours(0);
                minStartDif.setMinutes(0);

                var minEndDif = new Date(
                    new Date(
                        jQuery(shortcodeAtrr + ' [name="reservation_starts_after"]')
                            .val()
                            .replace(' ', 'T')
                    )
                );
                minEndDif.setHours(0);
                minEndDif.setMinutes(0);

                minLengthBooking = Math.ceil(Math.abs(daysDifference(minStartDif, minEndDif)));

                jQuery(shortcodeAtrr + ' .mobile-datepicker')
                    .mobiscroll()
                    .datepicker({
                        controls: ['calendar'],
                        select: 'range',
                        display: 'inline',
                        calendarType: 'month',
                        calendarScroll: 'vertical',
                        pages: 1,
                        minRange: minLengthBooking,
                        layout: 'liquid',
                        dateFormat: 'DD/MM/YYYY',
                        startInput: '#start-' + shortcodeID,
                        endInput: '#end-' + shortcodeID,
                        start: new Date(
                            jQuery(shortcodeAtrr + ' [name="reservation_starts_after"]')
                                .val()
                                .replace(' ', 'T')
                        ),
                        end: new Date(
                            jQuery(shortcodeAtrr + ' [name="default_booking_datetime"]')
                                .val()
                                .replace(' ', 'T')
                        ),
                        firstDay: 1,
                        showLabel: true,
                        showRangeLabels: true,
                        rangeStartLabel: fromLabel + ' *',
                        rangeEndLabel: toLabel + ' *',
                        mousewheel: true,
                        months: 2,
                        touchUi: true,
                        min: new Date(
                            jQuery(shortcodeAtrr + ' [name="pickup_reservation_start_datetime"]')
                                .val()
                                .replace(' ', 'T')
                        ),
                        onChange: function (event, inst) {
                            var startDateChange = new Date(event.value[0]);
                            var endDateChange = event.value[1];

                            var startDateChangeMin = startDateChange;
                            if (jQuery(shortcodeAtrr + ' .form-control[name="time_from"]').val() != null) {
                                var dateAfterMinTime = jQuery(shortcodeAtrr + ' .form-control[name="time_from"]')
                                    .val()
                                    .split(':');
                                startDateChangeMin.setHours(dateAfterMinTime[0]);
                                startDateChangeMin.setMinutes(dateAfterMinTime[1]);
                            }

                            var endDateChangeMin = new Date(startDateChangeMin);

                            addHours(endDateChangeMin, parseInt(jQuery(shortcodeAtrr + ' [name="min_length_hours"]').val()));

                            // minLengthBooking = Math.abs(Math.floor(daysDifference(startDateChangeMin, endDateChangeMin)));
                            var minLengthStartDif = new Date(startDateChangeMin);
                            minLengthStartDif.setHours(0);
                            minLengthStartDif.setMinutes(0);

                            var minLengthEndDif = new Date(endDateChangeMin);
                            minLengthEndDif.setHours(0);
                            minLengthEndDif.setMinutes(0);

                            minLengthBooking = Math.ceil(Math.abs(daysDifference(minLengthStartDif, minLengthEndDif)));

                            if (endDateChange == null) {
                                var endDateChangeDefault = new Date(event.value[0]);
                                if (jQuery(shortcodeAtrr + ' .form-control[name="time_from"]').val() != null) {
                                    endDateChangeDefault.setHours(dateAfterMinTime[0]);
                                    endDateChangeDefault.setMinutes(dateAfterMinTime[1]);
                                }
                                addHours(endDateChangeDefault, parseInt(jQuery(shortcodeAtrr + ' [name="default_length_hours"]').val()));

                                jQuery(shortcodeAtrr + ' .mobile-datepicker').mobiscroll('setVal', [new Date(event.value[0]), new Date(endDateChangeDefault)]);
                            }

                            pickupDateSameMinStart(
                                shortcodeAtrr,
                                new Date(event.value[0]),
                                new Date(
                                    jQuery('body ' + shortcodeAtrr + ' [name="pickup_reservation_start_datetime"]')
                                        .val()
                                        .replace(' ', 'T')
                                )
                            );

                            dropoffMinDateTime(
                                shortcodeAtrr,
                                new Date(event.value[0]),
                                new Date(event.value[1]),
                                new Date(
                                    jQuery('body ' + shortcodeAtrr + ' [name="minimum_reservation_datetime"]')
                                        .val()
                                        .replace(' ', 'T')
                                )
                            );

                            if (inst._activeSelect == 'end' && endDateChange != null) {
                                // inst.setOptions({ min: endDateChangeMin });
                                setTimeout(function () {
                                    jQuery(shortcodeAtrr + ' .datepicker-modal').removeClass('open');
                                }, 100);
                                setTimeout(function () {
                                    jQuery(shortcodeAtrr + ' .mobile-datepicker').mobiscroll('setActiveDate', 'start');
                                }, 300);
                            } else if (inst._activeSelect == 'start' && endDateChange != null) {
                                // inst.setOptions({ min: __pickupReservationStartDatetime });
                                inst.setOptions({ minRange: minLengthBooking });
                                // inst.setOptions({ min: endDateChangeMin });
                                setTimeout(function () {
                                    jQuery(shortcodeAtrr + ' .mobile-datepicker').mobiscroll('setActiveDate', 'end');
                                }, 100);
                                // inst.setOptions({ min: __pickupReservationStartDatetime });
                            }

                            updateUrl(shortcodeAtrr);
                        },
                        onActiveDateChange: function (event, inst) {
                            if (event.active == 'start') {
                                inst.setOptions({
                                    min: new Date(
                                        jQuery('body ' + shortcodeAtrr + ' [name="pickup_reservation_start_datetime"]')
                                            .val()
                                            .replace(' ', 'T')
                                    )
                                });
                            } else {
                                if (inst.__value != null) {
                                    inst.setOptions({ min: new Date(inst.__value[0]) });
                                }
                            }
                        }
                    });

                if (jQuery(shortcodeAtrr + ' [name="preselect_default_dates"]').length == 0) {
                    jQuery(shortcodeAtrr + ' .mobile-datepicker').mobiscroll('setVal', [
                        new Date(
                            jQuery(shortcodeAtrr + ' [name="reservation_starts_after"]')
                                .val()
                                .replace(' ', 'T')
                        ),
                        new Date(
                            jQuery(shortcodeAtrr + ' [name="default_booking_datetime"]')
                                .val()
                                .replace(' ', 'T')
                        )
                    ]);
                }
            });
        }

        function updateUrl(shortcodeAtrr = null) {
            var formUrl = jQuery(shortcodeAtrr + '.gc-search-form').attr('data-form');
            formUrl = formUrl + 'select?filter';
            var urlParametersChanged = '';
            var vehicleSort = '';
            var agentCode = '';
            var website = '';

            jQuery(shortcodeAtrr + '.gc-search-form .required').each(function () {
                if (jQuery(this).val() != '') {
                    urlParametersChanged += '&' + jQuery(this).attr('name') + '=' + jQuery(this).val();
                }
            });

            if (jQuery(shortcodeAtrr + ' [name="vehicles_sort_by"]').length > 0) {
                vehicleSort = jQuery(shortcodeAtrr + ' [name="vehicles_sort_by"]').val();
                urlParametersChanged += '&vehicles_sort_by=' + vehicleSort;
            }

            if (jQuery(shortcodeAtrr + ' [name="agent_code"]').length > 0) {
                agentCode = jQuery(shortcodeAtrr + ' [name="agent_code"]').val();
                urlParametersChanged += '&agent_code=' + agentCode;
            }

            if (jQuery(shortcodeAtrr + ' [name="website"]').length > 0) {
                website = jQuery(shortcodeAtrr + ' [name="website"]').val();
                urlParametersChanged += '&website=' + website;
            }

            if (jQuery(shortcodeAtrr + ' [name="language"]').length > 0) {
                language = jQuery(shortcodeAtrr + ' [name="language"]').val();
                urlParametersChanged += '&lang=' + language;
            }

            if (gocars_ajax.utm_tracking_enabled === '1') {
                jQuery(shortcodeAtrr + ' .gc-utm-inputs input.gc-utm-param').each(function () {
                    urlParametersChanged += '&' + jQuery(this).attr('name') + '=' + jQuery(this).val();
                });
            }

            urlParametersChanged += gcReadConsentParams();

            var carSearchUrlChanged = formUrl + urlParametersChanged;
            jQuery(shortcodeAtrr + ' .search-submit').attr('href', carSearchUrlChanged);
        }

        //check if pickup is starting date and change time
        function pickupDateSameMinStart(shortcodeAtrr, firstDate, secondDate) {
            var minHour =
                (secondDate.getHours() < 10 ? '0' + secondDate.getHours() : secondDate.getHours()) + ':' + (secondDate.getMinutes() < 10 ? '0' + secondDate.getMinutes() : secondDate.getMinutes());
            var defaultHour = jQuery(shortcodeAtrr + ' [name="default_hour"]').val();

            //same day
            if (firstDate.getFullYear() <= secondDate.getFullYear() && firstDate.getMonth() <= secondDate.getMonth() && firstDate.getDate() <= secondDate.getDate()) {
                if (timepickerSelect.length > 0) {
                    jQuery(shortcodeAtrr + ' .form-control[name="time_from"] option').each(function (index, option) {
                        //hide options prior start date time
                        jQuery(this).prop('hidden', true);
                        if (jQuery(this).val() >= minHour) jQuery(this).prop('hidden', false);
                        if (defaultHour != '' && defaultHour != 'null') {
                            if ((jQuery(this).val() == minHour || jQuery(this).val() == defaultHour) && defaultHour != 'null') jQuery(this).prop('selected', true);
                        }
                    });
                }

                if (timepickerInput.length > 0) {
                    var updatedHour = minHour < defaultHour ? defaultHour : minHour;
                    // updatedHour = timepickerFromRequest(updatedHour);

                    jQuery(shortcodeAtrr + ' .form-control[name="time_from"]').timeselector('option', {
                        min: minHour,
                        max: jQuery(shortcodeAtrr + ' [name="default_max_hour"]').val()
                    });
                    jQuery(shortcodeAtrr + ' .form-control[name="time_from"]')
                        .val(updatedHour)
                        .timeselector('refresh');
                }
            } else {
                if (timepickerSelect.length > 0) {
                    //unset hidden options for timepicker
                    jQuery(shortcodeAtrr + ' .form-control[name="time_from"] option').each(function (index, option) {
                        if (jQuery(this).val() == '') return;

                        jQuery(this).prop('hidden', false);

                        if (defaultHour != '' && defaultHour != 'null') {
                            if (jQuery(this).val() == defaultHour && defaultHour != 'null') jQuery(this).prop('selected', true);
                        }
                    });
                }

                if (timepickerInput.length > 0) {
                    var updatedHour = defaultHour == '' ? jQuery(shortcodeAtrr + ' .form-control[name="time_from"]').val() : defaultHour;
                    // updatedHour = timepickerFromRequest(defaultHour);

                    jQuery(shortcodeAtrr + ' .form-control[name="time_from"]').timeselector('option', {
                        min: '',
                        max: ''
                    });
                    jQuery(shortcodeAtrr + ' .form-control[name="time_from"]')
                        .val(updatedHour)
                        .timeselector('refresh');
                }
            }
        }

        function dropoffMinDateTime(shortcodeAtrr, firstDate, secondDate, minLengthDate) {
            var defaultHour = jQuery(shortcodeAtrr + ' [name="default_hour"]').val();

            //set pickup date hours
            if (jQuery(shortcodeAtrr + ' [name="time_from"]').val() != null) {
                var pickupTime = jQuery(shortcodeAtrr + ' [name="time_from"]')
                    .val()
                    .split(':');
                firstDate.setHours(pickupTime[0]);
                firstDate.setMinutes(pickupTime[1]);
            }

            //set min start date hours
            if (
                firstDate !=
                new Date(
                    jQuery(shortcodeAtrr + ' [name="reservation_starts_after"]')
                        .val()
                        .replace(' ', 'T')
                )
            ) {
                minLengthDate = addHours(firstDate, parseInt(jQuery(shortcodeAtrr + ' [name="min_length_hours"]').val()));
            }

            var minHour =
                (minLengthDate.getHours() < 10 ? '0' + minLengthDate.getHours() : minLengthDate.getHours()) +
                ':' +
                (minLengthDate.getMinutes() < 10 ? '0' + minLengthDate.getMinutes() : minLengthDate.getMinutes());

            //same day with min start selected
            if (minLengthDate.getFullYear() >= secondDate.getFullYear() && minLengthDate.getMonth() >= secondDate.getMonth() && minLengthDate.getDate() >= secondDate.getDate()) {
                if (timepickerSelect.length > 0) {
                    jQuery(shortcodeAtrr + ' .form-control[name="time_to"] option').each(function (index, option) {
                        //hide options prior start date time
                        jQuery(this).prop('hidden', true);
                        if (jQuery(this).val() >= minHour) jQuery(this).prop('hidden', false);
                        // if (jQuery(this).val() == minHour || jQuery(this).val() == defaultHour) jQuery(this).prop('selected', true);
                        if (
                            (jQuery(this).val() == minHour || jQuery(this).val() == defaultHour) &&
                            (defaultHour != 'null' || jQuery(shortcodeAtrr + ' .form-control[name="time_from"]').val() != null)
                        ) {
                            jQuery(this).prop('selected', true);
                        }
                        if (defaultHour == 'null') {
                            jQuery(this).prop('selected', false);
                        }
                    });

                    if (defaultHour == 'null') {
                        jQuery(shortcodeAtrr + ' [name="time_to"] option:first-child').prop('selected', true);
                    }
                }

                if (timepickerInput.length > 0) {
                    var updatedHour = minHour < defaultHour ? defaultHour : minHour;
                    // updatedHour = timepickerToRequest(updatedHour);

                    jQuery(shortcodeAtrr + ' .form-control[name="time_to"]').timeselector('option', {
                        min: minHour,
                        max: jQuery(shortcodeAtrr + ' [name="default_max_hour"]').val()
                    });
                    jQuery(shortcodeAtrr + ' .form-control[name="time_to"]')
                        .val(updatedHour)
                        .timeselector('refresh');
                }
            } else {
                if (timepickerSelect.length > 0) {
                    //unset hidden options for timepicker
                    jQuery(shortcodeAtrr + ' .form-control[name="time_to"] option').each(function (index, option) {
                        if (jQuery(this).val() == '') return;
                        // if (jQuery(this).val() == defaultHour) jQuery(this).prop('selected', true);
                        if (jQuery(this).val() == defaultHour && (defaultHour != 'null' || jQuery(shortcodeAtrr + ' .form-control[name="time_from"]').val() != null))
                            jQuery(this).prop('selected', true);
                        jQuery(this).prop('hidden', false);
                    });
                }

                if (timepickerInput.length > 0) {
                    var updatedHour = defaultHour == '' ? jQuery(shortcodeAtrr + ' .form-control[name="time_to"]').val() : defaultHour;
                    // updatedHour = timepickerToRequest(defaultHour);

                    jQuery(shortcodeAtrr + ' .form-control[name="time_to"]').timeselector('option', {
                        min: '',
                        max: ''
                    });
                    jQuery(shortcodeAtrr + ' .form-control[name="time_to"]')
                        .val(updatedHour)
                        .timeselector('refresh');
                }
            }
        }

        //check dates
        function checkDates(domain, shortcodeAtrr, first = null) {
            jQuery.ajax({
                url: 'https://' + domain + '.gocars.gr/api/v1/dates/',
                method: 'GET',
                dataType: 'json',
                success: function (response) {
                    // console.log(response);
                    var responseMessage = '';
                    Object.keys(response).forEach(function (key) {
                        responseMessage += '<input type="hidden" name="' + key + '" value="' + response[key] + '">';
                    });
                    jQuery('.datetime_options' + shortcodeAtrr).html(responseMessage);
                    if (first == null || first) {
                        updateDates(shortcodeAtrr, response);
                        // Trigger AJAX call to update post meta
                        updatePostMeta(shortcodeAtrr, response);
                    }
                    return response;
                },
                error: function (xhr, status, error) {
                    // Handle the error if the API request fails
                    jQuery(shortcodeAtrr + ' .search_form-field').removeClass('input-opacity blur-effect');
                }
            });
        }

        // Function to get a cookie by name
        function getCookie(name) {
            let nameEQ = name + '=';
            let ca = document.cookie.split(';');
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i];
                while (c.charAt(0) === ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        // Function to update the cookie with the current time
        function updateCookie(name, value, days) {
            let expires = '';
            if (days) {
                let date = new Date();
                date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
                expires = '; expires=' + date.toUTCString();
            }
            document.cookie = name + '=' + (value || '') + expires + '; path=/';
        }

        function updatePostMeta(shortcodeAtrr, response) {
            var postId = jQuery('form' + shortcodeAtrr).attr('data-shortcode');
            var metaFieldValue = JSON.stringify(response);
            var ajaxUrl = typeof gocars_ajax !== 'undefined' && gocars_ajax.ajax_url ? gocars_ajax.ajax_url : '/wp-admin/admin-ajax.php';
            var ajaxNonce = typeof gocars_ajax !== 'undefined' && gocars_ajax.nonce ? gocars_ajax.nonce : '';

            let cookieValue = getCookie('dates_data');
            if (cookieValue) {
                updateCookie('dates_data', metaFieldValue, 1);
            }

            jQuery.ajax({
                url: ajaxUrl,
                method: 'POST',
                dataType: 'html',
                data: {
                    action: 'update_post_meta_action',
                    nonce: ajaxNonce,
                    post_id: postId,
                    meta_key: 'dates_data',
                    meta_value: metaFieldValue
                },
                success: function (response) {
                    console.log('Post meta updated successfully');
                },
                error: function (xhr, status, error) {
                    console.error('Error updating post meta:', error);
                }
            });
        }

        //update dates
        function updateDates(shortcodeAtrr, response) {
            var defaultHour = jQuery(shortcodeAtrr + ' [name="default_hour"]').val();

            if (shortcodeAtrr == null || response == null) {
                jQuery(shortcodeAtrr + ' .search_form-field').removeClass('input-opacity blur-effect');
                return;
            }
            if (response.date_from != jQuery(shortcodeAtrr + ' [name="date_from"]').val()) {
                if (jQuery(shortcodeAtrr + ' [name="preselect_default_dates"]').length == 0) {
                    jQuery(shortcodeAtrr + ' [name="date_from"]').val(response.date_from);
                }
                // console.log('changed date_from' + shortcodeAtrr);
            }
            if (response.time_from != jQuery(shortcodeAtrr + ' [name="time_from"]').val()) {
                if (jQuery(shortcodeAtrr + ' select[name="time_from"]').length > 0) {
                    jQuery(shortcodeAtrr + ' [name="time_from"] option').each(function (index, option) {
                        //hide options prior start date time
                        jQuery(this).prop('hidden', true);
                        if (jQuery(this).val() >= response.min_hour) jQuery(this).prop('hidden', false);
                        if (defaultHour != '' && defaultHour != null && defaultHour != 'null') {
                            if (jQuery(this).val() == response.time_from) jQuery(this).prop('selected', true);
                        }
                    });
                } else {
                    if (defaultHour != null) {
                        jQuery(shortcodeAtrr + ' [name="time_from"]')
                            .val(response.time_from)
                            .timeselector('refresh');
                    }
                }
                jQuery(shortcodeAtrr + ' [name="time_from"]').attr('data-min_hour', response.min_hour);
                // console.log('changed time_from' + shortcodeAtrr);
            }
            if (response.date_to != jQuery(shortcodeAtrr + ' [name="date_to"]').val()) {
                if (jQuery(shortcodeAtrr + ' [name="preselect_default_dates"]').length == 0) {
                    jQuery(shortcodeAtrr + ' [name="date_to"]').val(response.date_to);
                }
                // console.log('changed date_to' + shortcodeAtrr);
            }
            if (response.time_to != jQuery(shortcodeAtrr + ' [name="time_to"]').val()) {
                if (jQuery(shortcodeAtrr + ' select[name="time_to"]').length > 0) {
                    jQuery(shortcodeAtrr + ' [name="time_to"] option').each(function (index, option) {
                        //hide options prior start date time
                        if (defaultHour != '' && defaultHour != null && defaultHour != 'null') {
                            if (jQuery(this).val() == response.time_to) jQuery(this).prop('selected', true);
                        }
                    });
                } else {
                    if (defaultHour != null) {
                        jQuery(shortcodeAtrr + ' [name="time_to"]')
                            .val(response.time_to)
                            .timeselector('refresh');
                    }
                }
                // console.log('changed time_to' + shortcodeAtrr);
            }
            jQuery(shortcodeAtrr + ' .search_form-field').removeClass('input-opacity blur-effect');
            jQuery(shortcodeAtrr + ' .form-control').removeClass('hide-form-control');
            return;
        }

        //add hours to date
        function addHours(date, hours) {
            date.setHours(date.getHours() + hours);
            return date;
        }

        //get date difference in days
        function daysDifference(date1, date2) {
            // To calculate the time difference of two dates
            var timeDifference = date2.getTime() - date1.getTime();

            // To calculate the no. of days between two dates
            var dayDifference = timeDifference / (1000 * 3600 * 24);

            return dayDifference;
        }

        var timeSpace = jQuery('[name="time_spacer"]').val();
        function roundTime(date) {
            var hours = date.getHours();
            var minutes = date.getMinutes();

            // Calculate the closest step based on the timeSpace
            var closestStep = Math.ceil(minutes / timeSpace) * timeSpace;

            // If the closestStep is 60, update the hours and reset the minutes to 0
            if (closestStep === 60) {
                hours++;
                closestStep = 0;
            }

            // Format the result back into a time string
            var roundedTime = hours.toString().padStart(2, '0') + ':' + closestStep.toString().padStart(2, '0');
            return roundedTime;
        }

        //check timepickers onces if it has already requested from url
        let timepickerRequestFrom,
            timepickerRequestTo = false;

        // remove empty spaces
        if (jQuery('.gocars-terms-wrap').length > 0) {
            jQuery('.gocars-terms-wrap h2, .gocars-terms-wrap h3').html(function (i, html) {
                return html.replace(/&nbsp;/g, '');
            });
        }

        // Build a merged UTM params object from all available sources.
        //
        // Strategy:
        //  - Always read the current page URL first (catches ALL params: gad_source, gbraid, etc.)
        //  - If the plugin banner is enabled, merge sessionStorage['gc_utm'] on top — the banner
        //    persists the 6 standard UTMs across pages, so links on page 2+ still get attribution.
        //    sessionStorage values win over URL values for those 6 keys.
        //  - If no banner, also look for a 'utm_data' event in window.dataLayer (GTM push).
        function gcGetUtmParams() {
            var result = {};

            // Step 1: read everything available in the current URL
            var currentParams = new URLSearchParams(window.location.search);
            GC_UTM_PARAMETERS.forEach(function (p) {
                if (currentParams.has(p)) result[p] = currentParams.get(p);
            });

            if (typeof gocars_ajax !== 'undefined' && gocars_ajax.cookie_banner_enabled === '1') {
                // Step 2a (banner active): overlay sessionStorage for cross-page persistence
                try {
                    var stored = JSON.parse(sessionStorage.getItem('gc_utm') || '{}');
                    Object.keys(stored).forEach(function (k) {
                        result[k] = stored[k];
                    });
                } catch (e) { }
                return result;
            }

            // Step 2b (no banner): supplement with any utm_data event in dataLayer
            if (window.dataLayer && Array.isArray(window.dataLayer)) {
                for (var i = window.dataLayer.length - 1; i >= 0; i--) {
                    var entry = window.dataLayer[i];
                    if (entry && entry.event === 'utm_data') {
                        GC_UTM_PARAMETERS.forEach(function (p) {
                            if (entry[p] && !result[p]) result[p] = entry[p];
                        });
                        break;
                    }
                }
            }

            return result;
        }

        // Append UTM parameters to gocars.gr links on hover (desktop) and touch (mobile).
        // Uses string concatenation to avoid re-encoding existing date/time values in the href
        // (e.g. 26/04/2026 and 10:00 that the URL API would percent-encode as %2F / %3A).
        function gcAppendUtmToLink(element) {
            var $link = jQuery(element);
            var href = $link.attr('href');
            if (!href) return;
            var hash = '';
            var hashIndex = href.indexOf('#');
            if (hashIndex !== -1) {
                hash = href.substring(hashIndex);
                href = href.substring(0, hashIndex);
            }
            var baseHref = href;
            var query = '';
            var queryIndex = href.indexOf('?');
            if (queryIndex !== -1) {
                baseHref = href.substring(0, queryIndex);
                query = href.substring(queryIndex + 1);
            }
            var params = [];
            if (query) {
                query.split('&').forEach(function (token) {
                    if (!token) return;
                    var key = token.split('=')[0];
                    if (
                        key === 'gc_c_necessary' ||
                        key === 'gc_c_preferences' ||
                        key === 'gc_c_analytics' ||
                        key === 'gc_c_advertising' ||
                        key === 'amp;gc_c_necessary' ||
                        key === 'amp;gc_c_preferences' ||
                        key === 'amp;gc_c_analytics' ||
                        key === 'amp;gc_c_advertising'
                    ) {
                        return;
                    }
                    params.push(token);
                });
            }
            var utmParams = gcGetUtmParams();
            var existingParams = '&' + params.join('&') + '&';
            Object.keys(utmParams).forEach(function (param) {
                var alreadyPresent = existingParams.indexOf('&' + param + '=') !== -1;
                if (!alreadyPresent) {
                    params.push(param + '=' + encodeURIComponent(utmParams[param]));
                    existingParams += param + '=x&';
                }
            });
            // External referrer attribution:
            // - Prefer the first external referrer (saved in sessionStorage)
            // - Fallback to current document.referrer when external
            // - Never send current-domain referrers as plugin_referrer
            var pluginReferrer = '';
            try {
                var storedReferrer = sessionStorage.getItem('gc_plugin_referrer') || '';
                if (storedReferrer) {
                    pluginReferrer = storedReferrer;
                } else if (document.referrer) {
                    var refUrl = new URL(document.referrer);
                    if (refUrl.hostname !== window.location.hostname) {
                        pluginReferrer = document.referrer;
                        sessionStorage.setItem('gc_plugin_referrer', pluginReferrer);
                    }
                }
            } catch (e) { }

            if (
                pluginReferrer &&
                existingParams.indexOf('&plugin_referrer=') === -1 &&
                existingParams.indexOf('&amp;plugin_referrer=') === -1
            ) {
                params.push('plugin_referrer=' + encodeURIComponent(pluginReferrer));
                existingParams += 'plugin_referrer=x&';
            }
            console.log(params);
            var consentParams = gcReadConsentParams();
            if (consentParams) {
                consentParams.substring(1).split('&').forEach(function (token) {
                    if (token) params.push(token);
                });
            }
            href = baseHref + (params.length ? '?' + params.join('&') : '');
            $link.attr('href', href + hash);
        }

        // Exclude .search-submit: it has its own mouseover -> updateUrl() handler
        jQuery(document).on('mouseenter touchstart', 'a[href*="gocars.gr"]', function () {
            gcAppendUtmToLink(this);
        });

        // Remove target="_blank" from shortcode submit links if injected by the CMS/editor
        jQuery('.search-submit').removeAttr('target');
    }
});
