// function moveSidebarOnFixedBlockShowing() {
//     let fixedBlock = document.querySelector('.comp-fixed-block');
//     let sidebar = document.querySelector('.sidebar');
//
//     if (!fixedBlock || !sidebar) return;
//
//     let lastState = true;
//
//     window.addEventListener('scroll', function () {
//         if (lastState === fixedBlock.classList.contains('comp-fixed')) return;
//
//         lastState = !lastState;
//
//         if (fixedBlock.classList.contains('comp-fixed')) {
//             sidebar.style.paddingTop = (fixedBlock.clientHeight + 16) + 'px';
//             return;
//         }
//
//         sidebar.style.paddingTop = '0px';
//
//     }, 200);
// }

//moveSidebarOnFixedBlockShowing();
function initLeadWithReviewForm() {
    const textBlock = document.querySelector('.lead-with-review-form-text');

    if (textBlock.scrollHeight > textBlock.clientHeight) {
        document.querySelector('.lead-read-more').classList.remove('hidden');
    }
}

initLeadWithReviewForm();
function initModalAddBankReview() {
    let mainBlock = document.querySelector('#modal_bank_review');

    if (!mainBlock) return;

    initRatingWrap();
    initModalAddBankReviewSelects(mainBlock);

    let form = mainBlock.querySelector('form');

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

        let name = form.querySelector('#name').value;
        let id = form.querySelector('#reviewUserId').value;
        let rating = document.querySelectorAll('.rating-wrap .select').length;

        if (!rating) {
            alert('Вы не указали рейтинг');
            return false;
        }

        let review = form.querySelector('#content').value;

        if(name == '' || name == undefined) {
            alert('Вы не указали имя');
            return false;
        }

        if(review == '' || review == undefined) {
            alert('Вы не заполнили текст отзыва');
            return false;
        }

        let bankCat = document.querySelector('.bank-categroy-select')?.dataset.value;
        let bankProduct = document.querySelector('.bank-product-select')?.dataset.value;
        let bank = document.querySelector('#reviewBank').value;

        let review_data = {
            '_token': document.getElementsByName('csrf-token')[0].attributes[1].nodeValue,
            'rating':rating,
            'name': name,
            'uid': id,
            'review': review,
            'company_id': bank,
            'product_id': bankProduct,
            'bank_category_page_id': bankCat
        };

        grecaptcha.confirmed(function () {
            review_data['g-recaptcha-response'] = grecaptcha.getResponse();

            fetch('/actions/banks/add-review', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                body: JSON.stringify(review_data)
            }).then((res) => {
                grecaptcha.reset();
                return res.text().then((value) => {
                    form.closest('.modal-block').classList.remove('open');

                    let modalAfterReviewAdd = document.querySelector('#modal_answer_after_adding_review');

                    if(modalAfterReviewAdd) {
                        document.querySelector('#modal_answer_after_adding_review_btn').click();
                        modalAfterReviewAdd.querySelector('.answeredReview').innerHTML = value;
                    }

                    form.querySelectorAll('input, textarea').forEach(tag => {
                        if (!tag.readOnly) {
                            tag.value = "";
                        }
                    });

                    grecaptcha.reset();
                }).catch((err) => {
                    console.log(err);
                    grecaptcha.reset();
                });
            });
        })
    })
}

function initRatingWrap() {
    let wrap = document.querySelector('#modal_bank_review .rating-wrap');

    if (!wrap) return;

    let stars = wrap.querySelectorAll('.rating-star');

    stars.forEach(star => {
        star.addEventListener('mouseenter', () => {
            stars.forEach(hoveredStar => {
                if (hoveredStar.dataset.rate > star.dataset.rate) {
                    hoveredStar.classList.remove('hover');
                    return;
                }
                hoveredStar.classList.add('hover');
            })
        })

        star.addEventListener('click', () => {
            stars.forEach(hoveredStar => {
                if (hoveredStar.dataset.rate > star.dataset.rate) {
                    hoveredStar.classList.remove('select');
                    return;
                }
                hoveredStar.classList.add('select');
            })
        })
    });

    wrap.addEventListener('mouseleave', () => {
        stars.forEach(star => {
            star.classList.remove('hover');
        })
    })
}

function initModalAddBankReviewSelects(mainBlock) {
    const bankCategorySelect = mainBlock.querySelector('.bank-categroy-select');
    const bankProductSelect = mainBlock.querySelector('.bank-product-select');

    if (!bankCategorySelect || !bankProductSelect) {
        mainBlock.querySelectorAll('.select-inputs').forEach(selectBlock => {
            initSelectNew(selectBlock, (selectItem) => {
                selectBlock.dataset.value = selectItem.dataset.value;
            });
        })

        return;
    }

    initSelectNew(bankCategorySelect, (selectItem) => {
        bankCategorySelect.dataset.value = selectItem.dataset.value;

        bankProductSelect.dataset.value = '';
        bankProductSelect.classList.remove('selected');

        bankProductSelect.querySelectorAll('.bank-review-form-select-item').forEach(item=> {
            item.classList.remove('r-active')

            if (item.dataset.cat != selectItem.dataset.value) {
                item.style.display = 'none';
            } else {
                item.style.display = 'flex';
            }
        })
    });

    bankCategorySelect.querySelector('.bank-review-form-select-item.active')?.click();

    initSelectNew(bankProductSelect, (selectItem) => {
        bankProductSelect.dataset.value = selectItem.dataset.value;

        if (bankCategorySelect.dataset.value || !selectItem.dataset.value) return;

        bankCategorySelect.querySelector("[data-value='" + selectItem.dataset.cat + "']")?.click();

        selectItem.click();
    });
}

document.addEventListener("DOMContentLoaded", function(event) {
    initModalAddBankReview();
});let loadReviewsMoreBtn = $$(".loadMoreReview");

let page_number = 1;
function loadItems(sortItems = false) {
    let token = document.getElementsByName('csrf-token')[0].attributes[1].nodeValue;
    let organisation_id = $$('.reviewsBlock')[0].dataset['company'];
    page_number ++;
    if (sortItems) {
        page_number = 1;
    }
    let sort_type = $$('.reviews-sort .select-options .r-active')[0].dataset['sort'];

    let is_cashback_category = false;
    if (window.IS_CASHBACK_CATEGORY !== undefined) {
        is_cashback_category = window.IS_CASHBACK_CATEGORY;
    }

        (async function(){
        let data = {
            _token: token,
            organisation_id: organisation_id,
            organisation_type: window.ORGANIZATION_TYPE,
            organisation_category_id: window.BANK_CATEGORY_ID,
            organisation_product_id: window.BANK_PRODUCT_ID,
            is_cashback_category: is_cashback_category,
            page_number:page_number,
            sort_type:sort_type
        };
        let response = await fetch('/actions/load_sorted_reviews', {
            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) => {
                    if($$('.reviewsBlock').length != 0){
                        if(sortItems) {
                            $$('.reviewsBlock')[0].innerHTML = data.reviewsHtml;
                        } else {
                            $$('.reviewsBlock')[0].innerHTML += data.reviewsHtml;
                        }
                        allForMovingForm();
                        showClosedComments();

                        let reviews_all_count = $$('.main-reviews-wrap-btn-block')[0].dataset['reviews'];
                        if(page_number * 10 >= reviews_all_count) {
                            $$('.loadMoreReview')[0].classList.add('display_none');
                        } else {
                            $$('.loadMoreReview')[0].classList.remove('display_none');
                        }

                    }
                }).catch((err) => {
                    console.log(err);
                })
        });
        return false;
    })()

}
if(loadReviewsMoreBtn.length != 0) {
    loadReviewsMoreBtn[0].addEventListener('click',function (e) {
        loadItems();
    },false)
}


//Перемищение формы по странице

let answerForm = $$('#review-form')[0].cloneNode(true);
answerForm.classList.add('review-answer-form');
$$('#review-f')[0].parentNode.append(answerForm);
answerForm.style.display = 'none';
document.getElementsByClassName('cancel-btn')[0].addEventListener('click',function () {
    clearForm(this);
    moveFormBack();
},false);

function moveFormBack() {
    answerForm.style.display = 'none';
    $$('#review-f')[0].parentNode.append(answerForm);
}

function showClosedComments() {
    let closedComments = $$('.complainSuccessBlock');

    closedComments.forEach(item => {
        item.addEventListener('click', function () {
            item.classList.remove('complainSuccessBlock');
            item.querySelector('.replace-block').style.display = 'block';
        })
    })
}

function allForMovingForm(){

    let moveBtnBlock = $$('.review-btn-wrap-block');
    let mainFormBlock = $$('#review-f')[0];
    let formBlock = $$('.review-answer-form')[0];

    function moveBtnClick(moveBtnBlock) {
        let reviewWrap = moveBtnBlock.closest('.review-wrap');

        let hasReviewForm = reviewWrap.querySelector('.review-form') != null;
        let isShowForm = formBlock.style.display != 'none';
        let isNotCommentReply = moveBtnBlock.closest('.thread-answer-btn') == null;

        if (hasReviewForm && isShowForm && isNotCommentReply) {
            reviewWrap.querySelector('.replace-block').style.display = 'none';
            formBlock.style.display = 'none';
            if($$('.clicked-review-btn').length != 0) {
                $$('.clicked-review-btn')[0].classList.remove('clicked-review-btn');
            }
            return;
        } else {
            reviewWrap.querySelector('.replace-block').style.display = 'block';
            formBlock.style.display = 'block';
        }

        if(!moveBtnBlock.classList.contains('review-btn-wrap-block')) {
            moveBtnBlock = moveBtnBlock.closest('.review-btn-wrap-block');

            if($$('.clicked-review-btn').length != 0) {
                $$('.clicked-review-btn')[0].classList.remove('clicked-review-btn');
            } else{
                moveBtnBlock.classList.add('clicked-review-btn');
            }
        }

        var reviewForm = $$('#form-1');
        var answeredReviewBlock = formBlock.getElementsByClassName('answeredReview');
        if(!moveBtnBlock.classList.contains('answerAdded')) {
            reviewForm[0].style.display = 'flex';
            if(answeredReviewBlock.length != 0) {
                answeredReviewBlock[0].style.display = 'none';
            }
        } else {
            reviewForm[0].style.display = 'none';
            if(answeredReviewBlock.length != 0) {
                answeredReviewBlock[0].style.display = 'block';
            }
        }
        let moveForm = moveBtnBlock.nextElementSibling;

        moveBtnBlock.nextElementSibling.style.display = 'block';

        if (moveForm != null) {
            formBlock.style.display = 'block';
            moveBtnBlock.insertAdjacentElement('afterend', formBlock);
        }
        return;
    }

    for(let i=0;i<moveBtnBlock.length;i++) {
        moveBtnBlock[i].addEventListener('click',function (e) {
            moveBtnClick(e.target);
            let openReviewFormBtn = e.target;
            if(document.getElementsByClassName('cancel-btn').length != 0) {
                document.getElementsByClassName('cancel-btn')[0].addEventListener('click',function () {
                    let answerForm = $$('#review-form')[0];
                    answerForm.style.display='none';
                    openReviewFormBtn.parentNode.classList.remove('clicked-review-btn');
                },false);
            }
        },false);
    }
}

//Скрыть решенный отзыв

let successCompleteQuestion = document.querySelectorAll('.review-wrap');
let successLabel = document.querySelectorAll('.labelOfComplainSuccess');
for (let i = 0; i < successCompleteQuestion.length; i++) {
    complainSuccessBlock  = "complainSuccessBlock";

    if(successCompleteQuestion[i].querySelectorAll('.labelOfComplainSuccess').length > 0) {
        successCompleteQuestion[i].classList.add(complainSuccessBlock);
        successCompleteQuestion[i].querySelector('.review-btn-wrap-block').classList.remove('review-btn-wrap-block');
        successCompleteQuestion[i].querySelectorAll('.reply-bottom-info').forEach(n => n.remove());
    }

}
//сортировка отзывов серверная
function reviewsSortFilter(){
    moveFormBack();
    loadItems(sortItems=true);
    allForMovingForm();
    showClosedComments();
}
// if($$('.sort.reviews-sort').length != 0) {
//     $$('.sort.reviews-sort .select-options .option').forEach(function(option) {
//         option.addEventListener('click', function() {debugger
//             reviewsSortFilter();
//         });
//     });
// }
//открыть форму комментариев для трейта

let moveReviewBtnBlock = $$('.account-review-btn-wrap-block'),
    formReviewBlock = $$('.form-1')[0],
    nextPlaceOfReviewForm = $$('.replace-block'),
    cancelReviewForm = $$('.comment-form-cancel-btn')[0];

for(let i=0;i<moveReviewBtnBlock.length;i++) {
    moveReviewBtnBlock[i].addEventListener('click',function () {
        let moveReviewForm = this.parentNode.nextElementSibling;
        if (moveReviewForm == null) {
            formReviewBlock.style.display = 'block';
            nextPlaceOfReviewForm[i].insertAdjacentElement('afterend', formReviewBlock);
        }
    });
    cancelReviewForm.addEventListener('click',function () {
        formReviewBlock.style.display = 'none';
    });
}

//скрытие сортировочного блока и кнопки

let hideSortBlock = $$(".sort");
let hideButtonBlock = $$(".main-reviews-wrap-btn-block");
window.addEventListener('change', function(){
    if(hideSortBlock.length != 0) {
        hideSortBlock[0].style.display = "flex";
    }
    if(hideButtonBlock.length != 0) {
        hideButtonBlock[0].style.display = "block";
    }
})
document.addEventListener("DOMContentLoaded", function(event) {
    allForMovingForm();
    console.log($$('.main-reviews-wrap-btn-block')[0].dataset['reviews']);
    if($$('.main-reviews-wrap-btn-block')[0].dataset['reviews'] < 10) {
        $$('.loadMoreReview')[0].classList.add('display_none');
    }
});


document.querySelectorAll('#review-form form').forEach(item => {
    item.addEventListener('submit',function (e) {
        e.preventDefault();

        let name = item.querySelectorAll('.name')[0].value;
        let id = item.querySelectorAll('.reviewUserId')[0].value;
        let review = item.querySelectorAll('.review-content')[0].value;

        if(name == '' || name == undefined) {
            alert('Вы не указали имя');
            return false;
        }

        if(review == '' || review == undefined) {
            alert('Вы не заполнили текст отзыва');
            return false;
        }
        let company = $$('.reviewCompany')[0].value;

        if(item.parentNode.closest('[data-id]')) {
            var parent = item.parentNode.closest('[data-id]').dataset['id'];
        }
        if(parent == undefined) parent = 'null';

        let review_data = {
            '_token': document.getElementsByName('csrf-token')[0].attributes[1].nodeValue,
            'rating':null,
            'name': name,
            'uid': id,
            'company_id' : company,
            'parent':parent,
            'review': review,
            'pros':null,
            'minuses':null
        };

        if ($$('#g-recaptcha-response').length > 0) {
            review_data.captcha = $$('#g-recaptcha-response')[0].value;
        }

        if (review_data.captcha == '' && $$('#g-recaptcha-response-1').length > 0) {
            review_data.captcha = $$('#g-recaptcha-response-1')[0].value;
        }

        let url = '/actions/add-review';

        let reviewType = item.querySelector('.reviewType').value;

        if (reviewType === 'bank') {
            if($$('#bank-category-id').length != 0) {
                review_data.bank_category_id = $$('#bank-category-id')[0].getAttribute('data-val')
            } else review_data.bank_category_id = 0;
            if($$('#bank-category-page-id').length != 0) {
                review_data.bank_category_page_id = $$('#bank-category-page-id')[0].value
            }
            review_data.product_id = $$('#product_id')[0].value;
            url = '/actions/banks/add-review';
        }

        grecaptcha.confirmed(function () {
            review_data['g-recaptcha-response'] = grecaptcha.getResponse();

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                body: JSON.stringify(review_data)
            }).then((res) => {
                grecaptcha.reset();
                return res.text().then((value) => {
                    if (e.target.closest('.review-wrap')) {
                        e.target.closest('#review-form').style.display = 'none';
                        e.target.closest('.block-reviews').getElementsByClassName('review-btn-wrap-block')[0].classList.add('answerAdded')
                        e.target.closest('.review-wrap').innerHTML += ('<p class="answeredReview">'+value+'</p>');
                    } else {
                        if ($$('.answeredReview').length != 0) {
                            $$('.answeredReview')[0].innerHTML = value;
                        }
                        if($$('#modal_answer_after_adding_review_btn').length != 0) {
                            $$('#modal_answer_after_adding_review_btn')[0].click();
                        }
                    }

                    this.querySelectorAll('input, textarea').forEach(tag => {
                        if (!tag.readOnly) {
                            tag.value = "";
                        }
                    });
                }).catch((err) => {
                    console.log(err);
                    grecaptcha.reset();
                });
            });
        })
    })
})

$$('#bankReviewCategorySelect .def-sel-option').forEach(function(option) {
    option.addEventListener('click', function() {
        let ID = option.getAttribute('data-val');
        if (option.getAttribute('data-type') == 'category') {
            window.BANK_CATEGORY_ID = ID;
            if (ID == 0) {
                window.BANK_CATEGORY_ID = undefined;
            }
        } else {
            window.BANK_PRODUCT_ID = ID;
            if (ID == 0) {
                window.BANK_PRODUCT_ID = undefined;
            }
        }
    });
});

function initBankReviewCategorySelect() {
    const selectBlock = document.querySelector('#bankReviewCategorySelect');

    if (!selectBlock) return;

    initSelectNew(selectBlock, (selectOption) => {
        reviewsSortFilter();
    })

    let sort = document.querySelector('.reviews-sort .select-inputs');

    if (!sort) return;

    sort.addEventListener('click', () => {
        selectBlock.classList.remove('active');
    })
}

initBankReviewCategorySelect();

// let selectedCategoryItem = document.querySelectorAll('.category-select .category-selected-item');
// let selectCategoryOptions = document.querySelectorAll('.category-select .category-sel-option');
// let indexCategoryItemForSelect = 1;
//
// selectedCategoryItem.forEach(a => {
//     a.addEventListener('click', b => {
//         let nextEl = b.target.nextElementSibling;
//         nextEl.classList.toggle('selectCategoryToggle');
//         nextEl.style.zIndex = indexCategoryItemForSelect++;
//         a.classList.toggle('selectCategoryOpen');
//     }, false)
// });
//
// selectCategoryOptions.forEach(a => {
//     a.addEventListener('click', b => {
//         b.target.parentElement.classList.remove('selectCategoryToggle');
//         let parentEl = b.target.closest('.select-block').children[0];
//         var dataVal = b.target.getAttribute('data-val');
//         console.log('ts:' , dataVal);
//         parentEl.setAttribute('data-val', dataVal);
//         parentEl.innerText = b.target.innerText;
//         parentEl.classList.remove('selectCategoryOpen');
//         let seletedCat = $$('.category-selected-item')[0].dataset.val;
//     })
// });
// document.addEventListener('click', function (e) {
//     if (!e.target.classList.contains('selectCategoryOpen')) {
//         var openedCategorySelect = document.getElementsByClassName('selectCategoryOpen');
//         if (openedCategorySelect.length != 0) {
//             openedCategorySelect[0].classList.remove('selectCategoryOpen');
//             document.querySelectorAll('.category-select .selectCategoryToggle')[0].classList.remove('selectCategoryToggle');
//         }
//     }
// }, false);

// console.log('test');
function initSelectNewForReviews(selectBlock, callbackSelected) {
    let select = selectBlock.querySelector('.select-inputs-items');
    let filtersCategory = select.parentElement;
    let selectStatus = filtersCategory.querySelector('.select-inputs-status');

    if( selectStatus !== null ) {
        let preSetSelect = Array.from(select.querySelectorAll('li'))
            .filter(li => li.innerHTML == selectStatus.innerHTML);
        preSetSelect.forEach(el => {el.classList.add('r-active')});
    }

    select.querySelectorAll('li').forEach((item, index, items) => {
        item.addEventListener('click', (e) => {
            items.forEach(item => item.classList.remove('r-active'));
            item.classList.add('r-active');
            filtersCategory.classList.add('selected');
            filtersCategory.classList.remove('active');

            if (item.dataset.onSelectedValue) {
                selectStatus.innerHTML = item.dataset.onSelectedValue;
            } else {
                selectStatus.innerHTML = item.innerHTML;
            }
            reviewsSortFilter();
        })
    })
}

let sortSelectInputs = document.querySelector('.reviews-sort .select-inputs');
if(sortSelectInputs != null) {
    initSelectNewForReviews(sortSelectInputs);
}

document.addEventListener('DOMContentLoaded', function () {
    if ($$("[data-answer='1']").length == 0 && $$("[data-type='withAnswer']").length != 0) {
        $$("[data-type='withAnswer']")[0].style.display= 'none';
    }
});

function initAmountInputs() {
    document.querySelectorAll('.amount-input-block').forEach(amountInputBlock => {
        let input = amountInputBlock.querySelector('input');

        if (amountInputBlock.querySelector('.dropdown')) {
            initInputDropdown(amountInputBlock);
        }

        if (input.dataset.mask) {
            initMaskForInputBlock(amountInputBlock);
            return;
        }

        if (input.dataset.type == 'text') {
            formattedTextInput(input);
            return;
        } else if (input.dataset.type == 'text-ru') {
            formattedTextInput(input, true);
            return;
        }

        let repeatBlock = amountInputBlock.querySelector('.amount-input-repeat');

        if (!repeatBlock) {
            return;
        }

        if (input.value) {
            input.dataset.focusOuted = true;
        } else {
            input.addEventListener('focusout', function () {
                if (!input.value) return;
                input.dataset.focusOuted = true;
                input.dispatchEvent(new Event('input'));
            });
        }

        setFormattedNumberInput(input);
        setRepeatBlock(repeatBlock, input.value);
        formattedNumberInputAction(input, repeatBlock);

        initInputRange(amountInputBlock, input);
    })
}

function formattedTextInput(input, onlyRuText = false) {
    function setTextInputValue(input, onlyRuText) {
        const engToRu = {
            'q': 'й', 'w': 'ц', 'e': 'у', 'r': 'к', 't': 'е', 'y': 'н', 'u': 'г', 'i': 'ш', 'o': 'щ', 'p': 'з',
            'a': 'ф', 's': 'ы', 'd': 'в', 'f': 'а', 'g': 'п', 'h': 'р', 'j': 'о', 'k': 'л', 'l': 'д',
            'z': 'я', 'x': 'ч', 'c': 'с', 'v': 'м', 'b': 'и', 'n': 'т', 'm': 'ь',
            'Q': 'Й', 'W': 'Ц', 'E': 'У', 'R': 'К', 'T': 'Е', 'Y': 'Н', 'U': 'Г', 'I': 'Ш', 'O': 'Щ', 'P': 'З',
            'A': 'Ф', 'S': 'Ы', 'D': 'В', 'F': 'А', 'G': 'П', 'H': 'Р', 'J': 'О', 'K': 'Л', 'L': 'Д',
            'Z': 'Я', 'X': 'Ч', 'C': 'С', 'V': 'М', 'B': 'И', 'N': 'Т', 'M': 'Ь'
        };

        let formattedInputText = input.value.replace(/[0-9]/g, '');

        if (onlyRuText) {
            formattedInputText = formattedInputText.split('').map(char => engToRu[char] || char).join('')
        }

        input.value = formattedInputText;
    }

    input.addEventListener('input', () => {
        setTextInputValue(input, onlyRuText)

        if (input.value) {
            input.closest('.amount-input-block').classList.remove('error');
        }
    });
    input.addEventListener('focus', () => {setTextInputValue(input, onlyRuText)});
    input.addEventListener('blur', () => {setTextInputValue(input, onlyRuText)});
}

function initInputRange(amountInputBlock, amountInput) {
    let inputRange = amountInputBlock.querySelector('.amount-input-range-value');

    if (!inputRange) return;

    inputRange.addEventListener('input', inputRangeEvent);
    amountInput.addEventListener('input', inputRangeEvent);

    inputRange.style.backgroundSize = (inputRange.value - inputRange.min) * 100  / (inputRange.max - inputRange.min) + '% 100%';

    function inputRangeEvent(e) {
        let target = e.target;
        let val = parseInputNumber(target.value);
        let min = inputRange.min;
        let max = inputRange.max;

        if (e.target.type === 'range') {
            amountInput.value = val;
            amountInput.dispatchEvent(new Event('input'));
        } else {
            if(val == '') {
                val = 0;
            }
            inputRange.value = val;
        }

        let backgroundSize = (+val - min) * 100 / (max - min);

        if (backgroundSize < 0) {
            backgroundSize = 0
        }

        inputRange.style.backgroundSize = backgroundSize + '% 100%';
    }
}

function formattedNumberInputAction(input, repeatBlock) {
    input.addEventListener('input', () => {
        if (!input.dataset.focusOuted) return;

        setFormattedNumberInput(input);
        setRepeatBlock(repeatBlock, input.value);
        input.closest('.amount-input-block').classList.remove('error');
    });
    input.addEventListener('focus', () => {setRepeatBlock(repeatBlock, input.value)});
    input.addEventListener('blur', () => {setRepeatBlock(repeatBlock, input.value)});

    if (input.dataset.min) {
        input.addEventListener('change', () => {
            if (parseInputNumber(input.value) >= +input.dataset.min) return;

            input.value = input.dataset.min;

            setRepeatBlock(repeatBlock, input.value)
        });
    }
}
function setFormattedNumberInput(input) {
    if (!input.value) {
        return;
    }

    input.value = getFormattedNumber(input.value, input.dataset.max, input.dataset.decimal);
}

function parseInputNumber(number) {
    return Number(number.replace(/[ +]/g, ''))
}

function getFormattedNumber(number, max = null, decimalPlaces) {
    number = number.toString().replace(/,/g, '.'); // Заменяем запятые точками

    let integerPart = number.split('.')[0].replace(/[^0-9]/g, '');
    let decimalPart = '';

    if (decimalPlaces > 0 && number.indexOf('.') !== -1) {
        decimalPart = number.split('.')[1].replace(/[^0-9]/g, '');

        decimalPart = '.' + decimalPart.substring(0, decimalPlaces);
    }

    number = Number(integerPart) + decimalPart;

    if (max && number > Number(max)) {
        return max.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ") + '+';
    }

    return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}


function setRepeatBlock(element, value) {
    let ending = element.dataset.ending.split(',');


    if (ending.length === 3) {
        if (value == 1) ending = ending[0];
        else if (value > 1 && value < 5) ending = ending[1];
        else ending = ending[2];
    } else {
        ending = ending[0];
    }

    if (value) {
        element.innerHTML = `<span class="number">${value}</span><span> ${ending}</span>`;
    } else {
        element.innerHTML = '';
    }
}

function initSelect(selectBlock, callbackSelected) {
    let select = selectBlock.querySelector('.select-filters-border');
    let filtersCategory = selectBlock.querySelector('.select-filters');

    select.querySelectorAll('li').forEach((item, index, items) => {
        item.addEventListener('click', () => {
            items.forEach(item => item.classList.remove('hiddenStyle'));
            item.classList.add('hiddenStyle');
            filtersCategory.classList.add('selected');
            filtersCategory.classList.remove('active');

            if (item.dataset.onSelectedValue) {
                filtersCategory.querySelector('.select-status').innerHTML = item.dataset.onSelectedValue;
            } else {
                filtersCategory.querySelector('.select-status').innerHTML = item.innerHTML;
            }

            callbackSelected(item.dataset.value, item);
        })
    })
}

function initShowingNewSelect() {
    document.querySelectorAll('.select-filters-header').forEach((item, index, items) => {
        let categoryFilter = item.parentElement;
        let multiselect = categoryFilter.querySelector('.category-multi-select');
        
        let selectCount = item.querySelector('.select-count');
        let selectStatus = item.querySelector('.select-status');

        let defaultLeftValue = null;

        item.addEventListener('click', () => {
            if (categoryFilter.classList.contains('filter-blocked')) {
                return;
            }

            if (!categoryFilter.classList.contains('active')) {
                items.forEach(item => {item.parentElement.classList.remove('active')})
            }

            categoryFilter.classList.toggle('active');

            if (categoryFilter.classList.contains('active') && multiselect) {

                if (defaultLeftValue === null) {
                    defaultLeftValue = selectCount.style.left;
                }

                if (+selectCount.style.left.replace('px', '') < selectStatus.offsetWidth + 30) {
                    selectCount.style.left = selectStatus.offsetWidth + 30 + 'px';
                }
            } else if (multiselect) {
                selectCount.style.left = defaultLeftValue;
            }
        })

        document.addEventListener('click', (event) => {
            if ((event.target.closest('.select-filters') == null || !event.target.closest('.select-filters').isEqualNode(item.closest('.select-inputs'))) && document.querySelectorAll('.select-filters.active').length !== 0) {
                document.querySelectorAll('.select-filters.active .select-filters-header').forEach(itemAll => {
                    if (!itemAll.isEqualNode(item)) return;
                    // itemAll.dispatchEvent(new Event('click'));
                })
            } else if ((event.target.closest('.select-inputs') == null || !event.target.closest('.select-inputs').isEqualNode(item.closest('.select-inputs'))) && document.querySelectorAll('.select-inputs.active').length !== 0) {
                document.querySelectorAll('.select-inputs.active .select-filters-header').forEach(itemAll => {
                    if (!itemAll.isEqualNode(item)) return;
                    itemAll.dispatchEvent(new Event('click'));
                })
            }
        })
    })
}

initAmountInputs();

initShowingNewSelect();

// пример инициализации
// document.querySelectorAll('.select-block').forEach(selectBlock => {
//     initSelect(selectBlock, (value) => {
//         console.log(value);
//     })
// });
//
// document.querySelectorAll('.amount-input-filter').forEach(selectBlock => {
//     initSelect(selectBlock, (value) => {
//         console.log(value);
//     })
// });


// select quiz
function initShowingQuizSelect(elements = null) {
    if (elements === null) elements = document.querySelectorAll('.select-filters-headline');

    elements.forEach((item) => {
        let categoryFilter = item.parentElement;

        item.addEventListener('click', () => {
            if (categoryFilter.classList.contains('filter-blocked')) {
                return;
            }
            if (!categoryFilter.classList.contains('active')) {
                document.querySelectorAll('.select-filters-headline').forEach(item => {item.parentElement.classList.remove('active')})
            }
            categoryFilter.classList.toggle('active');
        })

        document.addEventListener('click', (event) => {
            if (event.target.closest('.select-inputs') == null && document.querySelectorAll('.select-inputs.active').length !== 0) {
                document.querySelectorAll('.select-inputs.active .select-filters-headline').forEach(item => {
                    item.dispatchEvent(new Event('click'));
                })
            }
        })
    })
}

initShowingQuizSelect();
function initSelectNew(selectBlock, callbackSelected) {
    let select = selectBlock.querySelector('.select-inputs-items');
    let filtersCategory = select.parentElement;
    let selectStatus = filtersCategory.querySelector('.select-inputs-status');

    if( selectStatus !== null ) {
        let preSetSelect = Array.from(select.querySelectorAll('li'))
            .filter(li => li.innerHTML == selectStatus.innerHTML);
        preSetSelect.forEach(el => {el.classList.add('r-active')});
    }

    select.querySelectorAll('li').forEach((item, index, items) => {
        item.addEventListener('click', (e) => {
            items.forEach(item => item.classList.remove('r-active'));
            item.classList.add('r-active');
            filtersCategory.classList.add('selected');
            filtersCategory.classList.remove('active');

            if (item.dataset.onSelectedValue) {
                selectStatus.innerHTML = item.dataset.onSelectedValue;
            } else {
                selectStatus.innerHTML = item.innerHTML;
            }

            if(e.target.closest('.client-sort')){
                getSort(e);//для страницы mfo клиентская сортировка
            }else{
                callbackSelected(item);
            }
        })
    })
}

function initMultiSelectNew(multiSelBlock, callBackFunc) {
    let checkboxes = multiSelBlock.querySelectorAll('input');
    let selectCount = multiSelBlock.querySelector('.select-inputs-count');
    let filterCheckboxes = multiSelBlock.querySelector('.filter-checkboxes');
    let headline = multiSelBlock.querySelector('.select-filters-headline')
    let selectInputStatus = multiSelBlock.querySelector('.select-inputs-status')

    headline.addEventListener('click', () => {
        if (!multiSelBlock.classList.contains('active')) {
            return;
        }

        moveCheckedBoxesToTop();
        filterCheckboxes.scrollTo(0, 0);
    })

    setInputStatusWidthEvent()

    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', () => {
            let checkedBoxes = Array.from(checkboxes).filter(checkbox => checkbox.checked);

            setInputStatusText(checkbox);

            if (!selectCount) {
                callBackFunc(checkedBoxes);
                return;
            }

            // if (filterCheckboxes.scrollHeight <= filterCheckboxes.clientHeight) {
            //     moveCheckedBoxesToTop();
            // }

            if (checkedBoxes.length) {
                selectCount.innerHTML = checkedBoxes.length;
                if (!selectInputStatus) selectCount.classList.add('active');
                multiSelBlock.classList.add('selected');
            } else {
                selectCount.classList.remove('active');
                selectCount.innerHTML = '';
                multiSelBlock.classList.remove('selected');
            }
            callBackFunc(checkedBoxes);

            if (selectInputStatus && !selectInputStatus.style.maxWidth) {
                selectInputStatus.style.maxWidth = selectInputStatus.clientWidth + 'px';
            }
        });
    });

    function moveCheckedBoxesToTop() {
        Array.from(multiSelBlock.querySelectorAll('.filter-checkbox'))
            .reverse()
            .filter(checkbox => checkbox.querySelector('input').checked)
            .forEach((checkbox) => {
                filterCheckboxes.prepend(checkbox);
            });
    }

    function setInputStatusText(checkbox) {
        if (!selectInputStatus) return;

        let selectedCheckboxesNames = selectInputStatus.innerHTML.split(', ').filter(item => item !== '');

        let checkboxName = checkbox.parentElement.querySelector('label').innerHTML;

        if (checkbox.checked) {
            selectedCheckboxesNames.push(checkboxName);
        } else {
            selectedCheckboxesNames = selectedCheckboxesNames.filter(item => item !== checkboxName);
        }

        selectInputStatus.innerHTML = selectedCheckboxesNames.join(', ');
    }

    function setInputStatusWidthEvent() {
        if (!selectInputStatus) return;

        window.addEventListener('resize', () => {
            if (!selectInputStatus.style.maxWidth) return;

            selectInputStatus.style.maxWidth = '';
            selectInputStatus.style.whiteSpace = 'initial';
            selectInputStatus.style.maxWidth = selectInputStatus.clientWidth + 'px';

            selectInputStatus.style.whiteSpace = '';
        })
    }
}

function formatCurrencyValue(num) {
    num = parseFloat(num);

    if (num >= 1) {
        return num.toFixed(2);
    }

    let str = num.toString();
    let match = str.match(/0\.(0*)[1-9]{2}/);

    if (match) {
        return parseFloat(match[0]);
    }

    return num.toFixed(2);
}

function addErrorToInputBlock(inputBlock, errorMessage) {
    if (!inputBlock.classList.contains('amount-input-block')) return;

    inputBlock.classList.add('error');
    let errorMessageBlock = inputBlock.querySelector('.err-msg');

    if (!errorMessageBlock) {
        errorMessageBlock = document.createElement('div');
        errorMessageBlock.classList.add('err-msg');
        inputBlock.append(errorMessageBlock);
    }

    errorMessageBlock.innerHTML = errorMessage;
}


//клиентская сортировка(start)
var getSort = ({ target }) => {
    const order = (target.dataset.type == 'up') ? -1 : 1;
    var arrForSort = [];
    var elementsBlock = $$('.offers-list')[0];
    if(window.itemsArr) {
        arrForSort = window.itemsArr;
    } else {
        arrForSort = [].slice.call(elementsBlock.children);
    }
    const collator = new Intl.Collator(['en', 'ru'], { numeric: true });
    const comparator = (order) => (a, b) => {
        var firstItem  = (a.querySelector("[data-"+target.dataset.field+"]") != null) ? a.querySelector("[data-"+target.dataset.field+"]").innerHTML : '0';
        var secondItem = (b.querySelector("[data-"+target.dataset.field+"]") != null) ? b.querySelector("[data-"+target.dataset.field+"]").innerHTML : '0';
        return order * collator.compare(
            firstItem.replace(/\s/g, ''),
            secondItem.replace(/\s/g, '')
        )
    };
    elementsBlock.innerHTML = '';
    var sortedArr = [];
    sortedArr.push(...[...arrForSort].sort(comparator(order)));
    offersListItemsArr = [...sortedArr];
    if($$('.pagination').length != 0) {
        page(1,sortedArr);
    } else {
        sortedArr.forEach((elem)=>{
            elementsBlock.append(elem);
        });
    }
};

function setMaskForInput(input, maskElem, mask, startMask = null) {
    if (!input.value) {
        input.parentElement.classList.add('focused');
        input.removeAttribute("placeholder");
    }

    let i = 0,
        val = input.value.replace(/\D/g, '');

    input.value = mask.replace(/(?!\+)./g, function(a) {
        return /[_\d]/.test(a) && i < val.length ? val.charAt(i++) : i >= val.length ? '' : a;
    });

    if (startMask && !input.value.startsWith(startMask)) {
        input.value = startMask;
    }

    let maskMainValue = input.value;

    maskElem.innerHTML = '<i>' + maskMainValue + '</i>' + mask.substring(maskMainValue.length);

    input.setSelectionRange(input.value.length,input.value.length);
}

function initMaskForInputBlock(inputBlock) {
    const maskElem = inputBlock.querySelector('.input-mask')
    const input = inputBlock.querySelector('input')

    if (!maskElem || !input) return;

    let mask = input.dataset.mask;
    let startMask = input.dataset.maskStart;

    input.addEventListener('input', () => {
        setMaskForInput(input, maskElem, mask, startMask)
        input.closest('.amount-input-block').classList.remove('error');
    });
    input.addEventListener('focus', () => {setMaskForInput(input, maskElem, mask, startMask)});
    // input.addEventListener('blur', () => {setMask(input,maskElem, mask, startMask)}); // баг на сафари

    input.addEventListener('click', function () {
        if (!input.value) {
            input.value = mask;
            maskElem.innerHTML = mask;
            if (startMask) {
                this.setSelectionRange(startMask.length,startMask.length);
            } else {
                this.setSelectionRange(0,0);
            }
            return;
        }

        this.setSelectionRange(this.value.length,this.value.length);
    })
}

function initInputDropdown(inputBlock) {
    const input = inputBlock.querySelector('.amount-input-value');

    inputBlock.querySelectorAll('.dropdown-item').forEach(dropdownItem => {
        dropdownItem.addEventListener('click', () => {
            input.value = dropdownItem.textContent.trim();
        })
    })
}

//end клиентская сортировка(end)

// document.querySelectorAll('.select-inputs').forEach(selectBlock => {
//     initSelectNew(selectBlock, (value) => {});
// });
//
// document.querySelectorAll('.select-inputs').forEach(item => {
//     initMultiSelectNew(item, function (items) {
//         console.log(items);
//     });
// });
let tabLink = document.querySelector('#tab-link');

$$('.tab-wrap').forEach((e) => {
    let tabTabs = e.querySelectorAll('.tab .tab-links');
    let tabItems = e.querySelectorAll('.tabs-items .tab-content');
    let tabContentTitles = e.querySelectorAll('.tab-content-titles div');
    for(let i =0;i<tabTabs.length;i++) {
        tabTabs[0].classList.add('on');
        tabItems[0].classList.add('on');
        if(tabContentTitles.length != 0) {
            tabContentTitles[0].classList.add('on');
        }
        tabTabs[i].onclick = () => {
            if (tabLink && tabTabs[i].dataset.tabLink) {
                tabLink.href = tabTabs[i].dataset.tabLink;
            }

            tabTabs.forEach((e)  => { e.classList.remove('on') });
            tabItems.forEach((e)  => { e.classList.remove('on') });
            tabTabs[i].classList.add('on');
            tabItems[i].classList.add('on');
            if(tabContentTitles.length != 0) {
                tabContentTitles.forEach((e)  => { e.classList.remove('on') });
                tabContentTitles[i].classList.add('on');
            }
        }
    }
});

function initMinimalCards() {
    document.querySelectorAll('.card-minimal-wrap').forEach((card) => {
        const titleColumn = card.querySelector('.card-min-col-title');

        titleColumn.querySelectorAll('a').forEach(titleColumnItem => {
            if (titleColumn.offsetWidth > 100) {
                titleColumnItem.style.maxWidth = titleColumn.offsetWidth + 'px';
            }
        })
    })
}

initMinimalCards()
document.querySelectorAll('.tab-wrap.ajax-loading').forEach((e) => {
    let tabTabs = e.querySelectorAll('.tab .tab-links');
    let tabItems = e.querySelectorAll('.tabs-items .tab-content');

    for(let i =0;i<tabTabs.length;i++) {
        let listingId = tabItems[i].dataset.listing;
        let categoryId = tabItems[i].dataset.category;
        let sectionId = tabItems[i].dataset.section;

        if (!listingId || !categoryId || !sectionId || tabItems[i].childNodes.length > 1) {
            continue;
        }

        tabTabs[i].addEventListener('click', function (e) {
            if (tabItems[i].childNodes.length > 1) {
                return;
            }

            var token = document.getElementsByName('csrf-token')[0].attributes[1].nodeValue;

            fetch('/actions/load_cards_for_best', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                    'X-CSRF-TOKEN': token
                },
                body: JSON.stringify({
                    listing_id: listingId,
                    section_type: sectionId,
                    category_id: categoryId,
                    template: 'new'
                })
            }).then((res) => {
                return res.json().then((data) => {
                    tabItems[i].innerHTML = data.code;

                    initMinimalCards();
                }).catch((err) => {
                    console.log(err);
                });
            })
        })
    }
});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();
            })
        });
    })
}


function addButtonClickHendler ()
{
    $$('button[data-href]').forEach((button) => {
        button.addEventListener('click', () => {
            let link = button.getAttribute('data-href');

            if (link) {
                window.open(link, '_blank').focus();
            }
        });
    });
}

addButtonClickHendler();

function accessibilityHandler(event, el) {
    if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault(); // предотвращаем прокрутку страницы при нажатии пробела
        console.log(event);
        console.log(el);
        el.click();
        //toggleSubmenu();
    }
}
let fullPage = document.body;

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';
}

function initImgLazyLoading() {
    document.querySelectorAll('.hl-item').forEach(hlItem => {
        hlItem.addEventListener('mouseover', () => {
            if (hlItem.dataset.inited) return;


            console.log(hlItem.querySelectorAll('.h-wrap-sub-menu img'));
            hlItem.querySelectorAll('.h-wrap-sub-menu img').forEach(img => {
                img.style.display = 'inherit';
            })

            hlItem.dataset.inited = true;
        })
    })
}

initImgLazyLoading();

$$('.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 > 0) {
    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);
            })
        }
    }
});function initTabSwitchTracker() {
    let type = null;

    if (window.PAGE_TYPE) {
        type = window.PAGE_TYPE;
    } else if (window.CATEGORY_ID) {
        type = window.CATEGORY_ID;
    }

    let typeToSwitchTitle = {
        1: 'Не забудьте оформить займ!',
        4: 'Не забудьте оформить кредит!',
        8: 'Не забудьте оформить автокредит!',
        10: 'Не забудьте оформить ипотеку!',
        6: 'Не забудьте оформить карту!',
        5: 'Не забудьте оформить кредитку!',
        2: 'Не забудьте открыть расчетный счет!',
        11: 'Не забудьте открыть вклад!',
        3: 'Не забудьте взять займ под залог!',
        13: 'Не забудьте оформите бизнес-кредит!',
        12: 'Не забудьте подключить эквайринг!',
        14: 'Не забудьте оформить карту для бизнеса!',
        'franchise': 'Не забудьте купить франшизу!',
        'insurance': 'Не забудьте оформить страховку!',
    };

    if (!typeToSwitchTitle[type]) return;

    let defaultTitle = document.title;
    let defaultFavicons = Array.from(document.querySelectorAll("link[rel~='icon']")).map(item => { return {href: item.href, element: item} });

    // if exists window.franchiseLoadParams  Не забудьте купить франшизу!
    
    document.addEventListener("visibilitychange", function() {
        if (document.hidden){
            document.title = typeToSwitchTitle[type];

            document.querySelectorAll("link[rel~='icon']").forEach(icon => {
                icon.href = icon.href.replace('/favicon', '/favicon/red');
            });
        } else {
            document.title = defaultTitle;

            defaultFavicons.forEach(item => {
                item.element.href = item.href;
            })
        }
    });
}

window.addEventListener('load', () => {
    initTabSwitchTracker();
})
