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":[[[82.83132527770961,55.044566317823225],[82.81564306810212,55.03549568542179],[82.8096563775809,55.037578376881015],[82.79459309175326,55.039660959598066],[82.78682568728101,55.04390383036357],[82.77971246897357,55.041821469207264],[82.77725020109798,55.03992383831364],[82.77214327513374,55.036584281587366],[82.75386133848829,55.01917955764455],[82.7343777722041,54.99875754418154],[82.7389697140376,54.992959538280495],[82.73824015318554,54.991059583091804],[82.74519243895219,54.99002320581638],[82.84097948729209,54.959265116934546],[82.83492842375449,54.949336510699545],[82.84192362486534,54.94568058239048],[82.93535147908914,54.93986463629044],[82.93763672116981,54.93959285906827],[82.9370680928586,54.93634992031826],[83.01264201406227,54.939456969796446],[83.01108633283364,54.949672088425444],[82.98503671888102,54.957896637092624],[82.961232177328,54.97457249841869],[82.9767031589259,54.98009549983591],[82.98751782567393,54.984920559153316],[82.99212049634349,54.987326700969874],[82.99578975827583,54.98608663059249],[83.00049971730601,54.98894305336092],[83.00083231122385,54.99070122502982],[83.00331067235362,54.992625871634274],[82.99851488263502,55.00079841808027],[83.00073575169938,55.00355511885085],[83.00126146466631,55.004856314187805],[83.00303172261614,55.00573197627927],[83.00305318028825,55.00710709700721],[83.0056281009426,55.00946257495216],[82.99990963132285,55.01197205432169],[83.00402950436967,55.015289011056815],[83.00596069486039,55.01585003039169],[83.01616381795306,55.017329604011735],[83.01766585500137,55.01789059466826],[83.02265476376907,55.02434450240441],[83.0228907981624,55.02494237608607],[83.02025150449182,55.0341805430135],[83.01817011029625,55.03692877753116],[83.01727961690332,55.03860473792798],[83.02211832196618,55.039393400804144],[83.01528405339627,55.04346585699648],[83.00143097343368,55.051751973506605],[82.99827669563217,55.052959209091206],[82.99338434638899,55.054258794291904],[82.98973654212881,55.05574926165482],[82.98399661483694,55.06004790078192],[82.97841762008598,55.05744906549748],[82.96826814117362,55.064746312608285],[82.98047755660949,55.0702137536532],[82.983095392608,55.07178365719223],[82.98493002357421,55.07359358683761],[82.98508022727904,55.07464010727292],[82.98497293891842,55.075637354103385],[82.98407171668947,55.07670228766211],[82.98282717170657,55.077490197051056],[82.98093889656006,55.07821653721124],[82.97546719016974,55.08023544706129],[82.96747420730536,55.08368828430655],[82.96444867553654,55.08498071321515],[82.9615197032923,55.08638387424696],[82.95835469665474,55.08861775228179],[82.95531843604992,55.09060536757011],[82.95413826408334,55.09091919249159],[82.95201395454357,55.0910607205683],[82.94578050079298,55.09009462760991],[82.93674682083088,55.086894661840844],[82.93475125732378,55.086343872555545],[82.93138240280106,55.08464222402216],[82.92741273345904,55.08683312153293],[82.9035088867183,55.0850237934996],[82.90175472202266,55.08405139957711],[82.89722715320552,55.08139873589449],[82.895875319862,55.08213423691928],[82.89509211482964,55.082682007098974],[82.89384220542873,55.08406370851488],[82.89356862010918,55.08473146239846],[82.89303217830623,55.08751621383146],[82.88999591770136,55.088959284635024],[82.88603161277736,55.089020821678176],[82.86140893402063,55.08294050279605],[82.86939118804894,55.07255011713232],[82.86441300811734,55.06292058678393],[82.84527276458705,55.05279598819036],[82.83132527770961,55.044566317823225]]]},"properties":{"description":"24.delivery","fill":"#1bad03","fill-opacity":0.2,"stroke":"#1bad03","stroke-width":"2","stroke-opacity":0.9}},{"type":"Feature","id":1,"geometry":{"type":"Polygon","coordinates":[[[82.86134973895975,55.0830786544015],[82.88597873293675,55.089123423081055],[82.89007714831152,55.08903727142362],[82.89314559542454,55.087597280406534],[82.89366057955543,55.08485253790063],[82.89389661394875,55.084175554382085],[82.8955488547019,55.08243996223835],[82.89724401079935,55.081553673248216],[82.90340236269753,55.08512332809062],[82.92749932848737,55.08692034356627],[82.93136170946882,55.08480330313456],[82.93466619097516,55.086452635018695],[82.93666175448226,55.086969575725355],[82.94563106142805,55.090169535489494],[82.95204690539168,55.09114178000708],[82.95410684191509,55.0910433259466],[82.9554372175865,55.09066181416225],[82.96176723086168,55.08632955291962],[82.9671960219078,55.08389244879736],[82.97584346377185,55.08018727242673],[82.98281720721059,55.077589750554914],[82.98324636065301,55.077368153173985],[82.9841261252099,55.07676490959807],[82.98504880511099,55.075792313980465],[82.98522046648795,55.074684264716204],[82.98517755114374,55.07361312113238],[82.98328927599727,55.071766254196724],[82.98073581301507,55.07020250658523],[82.968462024563,55.06475969380955],[82.97848275744262,55.057653364558455],[82.98408320986573,55.06017828871198],[82.98985532366581,55.05581807540409],[82.99348167025394,55.05432761061966],[82.99828818880864,55.05305882395724],[83.00154975497072,55.05183927250122],[83.00607732378786,55.04910438512113],[83.02236369692633,55.039382929183574],[83.01740697466678,55.03858194311595],[83.01830819689577,55.03694295226185],[83.02038959109134,55.03426866470815],[83.02302888476206,55.024975045886606],[83.02283576571295,55.02443264584181],[83.01783612810925,55.01788628213047],[83.01626971804453,55.0172698083865],[83.00605586611586,55.01581489260722],[83.00412467562518,55.015247707681674],[83.00009063326674,55.011992403568236],[83.00584128939475,55.0094890914702],[83.00318053805198,55.00708428426114],[83.00320199572408,55.0057276624544],[83.00135663592182,55.004802666616094],[83.0009060248073,55.00358163930248],[82.99869588457905,55.000781769072546],[83.00350240313377,54.99261538782325],[83.00092748247947,54.99066606515424],[83.000669990414,54.98896341438062],[82.99588492953144,54.98595275285623],[82.99215129458273,54.98718665796344],[82.98708728396261,54.98457073390435],[82.97693780505026,54.98006650118453],[82.96145553897365,54.974551978563824],[82.98508043597691,54.9579969089393],[83.0111944229459,54.949735329658424],[83.01288957904336,54.93940904487393],[82.93703670810237,54.93629581446982],[82.92467708896187,54.871109527924126],[82.92879696200875,54.867297946377626],[82.96585436175855,54.859933638743534],[82.96673412631544,54.861035276570675],[82.98134680102866,54.85540299015182],[82.98134680102866,54.852927009879814],[82.98623915027184,54.84416081294299],[83.08176870654627,54.819833267415625],[83.13395376513999,54.832469574013366],[83.16755647967881,54.840792499788314],[83.16536779712271,54.846340159288175],[83.18373556445675,54.84690974167647],[83.184851363407,54.8525555997632],[83.16940183948121,54.85973558838945],[83.16691274951539,54.868003363881805],[83.1614195854529,54.87315129782836],[83.16150541614137,54.87716028897075],[83.15343733142458,54.88191116723628],[83.16373701404177,54.887601582901674],[83.16283579181304,54.89742183607716],[83.15279360126131,54.9128276123555],[83.15202112506526,54.91443461550157],[83.14897413562439,54.93255220514371],[83.14807291339534,54.94248497556],[83.14790125201844,54.946659956731054],[83.1499611885419,54.95221768776034],[83.15395231555603,54.957502991317845],[83.14970369647679,54.95908350728006],[83.14524050067597,54.96572593040002],[83.13901777576143,54.96918251714752],[83.13429708789525,54.969602225196],[83.1284176857346,54.96787398730839],[83.12073583911592,54.96693576975235],[83.11481352161107,54.9674789510233],[83.11155195544893,54.96851591296244],[83.10942764590956,54.971651324867494],[83.11298961948138,54.97334237011622],[83.11487789462784,54.97383609247097],[83.11627264331557,54.974292780216125],[83.11801071475723,54.97619353262776],[83.12041397403459,54.97739071340957],[83.12187309573869,54.97744008091952],[83.12395448993425,54.97847678454562],[83.13367481540425,54.98406711567364],[83.10268417728152,55.039255225533644],[83.10543075931277,55.0453175716656],[83.11015144717899,55.04726422716743],[83.10165420901978,55.056183129345364],[83.08594719302873,55.06315425168137],[83.08401600253801,55.06490299916284],[83.04650799167388,55.07758527889913],[83.03899780643214,55.079444186411074],[83.03657308948267,55.07951189332493],[83.03613320720426,55.07972732364867],[83.03283409011604,55.08237394399173],[83.03311303985362,55.083057112762106],[83.03332761657478,55.08327252390785],[83.0324103010917,55.08400799032401],[83.03259805572289,55.084254168543694],[83.03097263705986,55.08548195955407],[83.0301894320275,55.08573428284126],[83.02942768466734,55.086041992008475],[83.02827969920898,55.086657403197854],[83.0284459961679,55.0868912569557],[83.02677766216063,55.08765742609282],[83.02554921043182,55.08834973492682],[83.02535609138272,55.08833435041698],[83.02499667537474,55.08848204146609],[83.02365020644925,55.088291273768604],[83.02108065021318,55.09022967732761],[82.9961039198665,55.09475840465799],[83.00211206806009,55.10663156079094],[82.98623339069198,55.109202585946086],[82.98318640125105,55.10985454198787],[82.97983900440049,55.11125682632306],[82.97713533771346,55.10938710289105],[82.97719971072982,55.10776332440275],[82.97662035358267,55.10730816251193],[82.97267214191275,55.10599185413112],[82.97138468158559,55.10593034332863],[82.96580568683459,55.104244910338814],[82.96381012332755,55.103863525085174],[82.95915380847778,55.10337140970594],[82.95805946719973,55.10316225881515],[82.95295254123535,55.104490963428276],[82.95235172641603,55.103838919486584],[82.95162216556399,55.10364207393267],[82.94754520786142,55.102842378899176],[82.94312492740488,55.10292850067969],[82.93627992999892,55.10398655306182],[82.93314710986952,55.10436793713621],[82.92741791141371,55.10422030502495],[82.9243923796449,55.10442945035965],[82.92068020236829,55.10720974851987],[82.91928545368062,55.11476232101644],[82.9181696547304,55.12151413984685],[82.91784778964877,55.12271926202049],[82.91712895763277,55.123690711434044],[82.91625992191194,55.124317837056026],[82.91492954624059,55.12492036019902],[82.91320220363497,55.12532613594582],[82.91154996288181,55.125424505200165],[82.90311709773907,55.12776070347444],[82.9011429919041,55.12818489316797],[82.90043488872415,55.12820948373604],[82.90027395618361,55.12886727583528],[82.89884702098767,55.129260716345314],[82.8982247484962,55.12953120443714],[82.89736644161147,55.129746364110424],[82.88826838863295,55.131215566142735],[82.88757101428911,55.13143686384058],[82.8858973158638,55.1318671613876],[82.87482515705035,55.12626063411711],[82.86280886066385,55.096198137038826],[82.85328165424296,55.09277715023464],[82.86134973895975,55.0830786544015]]]},"properties":{"description":"25.delivery","fill":"#ffd21e","fill-opacity":0.3,"stroke":"#ffd21e","stroke-width":"2","stroke-opacity":0.9}},{"type":"Feature","id":2,"geometry":{"type":"Polygon","coordinates":[[[83.1337792239733,54.98402824179908],[83.12585061412429,54.979425217765616],[83.12409644942854,54.978471844292244],[83.12189167361832,54.97740120038516],[83.12042182307817,54.977333319977234],[83.11805075030902,54.97614230861762],[83.11634486537557,54.97427241090201],[83.11486428599936,54.97376017943594],[83.11299746852495,54.97326645614897],[83.10957496982208,54.97164946971401],[83.11178511005032,54.968575780842976],[83.11485355716336,54.96763757974684],[83.1207115016519,54.96716847094446],[83.1284362636148,54.96806964878065],[83.13410108905428,54.96976084550755],[83.13907926898594,54.969365827861935],[83.145387824589,54.96579814793895],[83.14978664737339,54.95922982183553],[83.15412109714147,54.957562875763045],[83.15012997012728,54.9521664332324],[83.14804857593177,54.94664574923284],[83.14916437488203,54.93256270410373],[83.15223282199516,54.91444511922705],[83.15302675586358,54.912801031084335],[83.16313331943178,54.89751891012022],[83.17536419253969,54.902564137981905],[83.19047039371165,54.90525961222977],[83.2100397906843,54.91935225935555],[83.23587482791577,54.928546893319016],[83.24282711368235,54.93388474450719],[83.249607738072,54.94292781258647],[83.29956119876546,54.9507585459923],[83.30050533633872,54.96725488626202],[83.30217903476402,54.98093082290683],[83.28248089175862,54.99334373186752],[83.25505798679038,54.99127106893089],[83.23145454745948,55.00491412395981],[83.21126287799545,55.00324908214711],[83.18345373492905,55.00053553186039],[83.16328352313712,54.98748324647333],[83.14547365527824,54.988939194690964],[83.1337792239733,54.98402824179908]]]},"properties":{"description":"26.delivery","fill":"#ed4543","fill-opacity":0.2,"stroke":"#ed4543","stroke-width":"1","stroke-opacity":0.9}}]};
var default_delivery_module = '24.delivery';
var center_map_module = [55.030204, 82.920430];
//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);
})();