let jsSelectBody = $$(".claim-select");
for (let i = 0; i < jsSelectBody.length; i++) {
    let selEl = jsSelectBody[i].getElementsByTagName("select")[0];
    let selItem = document.createElement("div");
    selItem.setAttribute("class", "selected-item");
    selItem.innerHTML = selEl.options[selEl.selectedIndex].innerHTML;
    jsSelectBody[i].appendChild(selItem);
    let selItems = document.createElement("div");
    selItems.setAttribute("class", "select-items select-hide");
    for (let j = 1; j < selEl.length; j++) {
        let selItemEl = document.createElement("div");
        selItemEl.innerHTML = selEl.options[j].innerHTML;
        selItemEl.addEventListener("click", function(e) {
            let selItemElPar = this.parentNode.parentNode.getElementsByTagName("select")[0];
            let prevSelItemEl = this.parentNode.previousSibling;
            for (let i = 0; i < selItemElPar.length; i++) {
                if (selItemElPar.options[i].innerHTML === this.innerHTML) {
                    selItemElPar.selectedIndex = i;
                    prevSelItemEl.innerHTML = this.innerHTML;
                    let selectedEl = this.parentNode.getElementsByClassName("same-as-selected");
                    for (let k = 0; k < selectedEl.length; k++) {
                        selectedEl[k].removeAttribute("class");
                    }
                    this.setAttribute("class", "same-as-selected");
                    break;
                }
            }
            prevSelItemEl.click();
        });
        selItems.appendChild(selItemEl);
    }
    jsSelectBody[i].appendChild(selItems);
    selItem.addEventListener("click", function(e) {
        e.stopPropagation();
        closeAllSelect(this);
        this.nextSibling.classList.toggle("select-hide");
        this.classList.toggle("select-arrow-active");
    });
}


function closeAllSelect(el) {
    let arrSel = [];
    let jsSelectItems = $$(".select-items");
    let jsSelectedItem = $$(".selected-item")[0];
    if(jsSelectedItem != undefined && jsSelectedItem.length != 0) {
        for (let i = 0; i < jsSelectedItem.length; i++) {
            if (el == jsSelectedItem[i]) {
                arrSel.push(i)
            } else {
                jsSelectedItem[i].classList.remove("select-arrow-active");
                if (arrSel.indexOf(i)) {
                    jsSelectItems[i].classList.add("select-hide");
                }
            }
        }
    }
}
document.addEventListener("click", closeAllSelect);

if($$('.select-items').length != 0) {
    var selectItemsArr = $$('.select-items')[0].childNodes,
        hiddenBlock = $$('.hidden-claim-el')[0];
    for (let i = 0;i<selectItemsArr.length;i++) {
        selectItemsArr[i].addEventListener('click', function () {
            if (selectItemsArr[i].textContent === 'Другое') {
                hiddenBlock.style.display = 'block';
            } else
                hiddenBlock.style.display = 'none';
        }, false)
    }
}

var modalComplain = $$('#modalComplainForm');
if(modalComplain.length !=0) {
    modalComplain[0].addEventListener('submit',function (e) {
        e.preventDefault();
        var type_complaint = $$('#modal-complain .selected-item')[0].innerText;
        var comment = $$('.hidden-claim-el')[0].value;
        var isEmail = $$('.isEmail')[0].value;
        if (isEmail == ''){
            $$('.email-confirm')[0].style.display = "block";
            return false;
        }

        console.log(type_complaint);

        if (type_complaint === 'Выберите тип жалобы') {
            alert('Выберите тип жалобы');
            return false;
        }

        if (type_complaint === 'Другое' && comment == '') {
            alert('Вы не указали причину жалобы');
            return false;
        }

        grecaptcha.confirmed(function () {
            let data = {
                '_token': document.getElementsByName('csrf-token')[0].attributes[1].nodeValue,
                'g-recaptcha-response': grecaptcha.getResponse(),
                'h1': ($$('.org-title').length != 0) ? $$('.org-title')[0].innerHTML.trim() : '',
                'type_complaint': type_complaint,
                'email': $$('#ttt')[0].value,
                'comment': comment
            };

            fetch('/forms/phone_complaint', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                body: JSON.stringify(data)
            }).then((res) => {
                $$('#modal-complain')[0].classList.remove('open');
                var modalBack =  $$('#modal-back')[0];
                modalBack.classList.add('open');
                let exits = [].slice.call(modalBack.getElementsByClassName('modal-exit'));
                exits.forEach(function (exit) {
                    exit.addEventListener('click', function (event) {
                        event.preventDefault();
                        modalBack.classList.remove('open');
                    });
                });
                grecaptcha.reset();
            }).catch((err) => {
                console.log(err);
                grecaptcha.reset();
            });
        })
        
        return false;
    })
}
if($$('.isEmail').length != 0){
    $$('.isEmail')[0].addEventListener('input',function () {
        if ($$('.email-confirm')[0].style.display = "block") {
            $$('.email-confirm')[0].style.display = "none";
        }
    })
}

// $$('.selected-item')[0].addEventListener('click',function () {
//     var compainModalHeight = $$('#modal-complain')[0].getElementsByClassName('select-items')[0].offsetHeight;
//     var windowHeight = window.pageYOffset;
//     var selectItemsBlock = $$('.select-items')[0];
//     if(compainModalHeight+210 > windowHeight) {
//         selectItemsBlock.style.height = compainModalHeight-60+'px';
//         selectItemsBlock.style.overflowY = 'scroll'
//     } else {
//         selectItemsBlock.style.height = 'fit-content';
//         selectItemsBlock.style.overflowY = 'hidden'
//     }
// },false)
//
//

var orgMenuBankProducts = $$('.org-menu-bank-products');
if(orgMenuBankProducts.length != 0) {
    orgMenuBankProducts = orgMenuBankProducts[0];
    var toggleBankProducts = $$('.toggle-bank-products');
    var orgMenuBankProductsBlock = $$('.org-menu-bank-products-block');
    orgMenuBankProducts.addEventListener('click',function (e){
        toggleBankProducts[0].classList.toggle('active-bank-products-btn');
        orgMenuBankProductsBlock[0].classList.toggle('display_none');
        orgMenuBankProducts.classList.toggle('active-bank-products')
    })
    document.addEventListener( 'click', (e) => {
        if(!e.target.classList.contains('org-menu-bank-products')){
            orgMenuBankProductsBlock[0].classList.add('display_none');
            toggleBankProducts[0].classList.remove('active-bank-products-btn');
            orgMenuBankProducts.classList.remove('active-bank-products')
        }
    })
}let getCurrentDate = () => {
    let Data = new Date();
    let year = Data.getFullYear();
    let Month = Data.getMonth();
    let month = Month < 9 ? '0' + (Month + 1) : Month + 1;
    let day = Data.getDate();
    return [day, month, year];
}

let wordDeclension = (val, el) => {
    val = Math.abs(val) % 100;
    let sumVal = val % 10;
    if(val > 10 && val < 20){
        return el[2];
    }
    if(sumVal > 1 && sumVal < 5){
        return el[1];
    }
    if(sumVal === 1){
        return el[0];
    }
    return el[2];
}

var hiddenRecaptchaCallback = function () {
    console.log('captcha not loaded');
}


if (document.querySelector('.g-hidden-recaptcha-login')) {
    if (!document.querySelector(".g-recaptcha[data-size='invisible']")) {
        loadCaptchaScripts();
        initHiddenRecaptcha();
    }
}

document.querySelectorAll('.g-hidden-recaptcha').forEach(item => {
    item.addEventListener("mouseenter", function () {
        if (!document.querySelector(".g-recaptcha[data-size='invisible']")) {
            loadCaptchaScripts();
            initHiddenRecaptcha();
        }
    });
});

document.querySelectorAll('.captcha-submit').forEach(item => {
    item.addEventListener("mouseenter", function () {
        if (!document.querySelector(".g-recaptcha[data-size='invisible']")) {
            loadCaptchaScripts();
            initHiddenRecaptcha();
        }
    });
});

function loadCaptchaScripts() {
    let scriptEl = document.createElement("script");
    scriptEl.src = 'https://www.google.com/recaptcha/api.js';
    document.head.appendChild(scriptEl);
}

function initHiddenRecaptcha() {
    let hiddenCaptchaElement = document.createElement('div');
    hiddenCaptchaElement.classList.add('g-recaptcha');
    hiddenCaptchaElement.dataset.sitekey = '6LdyDPQjAAAAAApILG4zu-QDa9h4UsVLCzlwrC_Q';
    hiddenCaptchaElement.dataset.callback = 'hiddenRecaptchaCallback';
    hiddenCaptchaElement.dataset.size = 'invisible';
    hiddenCaptchaElement.style.position = 'absolute';
    hiddenCaptchaElement.style.top = '0';
    document.body.appendChild(hiddenCaptchaElement);

    if(typeof grecaptcha === 'undefined') {
        grecaptcha = {};
    }
    grecaptcha.ready = function(cb){
        if(typeof grecaptcha === 'undefined') {
            // window.__grecaptcha_cfg is a global variable that stores reCAPTCHA's
            // configuration. By default, any functions listed in its 'fns' property
            // are automatically executed when reCAPTCHA loads.
            const c = '___grecaptcha_cfg';
            window[c] = window[c] || {};
            (window[c]['fns'] = window[c]['fns']||[]).push(cb);
        } else {
            cb();
        }
    }

    grecaptcha.ready(function () {
        grecaptcha.confirmed = function (callback) {
            hiddenCaptchaElement.style.top = (document.documentElement.scrollTop + 30) + 'px';
            grecaptcha.executed = callback;
            grecaptcha.execute();
        };
    });

    hiddenRecaptchaCallback = function () {
        grecaptcha.executed();
    };

    document.querySelectorAll('.captcha-submit').forEach(button => {
        let form = button.closest('form');

        if (!form) return;

        form.addEventListener('submit', (e) => {
            e.preventDefault();

            grecaptcha.confirmed(function () {
                let input = document.createElement("input");
                input.type = "hidden";
                input.name = "g-recaptcha-response";
                input.value = grecaptcha.getResponse();
                form.appendChild(input);

                form.submit();
            })
        });
    })
}

let fullPage = document.body;
let scrollPageUp = "scroll-page-up";
let scrollPageDown = "scroll-page-down";
let scrollVal = 0;

// window.addEventListener("scroll", () => {
//     let searchBlock = $$('.search-block')[0];
//     scrollSearchBlock = "scroll-search-block";
//
//     let currentScroll = window.pageYOffset;
//     if (currentScroll <= 0) {debugger
//         fullPage.classList.remove(scrollPageUp);
//         searchBlock.classList.remove(scrollSearchBlock);
//         return;
//     }
//     if (currentScroll > scrollVal && !fullPage.classList.contains(scrollPageDown)) {debugger
//         fullPage.classList.remove(scrollPageUp);
//         fullPage.classList.add(scrollPageDown);
//         searchBlock.classList.remove(scrollSearchBlock);
//     } else if (currentScroll < scrollVal && fullPage.classList.contains(scrollPageDown)) {debugger
//         fullPage.classList.remove(scrollPageDown);
//         fullPage.classList.add(scrollPageUp);
//         searchBlock.classList.add(scrollSearchBlock);
//     }
//     scrollVal = currentScroll;
// });

function searchToggle() {
    if (document.querySelector('.ya-site-form_inited_yes')) {
        showSearchBlock();
        return;
    }

    initYandexSearch(window, document, 'yandex_site_callbacks', function () {
        showSearchBlock();
    });
}

document.addEventListener('DOMContentLoaded', function () {
    var favorites = localStorage.getItem('vzo');
    var favoritesBlock = $$('.fav-items-block')[0];

    if (favorites != null && favoritesBlock.length != 0) {

        favorites = favorites.split(',');
        if (favorites.length >= 1) {
            favoritesBlock.classList.remove('hiddenStyle')
            $$('.fav-items-count')[0].innerHTML = favorites.length;
            $$('.fav-items-count')[0].style.display = 'flex';
        } else {
            favoritesBlock.classList.add('hiddenStyle')
        }
    }
    // var compareItems = localStorage.getItem('vzo_compare'+window.CATEGORY_ID);
    var compareItems = null;
    for (let i = 1; i < 15; i++) {
        var compareItemsByCat = localStorage.getItem('vzo_compare' + i);
        if (compareItemsByCat != null) {
            compareItems += compareItemsByCat.split(',').length;
        }
    }
    if ($$('.compare-items-count').length != 0) {
        var compareItemsCountBlock = $$('.compare-items-count')[0];
        if (compareItems != null && Number(compareItems) >= 2 ) {
            compareItemsCountBlock.innerHTML = compareItems;
            compareItemsCountBlock.style.display = 'flex';
            compareItemsCountBlock.closest('.more-info-el').classList.remove('hiddenStyle');
        } else {
            compareItemsCountBlock.closest('.more-info-el').classList.add('hiddenStyle');
            compareItemsCountBlock.style.display = 'none';
        }
    }

    initSearchBlockLinksPositions();
});

function menuVisibility(tabName) {
    let headerMenu = $$('.header-bottom-menu');
    if (headerMenu.length != 0 && tabName.length != 0) {
        headerMenu.forEach(function (menu) {
            let menuName = menu.getAttribute('data-menu');
            if (menuName === tabName) {
                menu.classList.remove('h-bottom-hidden');
            } else {
                menu.classList.add('h-bottom-hidden');
            }
        });
    } else {
        console.log('Error header menu.');
    }
}

let headerTabs = $$('.header-top-block .ht-item');
headerTabs.forEach(function (tab) {
    tab.addEventListener('click', function () {
        let tabTitle = tab.querySelector('.ht-item-title');
        headerTabs.forEach(function (hTab) {
            hTab.querySelector('.ht-item-title').classList.remove('ht-active');
        });

        tabTitle.classList.add('ht-active');

        let targetTab = tab.getAttribute('data-target');
        menuVisibility(targetTab);
    })
})

document.querySelector('.search-block > [type=submit]').addEventListener('click', () => {
    let yandexSearchButton = document.querySelector('.ya-site-form__submit');

    if (yandexSearchButton) yandexSearchButton.click();
})

// $$('#headerMenu a').forEach(function(link){
//     link.addEventListener('click', g('menu'));
// });


let formListenerInterval = setInterval(function () {
    if (document.querySelector('.ya-site-form form')) {
        return;
    }
    
    const timeout = 500;

    setTimeout(function () {
        let searchBlock = document.querySelector('.search-block.with-links');

        if (!searchBlock) {
            return;
        }

        let searchInput = searchBlock.querySelector('.ya-site-form__input-text');
        let searchClearButton = searchBlock.querySelector('.search-block__clear');
        let searchSubmitButton = searchBlock.querySelector('.search-block > [type=submit]')

        searchInput.addEventListener('input', () => {
            if (searchInput.value) {
                searchClearButton.classList.remove('hiddenStyle');
                searchSubmitButton.classList.remove('hiddenStyle');
            } else {
                searchClearButton.classList.add('hiddenStyle');
                searchSubmitButton.classList.add('hiddenStyle');
            }
        })

        searchClearButton.addEventListener('click', () => {
            searchInput.value = '';
            searchClearButton.classList.add('hiddenStyle');
            searchSubmitButton.classList.add('hiddenStyle');
        })
    }, timeout)

    clearInterval(formListenerInterval);
}, 300);

function initYandexSearch(w, d, c, callback) {
    var s = d.createElement('script'), h = d.getElementsByTagName('script')[0], e = d.documentElement;
    if ((' ' + e.className + ' ').indexOf(' ya-page_js_yes ') === -1) {
        e.className += ' ya-page_js_yes';
    }
    s.type = 'text/javascript';
    s.async = true;
    s.charset = 'utf-8';
    s.src = (d.location.protocol === 'https:' ? 'https:' : 'http:') + '//site.yandex.net/v2.0/js/all.js';
    h.parentNode.insertBefore(s, h);
    (w[c] || (w[c] = [])).push(function () {
        Ya.Site.Form.init();
    });
    (w[c] || (w[c] = [])).push(function () {
        callback();
    });
}

function showSearchBlock() {
    let searchBlock = $$('.search-block')[0];
    let closeBtn = $$('.search-close-btn')[0];
    let iconSearch = $$('.icon-search')[0];

    let searchBlockWithLinks = document.querySelector('.search-block.with-links');

    let searchInput = document.querySelector('.ya-site-form__input-text');
    if (searchBlock.classList.contains('open-search-block')) {
        searchBlock.closest('.header').classList.remove('search')
        searchBlock.classList.remove('open-search-block');
        closeBtn.style.display = 'none';
        iconSearch.style.display = 'inline-block';

        if (searchBlockWithLinks) {
            document.querySelector('body').classList.remove('search-fixed-body');
            searchInput.value = '';
            searchInput.dispatchEvent(new Event('input'));
            searchBlockWithLinks.querySelector('.search-block-links .container').classList.remove('animate');
            document.querySelector('body').style.paddingRight = '0';
            document.querySelector('body').style.removeProperty('padding-right');
        }

    } else {
        searchBlock.closest('.header').classList.add('search')
        searchBlock.classList.add('open-search-block');
        closeBtn.style.display = 'block';
        iconSearch.style.display = 'none';
        focusInputAfterLoad();

        if (searchBlockWithLinks) {
            if (document.body.scrollHeight > window.innerHeight) {
                let scrollbarWidth = window.innerWidth - document.documentElement.clientWidth
                document.querySelector('body').style.paddingRight = scrollbarWidth + 'px';
            }

            document.querySelector('body').classList.add('search-fixed-body')
            searchBlockWithLinks.querySelector('.search-block-links .container').classList.add('animate');
        }
    }
}

function focusInputAfterLoad() {
    let searchInput = document.querySelector('.ya-site-form__input-text')

    if (!searchInput) {
        let inputLoadListener = setInterval(function () {
            let searchInput = document.querySelector('.ya-site-form__input-text')

            if (searchInput) {
                searchInput.focus();
                clearInterval(inputLoadListener);
            }
        }, 200)

        return;
    }

    searchInput.focus();
}

function initSearchBlockLinksPositions() {
    let searchBlockLinks = document.querySelector('.search-block-links');
    let headerTopBlock = document.querySelector('.header-top-block');

    if (!searchBlockLinks || !headerTopBlock) return;

    searchBlockLinks.style.top = headerTopBlock.offsetHeight + headerTopBlock.offsetTop - 2 + 'px';
}

$$('.footer-social-link').forEach((el) => {
    el.addEventListener('click', () => {
        let link = el.getAttribute('data-href');
        window.open(link, '_blank').focus();
    });
});
function showModalBlock() {
    let modals = document.querySelectorAll('[data-modal]');
    modals.forEach(function (trigger) {
        trigger.addEventListener('click', function (event) {
            event.preventDefault();
            let modal = document.getElementById(trigger.dataset.modal);
            modal.classList.add('open');
            let exits = document.querySelectorAll('.modal-exit');
            exits.forEach(function (exit) {
                exit.addEventListener('click', function (event) {
                    event.preventDefault();
                    modal.classList.remove('open');
                });
            });
        });
    });
}

function openedModalBlock() {
    document.querySelectorAll('.modal-block.open').forEach(modal => {
        let exits = document.querySelectorAll('.modal-exit');
        exits.forEach(function (exit) {
            exit.addEventListener('click', function (event) {
                event.preventDefault();
                modal.classList.remove('open');
            });
        });
    })
}

document.addEventListener('DOMContentLoaded', showModalBlock);
document.addEventListener('DOMContentLoaded', openedModalBlock);
if($$('#backCallForm').length != 0 && $$('#backCallForm')[0].getElementsByClassName('btn').length != 0) {
    $$('#backCallForm')[0].getElementsByClassName('btn')[0].addEventListener('click',function (e) {

        if (!$$('#backCallForm')[0].checkValidity()) {
            alert('Неверный формат номера телефона');
            return false;
        }

        e.preventDefault();
        var token = document.getElementsByName('csrf-token')[0].attributes[1].nodeValue;
        var name = $$('#cName')[0].value;
        var phone = $$('#cPhone')[0].value;
        var description = $$('#cDescription')[0].value;
        var currentPageUrl = window.location.pathname;

        // ^\+?[0-9 ()-]*


        // var email = $$('#c_email')[0].value;
        if (!phone) {
            alert('Вы не заполнили все поля');
            return false;
        }
        // if (!$$('#confirm-checkbox')[0].checked) {
        //     alert('Вы не подтвердили согласие на обработку персональных данных');
        //     return false;
        // }
        grecaptcha.confirmed(function () {
            let data = {
                'g-recaptcha-response': grecaptcha.getResponse(),
                _token: token,
                name: name,
                phone: phone,
                description: description,
                currentPageUrl: currentPageUrl
            };
            fetch('/forms/call_me', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                    'X-CSRF-TOKEN': token
                },
                body: JSON.stringify(data)
            }).then((res) => {
                return res.json()
                    .then((data) => {
                        grecaptcha.reset();
                        $$('#modal_call_back')[0].classList.remove('open');
                        if (data.status === 'success' && data.message != null) {
                            let modalNotify = document.getElementById('modal-notify-success');
                            modalNotify.querySelectorAll('.notify-message')[0].innerHTML = data.message;
                            modalNotify.classList.toggle('open')
                            $$('#backCallForm')[0].reset();
                        } else if (data.status === 'error' && data.message != null) {
                            let modalNotify = document.getElementById('modal-notify-error');
                            modalNotify.querySelectorAll('.notify-message')[0].innerHTML = data.message;
                            modalNotify.classList.toggle('open')
                            $$('#backCallForm')[0].reset();
                        }
                    }).catch((err) => {
                        grecaptcha.reset();
                        console.log(err);
                        $$('#modal_call_back')[0].classList.remove('open');
                        let modalNotify = document.getElementById('modal-notify-error');
                        modalNotify.querySelectorAll('.notify-message')[0].innerHTML = "Что-то пошло не так. <br> Пожалуйста, попробуйте снова.";
                        modalNotify.classList.toggle('open');
                    })
            });
        })
    },false);
}

document.querySelectorAll('.modal-exit').forEach(function (exit) {
    exit.addEventListener('click', function (event) {
        event.preventDefault();
        var modal = exit.closest('.modal-block');
        modal.classList.remove('open');
    });
});let toTopBtn = $$('#toTop')[0];
if (toTopBtn !== undefined) {
    window.addEventListener('scroll', () => {
        window.scrollY > 100 ? toTopBtn.style.display = 'inline-block' : toTopBtn.style.display = 'none';
    });

    toTopBtn.addEventListener('click', () => {
        console.log('click');
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
}
var firstCol = $$('.first-col');
var secondCol = $$('.second-col');

for(let i = 0; i<firstCol.length; i++){
    firstCol[i].addEventListener('mouseenter', function(){
        firstCol[i].style.background = "#D3E4FD";
        secondCol[i].style.background = "#F3F8FF";
    });
    secondCol[i].addEventListener('mouseenter', function(){
        firstCol[i].style.background = "#D3E4FD";
        secondCol[i].style.background = "#F3F8FF";
    });
    firstCol[i].addEventListener('mouseout', function(){
        firstCol[i].style.background = "#E1EDFF";
        secondCol[i].style.background = "#fff";
    });
    secondCol[i].addEventListener('mouseout', function(){
        firstCol[i].style.background = "#E1EDFF";
        secondCol[i].style.background = "#fff";
    });
}

// скрытие таблицы
let addTableWrap = (selector) => {
    selector = document.querySelectorAll('.content table');
    if ((selector).length > 0) {
        (selector).forEach((table) => {
            if (table.classList.contains('total_cards_table_js')) {
                return;
            }
            let tr = table.querySelectorAll('tr');

            let wrapper = document.createElement('div');
            wrapper.className = "table-scroll";
            table.parentNode.insertBefore(wrapper, table);
            wrapper.appendChild(table);

            if(tr.length > 5){
                table.closest('.table-scroll').classList.add('table-toggle-wrap');
                let button = document.createElement('span');
                button.className = 'table-toggle-btn down';
                button.textContent = 'Показать всё';
                table.after(button);
                let i = 0;
                table.querySelectorAll('tr').forEach((tr) => {
                    i++;
                    if (i>5) tr.className = 'hide';
                });
            } else {
                table.closest('.table-scroll').classList.add('without-toggle');
            }
        });
    }
}

if ($$('.content').length > 1) {
    addTableWrap('.content table');

    $$('.table-toggle-btn').forEach((button) => {
        button.addEventListener('click', () => {
            if (button.classList.contains('down')) {
                button.classList.add('up');
                button.classList.remove('down');
                button.textContent = 'Скрыть';
                button.previousSibling.querySelectorAll('tr.hide').forEach((tr) => {
                    tr.classList.add('show');
                    tr.classList.remove('hide');
                });
                if(button.closest('.panel') != null){
                    button.closest('.panel').style.maxHeight = 'fit-content';
                }
            } else {
                button.classList.add('down');
                button.classList.remove('up');
                button.textContent = 'Показать всё';
                button.previousSibling.querySelectorAll('tr.show').forEach((tr) => {
                    tr.classList.add('hide');
                    tr.classList.remove('show');
                });
            }
        });
    });
}
let citiesForCategory = {};

if($$('.modal-list-container a').length != 0) {
    $$('.modal-list-container a').forEach(item => {
        item.addEventListener('click', function () {
            document.cookie = "GEO_CITY=" + this.dataset.city + "; path=/;";
        });
    });

    $$('.modal-list-container .modal-list__el > span').forEach(item => {
        item.addEventListener('click', function () {
            document.cookie = "GEO_CITY=" + this.dataset.city + "; path=/;";
            document.querySelector('#modal-city').classList.remove('open');
        });
    });
}


if($$('.geo_cities_check').length != 0) {
    $$('.geo_cities_check')[0].addEventListener('click',function (e) {
        var elem = e.target;
        document.cookie = "GEO_CITY=" + elem.dataset.value + "; path=/;";
        var pageUrl = document.URL;
        var cityUrl = elem.dataset['url'];
        elem.style.display = 'none';

        if (cityUrl === undefined) {
            return false;
        }

        let data = {
            '_token': document.getElementsByName('csrf-token')[0].attributes[1].nodeValue,
            'action': 'before'
        };

        fetch('/actions/online-proverka-na-koronavirus', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json;charset=utf-8'
            },
            body: JSON.stringify(data)
        }).then((res) => {
        }).catch((err) => {
            console.log(err);
        });

        var re = /\/$/;
        pageUrl = pageUrl.replace(re,'');
        location.href = '/' + cityUrl;
    })
}

if($$('[data-modal="modal-city"]').length != 0) {
    $$('[data-modal="modal-city"]').forEach(item => {
        item.addEventListener('click', function () {
            loadCitiesInStorageByPage();
        })
    });
}

let pageCitiesLoaded = false;
function loadCitiesInStorageByPage() {
    if (window.location.pathname.startsWith('/zalogi')) {
        let params = {};

        if (document.querySelector('#zalogi-geo-modal')) {
            params = {
                breadcrumb: document.querySelector('#zalogi-geo-modal').dataset.breadcrumb
            }
        }
        
        loadCitiesInStorage('/actions/zalogi_cities_new', 'getCitiesZalogi', !pageCitiesLoaded, params);
        pageCitiesLoaded = true;

        return 'getCitiesZalogi';
    }

    loadCitiesInStorage('/actions/zaimy/geo/get_all_cities', 'geoCities');

    return 'geoCities';
}

function loadCitiesInStorage(actionUrl, storageName, update = false, params = {}) {
    if(localStorage.getItem(storageName) == null || localStorage.getItem(storageName) == '' || localStorage.getItem(storageName) == '{}' || update) {
        fetch(actionUrl + '?' + new URLSearchParams(params), {
            method: 'GET',
        }).then((res) => {
            return res.json().then((data) => {
                var geoCities = {};
                data.forEach(function(items) {
                    for (var key in items) {
                        // skip loop if the property is from prototype
                        if (!items.hasOwnProperty(key)) continue;
                        var value = items[key];
                        value.forEach((item) => {
                            geoCities[item[1]] = item;
                        })
                    }
                });
                localStorage.setItem(storageName,JSON.stringify(geoCities));

                loadCitiesForCategory();
            }).catch((err) => {
                console.log(err);
            });
        })
    } else {
        loadCitiesForCategory();
    }

    return false;
}

function loadCitiesForCategory() {
    if (Object.keys(citiesForCategory).length > 0) return;

    if (window.location.pathname.startsWith('/zalogi')) {
        console.log(JSON.parse(localStorage.getItem('getCitiesZalogi')));
        citiesForCategory = JSON.parse(localStorage.getItem('getCitiesZalogi'));
        setCitiesInModal();
        return;
    }

    let pageType = 'listing';
    let categoryId = window.CATEGORY_ID;

    if (window.location.pathname.includes('business/franchise')) {
        pageType = 'franchise';
    } else if (window.location.pathname.includes('currency')) {
        pageType = 'currency';
        categoryId = window.CURRENCY_CATEGORY_ID;
    }

    let data = {
        pageType: pageType,
        category: categoryId
    };
    let token = document.getElementsByName('csrf-token')[0].attributes[1].nodeValue;

    fetch('/actions/geo/get_cities', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'X-CSRF-TOKEN': token
        },
        body: JSON.stringify(data)
    }).then((res) => {
        return res.json().then(value => {

            value.forEach(item => {
                citiesForCategory[item[1]] = item;
            })
            setCitiesInModal();
        });
    }).catch((err) => {
        console.log(err);
    });

}

if($$('#searchCity').length != 0) {
    $$('#searchCity')[0].addEventListener('keyup', function (e) {
        let storageNameByPage = loadCitiesInStorageByPage();

        searchCityInputEvent(e, storageNameByPage);
    },false)
}

function searchCityInputEvent(e, cityStorageName) {
    var elem = e.target;
    var modalBlock = elem.closest('.modal-block');

    var resetSearchHint = modalBlock.querySelector('.reset-search-hint');
    var citySearchIcon = modalBlock.querySelector('.city-search-icon');
    var modalListContainer = modalBlock.querySelector('.modal-list-container');
    if(modalBlock.querySelector('.modal-searched-data-block')) {
        var modalSearchedDataBlock = modalBlock.querySelector('.modal-searched-data-block');
    }
    var searchHint = elem.value;
    if(searchHint.length != 0 && resetSearchHint) {
        citySearchIcon.classList.add('display_none');
        resetSearchHint.classList.remove('display_none');
        resetSearchHint.addEventListener('click',function (){
            elem.value = '';
            elem.classList.remove('focusedInp');
            modalListContainer.style.display = 'flex';
            if(modalSearchedDataBlock != undefined) {
                modalSearchedDataBlock.style.display = 'none';
            }
            citySearchIcon.classList.remove('display_none');
            resetSearchHint.classList.add('display_none');
        })
    }
    if(searchHint && modalSearchedDataBlock) {
        var matchesWithSearch = '';
        var cities = {
            ...JSON.parse(localStorage.getItem(cityStorageName)),
            ...citiesForCategory
        };

        // var counter = 0;
        // var maxElements = 5;

        if(cities != '' || cities != null) {
            for (var key in cities) {
                // skip loop if the property is from prototype
                if (!cities.hasOwnProperty(key)) continue;
                var city = cities[key];
                key = key.trim();
                searchHint = searchHint.trim();
                if(key.toLowerCase().indexOf(searchHint.toLowerCase()) == 0) {
                    var regexp = new RegExp( `(^${searchHint})(.*)`, 'gi' );
                    var matchesCity = [...key.matchAll(regexp)];
                    if(matchesCity.length != 0) {
                        matchesCity = matchesCity[0];

                        if (window.CATEGORY_ID == 1 || citiesForCategory[city[1]]) {
                            matchesWithSearch += `<div class="modal-list__el"><a href="${city[0]}" data-name="${city[1]}" data-city="${city[2]}"><span>${matchesCity[1]}</span><span class="not-matches-with-search">${matchesCity[2]}</span></a></div>`;
                        } else {
                            matchesWithSearch += `<div class="modal-list__el"><span data-name="${city[1]}" data-city="${city[2]}"><span>${matchesCity[1]}</span><span class="not-matches-with-search">${matchesCity[2]}</span></span></div>`;
                        }

                        // counter++;
                        // if (counter == maxElements) break;
                    }
                }
            }
            if(matchesWithSearch != '') {
                modalSearchedDataBlock.innerHTML = matchesWithSearch;
                modalListContainer.style.display = 'none';
                modalSearchedDataBlock.style.display = 'flex';
                elem.classList.add('focusedInp');

                updateEvents();
            }
        }
    } else {
        elem.classList.remove('focusedInp');
        if (resetSearchHint) {
            resetSearchHint.classList.add('display_none');
        }
        if (citySearchIcon) {
            citySearchIcon.classList.remove('display_none');
        }
        modalSearchedDataBlock.style.display = 'none';
        modalListContainer.style.display = 'flex';
    }
}

// Regoin
var YMapsLocal = localStorage.getItem('YMaps');
if (YMapsLocal == null) {
    var script = document.createElement("script");
    script.src = 'https://api-maps.yandex.ru/1.1/index.xml';
    document.head.appendChild(script);
    script.onload = function () {
        localStorage.setItem('YMaps', JSON.stringify(YMaps.location));
        window.city = YMaps.location.city;
    }
} else {
    YMapsLocal = JSON.parse(YMapsLocal);
    window.city = YMapsLocal.city;
}

// MetrikaID
var MetrikaID = localStorage.getItem('MetrikaID');
if (MetrikaID == null) {
    document.addEventListener("DOMContentLoaded", function(event) {
        if (yaCounter38176370 != null) {
            MetrikaID = yaCounter38176370.getClientID();
            window.clientID = MetrikaID;
            localStorage.setItem('MetrikaID', MetrikaID);
        }
    });
} else {
    window.clientID = MetrikaID;
}
document.addEventListener('DOMContentLoaded', function(){
    if (YMapsLocal != null && YMapsLocal.location) {
        window.city = YMapsLocal.location.city;   // Достанем в input регион (область)
    }
    if (window.load_city_from_yandex) {
        fetch("/actions/zaimy/geo/find_city_by_name?name="+window.city, {
            method: 'GET',
        }).then((res) => {
            return res.json().then((data) => {
                if($$('.your-geo-location').length != 0 && $$('.geo_cities_check').length != 0) {
                    var currentCityBlock = $$('.your-geo-location')[0].getElementsByTagName('b')[0];
                    var checkGeoCityBlock = $$('.geo_cities_check')[0];
                    if (data.url !== undefined) {
                        currentCityBlock.innerText = window.city;
                        checkGeoCityBlock.dataset['url'] =  data.url;
                        checkGeoCityBlock.dataset['name'] = data.imenitelny;
                        checkGeoCityBlock.dataset['value'] = data.url;
                    } else {
                        currentCityBlock.innerText = 'Москва';
                        checkGeoCityBlock.dataset['url'] = 'moskva';
                        checkGeoCityBlock.dataset['name'] = 'Москва';
                        checkGeoCityBlock.dataset['value'] = 'moskva';
                    }
                }
            }).catch((err) => {
                console.log(err);
            });
        })
    }
})

function updateEvents() {
    $$('.modal-list-container a').forEach(item => {
        item.addEventListener('click', function () {
            document.cookie = "GEO_CITY=" + this.dataset.city + "; path=/;";
        });
    });

    $$('.modal-list-container .modal-list__el > span').forEach(item => {
        item.addEventListener('click', function () {
            document.cookie = "GEO_CITY=" + this.dataset.city + "; path=/;";
            document.querySelector('.choose-city').innerHTML = this.innerHTML;
            document.querySelector('#modal-city').classList.remove('open');
        });
    });

    $$('.modal-searched-data-block a').forEach(item => {
        item.addEventListener('click', function () {
            document.cookie = "GEO_CITY=" + this.dataset.city + "; path=/;";
        });
    });

    $$('.modal-searched-data-block .modal-list__el > span').forEach(item => {
        item.addEventListener('click', function () {
            document.cookie = "GEO_CITY=" + this.dataset.city + "; path=/;";
            document.querySelector('.choose-city').innerHTML = this.dataset.name;
            document.querySelector('#modal-city').classList.remove('open');
        });
    });
}

function setCitiesInModal() {
    let modalListElements = document.querySelectorAll('.modal-list-container .modal-list__el > *');

    if (!modalListElements.length) return;

    let cities = null;
    if (window.CATEGORY_ID == 1) {
        cities = JSON.parse(localStorage.getItem('geoCities'));
    }

    modalListElements.forEach(modalListElement => {
        let city = citiesForCategory[modalListElement.innerHTML];

        if (cities && !city) {
            city = cities[modalListElement.innerHTML];
        }

        if (!city) return;

        modalListElement.parentElement.innerHTML = `
            <a href="${city[0]}" data-city="${city[2]}">${city[1]}</a>
        `;
    });

    updateEvents();
}

document.addEventListener("DOMContentLoaded", () => {
    let cookiesBlockVisibility = localStorage.getItem('cookies-hide-block');
    let cookiesBlock = $$('.cookies-info');
    if(cookiesBlock.length >0) {
        cookiesBlock = cookiesBlock[0];
        if(cookiesBlockVisibility != undefined && cookiesBlockVisibility == 'true') {
            cookiesBlock.style.display = 'none';
        } else {
            cookiesBlock.style.display = 'block';
            cookiesBlock.getElementsByClassName('btn')[0].addEventListener('click',function (){
                cookiesBlock.style.display = 'none';
                localStorage.setItem('cookies-hide-block',true);
            })
        }
    }
});