var connector_check_load = 'success'; var thelastofor = 'zeroorders'; var datajso = {"type":"FeatureCollection","metadata":{"name":"Ростов-на-Дону – для доставки","creator":"Yandex Map Constructor"},"features":[{"type":"Feature","id":0,"geometry":{"type":"Polygon","coordinates":[[[39.549167707618935,47.225804126101316],[39.558653613835425,47.21767871819853],[39.585645379829025,47.20569172429896],[39.60775686045875,47.19216186141886],[39.606452981633005,47.15372975732574],[39.61644404759124,47.09237389893102],[39.635018182397125,47.079281763878406],[39.747814620117,47.0705704772688],[39.81304594335916,47.09777328134764],[39.87278410253887,47.1254307589003],[39.877075636962665,47.1311713882308],[39.866260970214626,47.204806962158564],[39.86239858923318,47.23123917748557],[39.935097182372814,47.28724681390628],[39.93213602362039,47.29311583629893],[39.92565580664035,47.30067744124441],[39.924196684936256,47.30485191522438],[39.923939192870755,47.31549094497678],[39.91622515974389,47.31651241196848],[39.91344639120446,47.31664374199411],[39.9126631861721,47.31737334726706],[39.90973421392783,47.31727120313906],[39.81307812986706,47.331686152411535],[39.74283092465945,47.332532375300914],[39.74038475003786,47.328097499363935],[39.72703807797976,47.32497535539569],[39.686350926805204,47.31578989144247],[39.660279855180455,47.31772335472899],[39.65837012236186,47.31847483255422],[39.65448628370828,47.319073088765364],[39.620411500383106,47.309609627846285],[39.59414730970923,47.29092577979373],[39.58573590223852,47.284676885971436],[39.576552018571526,47.27579867557223],[39.574663743425035,47.27059955391404],[39.575007066178955,47.25990761027246],[39.570906474845415,47.25172199229118],[39.56515581871751,47.24894597407172],[39.55764563347579,47.24935508069146],[39.54987795616866,47.24774785782356],[39.54678805138352,47.24473783572569],[39.54417021538493,47.237285098811796],[39.54457133019266,47.23497805399777],[39.53882067406472,47.236527208925146],[39.53242628777324,47.231294974432856],[39.549167707618935,47.225804126101316]]]},"properties":{"description":"27.delivery","fill":"#1bad03","fill-opacity":0.2,"stroke":"#1bad03","stroke-width":"2","stroke-opacity":0.9}}]}; var default_delivery_module = '27.delivery'; var center_map_module = [47.222109, 39.718813]; //start fix: скрытие кнопки при актвином input const targetSelectorFix = 'input'; const buttonsSelectorFix = '.wa-submit-button'; let hasFocusedInputFix = false; function updateButtonVisibilityFix() { const inputs = document.querySelectorAll(targetSelectorFix); const buttons = document.querySelectorAll(buttonsSelectorFix); const anyInputFocused = Array.from(inputs).some(input => input === document.activeElement); if (anyInputFocused && !hasFocusedInputFix) { buttons.forEach(btn => btn.style.display = 'none'); document.getElementById( 'wa-step-confirm-section' ).style.display = 'none'; hasFocusedInputFix = true; } else if (!anyInputFocused && hasFocusedInputFix) { buttons.forEach(btn => btn.style.display = ''); document.getElementById( 'wa-step-confirm-section' ).style.display = ''; hasFocusedInputFix = false; } } // Делегирование фокуса и блюра document.body.addEventListener('focusin', (e) => { if (e.target.matches(targetSelectorFix)) { updateButtonVisibilityFix(); } }); document.body.addEventListener('focusout', (e) => { // Небольшая задержка, чтобы дать другому input получить фокус setTimeout(updateButtonVisibilityFix, 500); }); // Следим за изменениями DOM const observerFix = new MutationObserver((mutations) => { let shouldCheck = false; for (const m of mutations) { if ([...m.addedNodes, ...m.removedNodes].some(node => node.nodeType === 1 && (node.matches?.(targetSelectorFix) || node.querySelector?.(targetSelectorFix)) )) { shouldCheck = true; break; } } if (shouldCheck) { updateButtonVisibilityFix(); } }); observerFix.observe(document.body, { childList: true, subtree: true }); //end fix: скрытие кнопки при актвином input let lastAddress = ''; let customHtml_shipping = `
`; function openModal(){ //document.getElementById('map-modal').style.display = 'block'; UIkit.modal("#map-modal").show(); const elementmodfixshow = document.getElementById('wa-step-confirm-section'); if (elementmodfixshow) { elementmodfixshow.style.display = 'none'; } //modalMap.container.fitToViewport(); } let globalzone = 'notinzone'; // Наблюдатель за DOM const observer = new MutationObserver(() => { const btn = document.getElementById('show-map-btn_new'); if (btn && !btn.dataset.clickAttached) { btn.dataset.clickAttached = 'true'; // чтобы не навешивать повторно btn.onclick = openModal; } }); // Запуск наблюдения за всей страницей observer.observe(document.body, { childList: true, subtree: true }); function sc_addressNotZone(){ if (globalzone!='yesinzone'){ var sc_messageNotZone = `укажите адрес или выберите на карте`; //document.getElementById('shipping_address_street').value = ''; document.getElementById('wa-step-details-section').querySelector('.wa-delivery-price').innerHTML = sc_messageNotZone; document.getElementById('wa-step-confirm-section').querySelector('.wa-item-shipping').querySelector('.wa-value').innerHTML = sc_messageNotZone; //document.querySelector('.wa-item-total').remove(); //document.querySelector('.js-submit-order-button').remove(); document.querySelector('.wa-item-total')?.remove(); document.querySelector('.js-submit-order-button')?.remove(); if(document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]').value!==''){ //document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]').value=''; } } globalzone='notinzone'; } let first_preinput_address = ''; function preinput_address(){ if(!thelastofor||thelastofor==='zeroorders'||thelastofor===''){ var elem_address = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]'); var elem_address_value = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]').value; if(elem_address_value===''){ elem_address.value=first_preinput_address; var event_address = new Event('blur'); elem_address.dispatchEvent(event_address); setTimeout(sc_addressNotZone, 1000); }else{ elem_address.value=elem_address_value+' '; var event_address = new Event('blur'); elem_address.dispatchEvent(event_address); } //console.log('preinput_address_notzone'); }else{ var elem_address = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]'); elem_address.value=thelastofor; var event_address = new Event('blur'); elem_address.dispatchEvent(event_address); //console.log('preinput_address_good'); } } function check_address(){ var elem_address = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]').value; if(elem_address===''){ sc_addressNotZone(); }else{ //preinput_address(); } } first_response = 'deliveryDiv_1_not_find'; function first_change(){ var zoneName_1 = default_delivery_module; var deliveryDiv_1 = document.querySelector('div[data-variant-id="' + zoneName_1 + '"]'); if (deliveryDiv_1) { first_response = 'deliveryDiv_1_find'; var clickEvent_1 = new MouseEvent('click', { bubbles: true, // Событие всплывает cancelable: true, // Событие можно отменить view: window // Связь с window }); if (document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]')) { //first_preinput_address = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]').value; } // Инициируем событие клика на элементе document.querySelector('div[data-variant-id="' + zoneName_1 + '"]').dispatchEvent(clickEvent_1); //document.querySelector('div[data-id="' + zoneName_1 + '"]').dispatchEvent(clickEvent_1); setTimeout(sc_addressNotZone, 100); //setTimeout(preinput_address, 900); // Останавливаем интервал, так как условие выполнено clearInterval(checkInterval); }else{ first_response = 'deliveryDiv_1_not_find'; //console.log('bad response'); } } // Запускаем проверку каждые 2 секунды const checkInterval = setInterval(first_change, 2000); const checkInterval_2 = setInterval(check_address, 1000); //let countercheck = 0; //const maxAttemptscheck = 180; //const intervalcheck = setInterval(() => { // check_address(); // Вызываем функцию // countercheck++; // if (countercheck >= maxAttemptscheck) { // clearInterval(intervalcheck); // Останавливаем, когда достигли 180 раз // } //}, 50); // Интервал 50 мс, суммарно 9 секунд setTimeout(first_change, 100); setInterval(function insert_modalbutton(){ const addressInput = document.querySelector('input[name="details[shipping_address][street]"]'); if (addressInput) { var existingSpan = document.getElementById('shipping_address_after'); if (!existingSpan) { let customHtml_shipping = `выбрать адрес на карте`; addressInput.insertAdjacentHTML('afterend', customHtml_shipping); } } },1000); function setupAddressInputListener() { // Проверяем, может быть поле уже есть в DOM const addressInput = document.querySelector('input[name="details[shipping_address][street]"]'); if (addressInput) { attachAddressInputHandlers(addressInput); } // Наблюдаем за изменениями DOM на случай динамического добавления поля const observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { mutation.addedNodes.forEach(function(node) { if (node.nodeType === 1) { // Element node const inputs = node.querySelectorAll ? node.querySelectorAll('input[name="details[shipping_address][street]"]') : []; inputs.forEach(attachAddressInputHandlers); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); } function attachAddressInputHandlers(input) { let timeout; // Обработчик для ручного ввода с задержкой input.addEventListener('input', function() { clearTimeout(timeout); timeout = setTimeout(() => { handleAddressCompletion(input.value); }, 3000); }); // Обработчик для потери фокуса input.addEventListener('blur', function() { handleAddressCompletion(input.value); }); // Обработчик для выбора из автодополнения input.addEventListener('change', function() { setTimeout(() => handleAddressCompletion(input.value), 500); }); } // Функция, которая будет вызвана при завершении ввода адреса function handleAddressCompletion(address) { //if (!address || address.trim() === '') return; if(lastAddress!=address){ console.log('Адрес введён:'+address); //document.getElementById('address-input').value = address; var event = new Event('blur'); var elem = document.getElementById('address-input'); elem.dispatchEvent(event); //console.log('указан'); // присвоить переменной значение } lastAddress = address; } document.querySelector('body').insertAdjacentHTML('beforeend', customHtml_shipping); setupAddressInputListener(); const modal_click = document.getElementById('map-modal'); const modalContent_click = document.querySelector('.modal-content'); // Закрытие по клику вне контента modal_click.addEventListener('click', function(e) { if (!modalContent_click.contains(e.target)) { //modal_click.style.display = 'none'; UIkit.modal("#map-modal").hide(); setTimeout(() => { document.getElementById('wa-step-confirm-section').style.display = ''; }, 1000); setTimeout(() => { document.getElementById('wa-step-confirm-section').style.display = ''; }, 2000); } }); ymaps.ready(init); function init() { const allZonesCoordinates = []; datajso.features.forEach(zone => { zone.geometry.coordinates[0].forEach(coord => { allZonesCoordinates.push([coord[1], coord[0]]); }); }); function getBoundsFromCoordinates(coordsArray) { let lats = coordsArray.map(c => c[0]); let lons = coordsArray.map(c => c[1]); return [ [Math.min(...lats), Math.min(...lons)], [Math.max(...lats), Math.max(...lons)] ]; } const bounds = getBoundsFromCoordinates(allZonesCoordinates); const map = new ymaps.Map('map', { center: center_map_module, zoom: 11 }); const modalMap = new ymaps.Map('modal-map', { center: center_map_module, zoom: 11, controls: ['geolocationControl'] }); const zonePolygons = []; datajso.features.forEach(zone => { const coordinates = zone.geometry.coordinates[0].map(coord => [coord[1], coord[0]]); const polygonOptions = { hintContent: zone.properties.description, fillColor: zone.properties.fill || '#f371d1', fillOpacity: 0.6, strokeColor: zone.properties.stroke || '#f371d1', strokeWidth: parseInt(zone.properties['stroke-width']) || 0, strokeOpacity: 0.6 }; const polygon = new ymaps.Polygon([coordinates], {}, polygonOptions); const modalPolygon = new ymaps.Polygon([coordinates], {}, polygonOptions); polygon.events.add('click', e => { e.preventDefault(); const coords = e.get('coords'); getAddressByCoords(coords, zone.properties.description); }); modalPolygon.events.add('click', e => { e.preventDefault(); const coords = e.get('coords'); getAddressByCoords(coords, zone.properties.description); }); map.geoObjects.add(polygon); modalMap.geoObjects.add(modalPolygon); zonePolygons.push({ polygon: polygon, modalPolygon: modalPolygon, id: zone.id, name: zone.properties.description }); }); const infoPanel = document.getElementById('info'); //const showMapBtn = document.getElementById('show-map-btn'); //const mapModal = document.getElementById('map-modal'); const closeModal = document.getElementById('close-modal'); let currentPlacemark = null; let modalPlacemark = null; let suggestView = null; let addressSelected = false; //showMapBtn.addEventListener('click', () => { // mapModal.style.display = 'block'; // modalMap.container.fitToViewport(); //}); closeModal.addEventListener('click', () => { //mapModal.style.display = 'none'; //document.getElementById('map-modal').style.display = 'none'; UIkit.modal("#map-modal").hide(); setTimeout(() => { document.getElementById('wa-step-confirm-section').style.display = ''; }, 1000); setTimeout(() => { document.getElementById('wa-step-confirm-section').style.display = ''; }, 2000); }); function initializeInput(inputElement) { if (inputElement.dataset.suggestInit) return; inputElement.dataset.suggestInit = "true"; suggestView = new ymaps.SuggestView(inputElement.id, { boundedBy: bounds, strictBounds: true }); suggestView.events.add('select', e => { addressSelected = true; const selectedItem = e.get('item'); processAddressSelection(selectedItem.value); }); inputElement.addEventListener('blur', () => { if (inputElement.value && !addressSelected) { checkAddressZone(inputElement.value, true); } addressSelected = false; }); inputElement.addEventListener('keydown', e => { if (e.key === 'Enter') { checkAddressZone(inputElement.value, true); } }); } // Наблюдатель за появлением address-input //const observer = new MutationObserver(() => { // const input = document.getElementById('address-input'); // //const input = document.querySelector('input[name="details[shipping_address][street]"]'); // if (input) { // initializeInput(input); // } //}); const observer = new MutationObserver(() => { const input = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]'); if (input && !input.dataset.suggestInit) { input.dataset.suggestInit = "true"; const suggestView = new ymaps.SuggestView(input, { boundedBy: bounds, strictBounds: true }); suggestView.events.add('select', e => { addressSelected = true; const selectedItem = e.get('item'); input.value = selectedItem.value; checkAddressZone(selectedItem.value, true); }); input.addEventListener('blur', () => { if (input.value && !addressSelected) { checkAddressZone(input.value, true); } addressSelected = false; }); input.addEventListener('keydown', e => { if (e.key === 'Enter') { checkAddressZone(input.value, true); } }); } }); observer.observe(document.body, { childList: true, subtree: true }); //const initialInput = document.getElementById('address-input'); const initialInput = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]'); //const initialInput = document.querySelector('input[name="details[shipping_address][street]"]'); if (initialInput) initializeInput(initialInput); function processAddressSelection(address) { //const input = document.getElementById('address-input'); const input = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]'); //const input = document.querySelector('input[name="details[shipping_address][street]"]'); if (input) { input.value = address; checkAddressZone(address, true); } } function getAddressByCoords(coords, zoneName = null) { ymaps.geocode(coords, { results: 1 }).then(res => { const firstGeoObject = res.geoObjects.get(0); if (firstGeoObject) { const address = firstGeoObject.getAddressLine(); //const input = document.getElementById('address-input'); const input = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]'); //const input = document.querySelector('input[name="details[shipping_address][street]"]'); if (input) input.value = address; updateMapWithMarker(map, coords, address); updateMapWithMarker(modalMap, coords, address); map.setCenter(coords, 17); modalMap.setCenter(coords, 17); if (!zoneName) { checkZoneContainment(coords, address); } else { infoPanel.innerHTML = `
Адрес: ${address}
`; var deliveryDiv = document.querySelector('div[data-variant-id="' + zoneName + '"]'); if (deliveryDiv) { var clickEvent = new MouseEvent('click', { bubbles: true, // Событие всплывает cancelable: true, // Событие можно отменить view: window // Связь с window }); // Инициируем событие клика на элементе deliveryDiv.dispatchEvent(clickEvent); //setTimeout(load_js_shipping(), 1000); } } } }); } function checkAddressZone(address, centerMap = false) { infoPanel.innerHTML = 'Проверяем адрес...'; ymaps.geocode(address, { results: 1, boundedBy: bounds, strictBounds: true }).then(res => { const firstGeoObject = res.geoObjects.get(0); if (!firstGeoObject) { infoPanel.innerHTML = 'Адрес находится вне зон доставки'; sc_addressNotZone(); setTimeout(sc_addressNotZone, 100); setTimeout(sc_addressNotZone, 300); setTimeout(sc_addressNotZone, 500); setTimeout(sc_addressNotZone, 900); setTimeout(sc_addressNotZone, 1900); setTimeout(sc_addressNotZone, 2300); setTimeout(sc_addressNotZone, 2900); return; } const coords = firstGeoObject.geometry.getCoordinates(); const foundAddress = firstGeoObject.getAddressLine(); //const input = document.getElementById('address-input'); const input = document.querySelector('input[name="details\\[shipping_address\\]\\[street\\]"]'); //const input = document.querySelector('input[name="details[shipping_address][street]"]'); if (input) input.value = foundAddress; updateMapWithMarker(map, coords, foundAddress); updateMapWithMarker(modalMap, coords, foundAddress); setTimeout(updateMapWithMarker(map, coords, foundAddress), 500); setTimeout(updateMapWithMarker(modalMap, coords, foundAddress), 700); if (centerMap) { map.setCenter(coords, 17); modalMap.setCenter(coords, 17); } checkZoneContainment(coords, foundAddress); }).catch(err => { setTimeout(sc_addressNotZone, 1000); console.log('not found'); infoPanel.innerHTML = 'Адрес не найден'; setTimeout(sc_addressNotZone, 100); setTimeout(sc_addressNotZone, 300); setTimeout(sc_addressNotZone, 500); setTimeout(sc_addressNotZone, 900); //console.error('Geocode error:', err); }); } function updateMapWithMarker(mapInstance, coords, address) { if (mapInstance === map && currentPlacemark) { map.geoObjects.remove(currentPlacemark); } else if (mapInstance === modalMap && modalPlacemark) { modalMap.geoObjects.remove(modalPlacemark); } const placemark = new ymaps.Placemark(coords, { hintContent: address, balloonContent: address }, { preset: 'islands#redDotIcon' }); mapInstance.geoObjects.add(placemark); if (mapInstance === map) { currentPlacemark = placemark; } else { modalPlacemark = placemark; } } function checkZoneContainment(coords, address) { let zoneInfo = 'Адрес вне зон доставки'; zonePolygons.forEach(zone => { if (zone.polygon.geometry.contains(coords)) { zoneInfo = `Адрес находится в зоне: ${zone.name}`; globalzone = 'yesinzone'; var deliveryDiv = document.querySelector('div[data-variant-id="' + zone.name + '"]'); if (deliveryDiv) { var clickEvent = new MouseEvent('click', { bubbles: true, // Событие всплывает cancelable: true, // Событие можно отменить view: window // Связь с window }); // Инициируем событие клика на элементе deliveryDiv.dispatchEvent(clickEvent); //setTimeout(load_js_shipping(), 1000); } }else{ sc_addressNotZone(); } }); infoPanel.innerHTML = `
Адрес: ${address}
`; } } function makeDeliveryTimeRequired11() { var dd = $(document).find('.wa-desired-date-wrapper'); var parent = dd.closest('.wa-plugin-fields-wrapper'); var label = parent.find('.wa-label'); var new_label = 'Желаемое время доставки'; label.html(new_label); parent.find('#wahtmlcontrol_details_custom_desired_delivery_interval').prop('required', true).addClass('wa-select'); } function validateFields11(){ var dd = $(document).find('.wa-desired-date-wrapper'); var parent = dd.closest('.wa-plugin-fields-wrapper'); var date_inp = dd.find('#wahtmlcontrol_details_custom_desired_delivery_date_str'); var time_select = dd.find('select[name="details[custom][desired_delivery.interval]"]'); var date_val = date_inp.val() || false; var time_val = time_select.val() || false; //var buttonsubmit = document.querySelector('.js-submit-order-button'); parent.find('.wa-error-text').remove(); date_inp.removeClass('wa-error'); time_select.removeClass('wa-error'); if(!date_val || date_val == ''){ date_inp.addClass('wa-error'); date_inp.after('
Обязательное поле
'); //if (buttonsubmit) buttonsubmit.classList.add('d-none'); } else if(!time_val || time_val == ''){ time_select.addClass('wa-error'); time_select.after('
Обязательное поле
'); //if (buttonsubmit) buttonsubmit.classList.add('d-none'); } else { //if (buttonsubmit) buttonsubmit.classList.remove('d-none'); } } function validateFields2(){ var dd = $(document).find('.wa-desired-date-wrapper'); var parent = dd.closest('.wa-plugin-fields-wrapper'); var date_inp = dd.find('#wahtmlcontrol_details_custom_desired_delivery_date_str'); var time_select = dd.find('select[name="details[custom][desired_delivery.interval]"]'); var date_val = date_inp.val() || false; var time_val = time_select.val() || false; var buttonsubmit = document.querySelector('.js-submit-order-button'); parent.find('.wa-error-text').remove(); date_inp.removeClass('wa-error'); time_select.removeClass('wa-error'); if(!date_val || date_val == ''){ if (buttonsubmit) buttonsubmit.classList.add('d-none'); } else if(!time_val || time_val == ''){ if (buttonsubmit) buttonsubmit.classList.add('d-none'); } else { if (buttonsubmit) buttonsubmit.classList.remove('d-none'); } } $(document).on('focus', '#wahtmlcontrol_details_custom_desired_delivery_date_str', function() { //$(this).removeClass('wa-error'); //$(this).closest('.wa-field-wrapper').find('.wa-error-text').remove(); }); $(document).on('focus', '#wahtmlcontrol_details_custom_desired_delivery_interval', function() { //$(this).removeClass('wa-error'); // $(this).closest('.wa-field-wrapper').find('.wa-error-text').remove(); }); $(document).on('wa_order_form_ready', function (e) { //makeDeliveryTimeRequired(); }); $(document).on('wa_order_form_changed', function (e) { //makeDeliveryTimeRequired(); }); $(document).on('wa_order_form_region_changed', function () { //makeDeliveryTimeRequired(); }); $(document).on('wa_order_form_details_changed', function () { // makeDeliveryTimeRequired(); }); $(document).on('click', '.js-submit-order-button', function () { //validateFields(); }); //const intervalId = setInterval(validateFields2, 700); // эмулируем смену адреса для надежного просчета стоимости доставки let isDeliveryCoastFixed = false; function fixDeliveryCoast() { console.log('Start check delivery'); if (isDeliveryCoastFixed) return; console.log('Trying to fix delivery coast...'); const input = document.querySelector('input[name="details[shipping_address][street]"]'); if (input && input.offsetParent !== null) { input.focus(); const clickEvent = new MouseEvent('click', { bubbles: true, view: window }); input.dispatchEvent(clickEvent); input.dispatchEvent(new Event('focus', { bubbles: true })); setTimeout(function() { input.blur(); input.dispatchEvent(new Event('blur', { bubbles: true })); input.dispatchEvent(new Event('change', { bubbles: true })); console.log('Delivery coast fixed successfully!'); isDeliveryCoastFixed = true; }, 300); } else { console.log('Input not available yet'); } } // Запускаем в несколько этапов setTimeout(fixDeliveryCoast, 7000); // Первая попытка setTimeout(fixDeliveryCoast, 9000); // Вторая попытка setTimeout(fixDeliveryCoast, 12000); // Третья попытка setTimeout(fixDeliveryCoast, 15000); // Финальная попытка // Фикс стоимости доставки после ввода адреса (function() { const ADDRESS_INPUT_SELECTOR = 'input[name="details[shipping_address][street]"]'; const COOLDOWN_TIME = 4000; const FIX_DELAY = 300; const SUCCESS_DELAY = 3000; let successTimer = null; let lastTriggerTime = 0; function fixDelivery2Cost() { try { console.log('Trying to fix delivery cost...'); const input = document.querySelector(ADDRESS_INPUT_SELECTOR); if (input && window.getComputedStyle(input).display !== 'none') { input.focus(); const clickEvent = new MouseEvent('click', { bubbles: true, view: window }); input.dispatchEvent(clickEvent); input.dispatchEvent(new Event('focus', { bubbles: true })); setTimeout(() => { input.blur(); input.dispatchEvent(new Event('blur', { bubbles: true })); input.dispatchEvent(new Event('change', { bubbles: true })); console.log('Delivery cost fixed successfully!'); }, FIX_DELAY); } else { console.log('Input not available or hidden'); } } catch (error) { console.error('Error fixing delivery cost:', error); } } function successInputAddress() { console.log('Success: 3 seconds after address input blur'); fixDelivery2Cost(); } document.addEventListener('focus', (e) => { if (e.target.matches(ADDRESS_INPUT_SELECTOR)) { clearTimeout(successTimer); console.log('Address input focused'); } }, true); document.addEventListener('blur', (e) => { if (e.target.matches(ADDRESS_INPUT_SELECTOR)) { clearTimeout(successTimer); const currentTime = Date.now(); if (currentTime - lastTriggerTime >= COOLDOWN_TIME) { successTimer = setTimeout(() => { lastTriggerTime = Date.now(); successInputAddress(); }, SUCCESS_DELAY); console.log('Address input blurred - timer started'); } else { console.log('Address input blurred - cooldown active, skipping'); } } }, true); })();