$(document).ready(function (){
    if (document.querySelector(".header").dataset['page'] === 'True' && getInfoAboutUser()[0] !== 'mobile' && getInfoAboutUser()[0] !== 'laptop'){
        resetSlider()
        renderContent()
    } else {
        let el = document.querySelector(".container_sections_buttons")
        if (el){
            replaceHrefOnOnclick()
            replace_select_language()
            resetSlider()
            autoPlaySlider()
        }
    }
})
autoplayInterval = null


function getInfoAboutUser (){
    let user_type = ''
    if (screen.width <= 800){
        user_type = 'mobile'
    } else if (screen.width > 1024) {
        user_type = 'desktop'
    } else if (screen.width >= 800 && screen.width <= 1024) {
        user_type = 'laptop'
    }
    return [user_type,screen.width]
}

function sendWidthAjax () {
    let width = getInfoAboutUser()[1]
    let data = {
        'screen_width': width
    }
    return data
}

function renderContent (el=null) {
    let data = sendWidthAjax()
    if (!el) {
        let section_button = document.querySelector(".section_btn")
        data['section_url'] = section_button.dataset['url']
    } else {
        data['section_url'] = el.dataset['url']
    }
    data['csrfmiddlewaretoken'] = $('input[name=csrfmiddlewaretoken]').val();
    let language = $('html').attr('lang');
    data['lang'] = language
    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: '/get_content_for_section/',
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        // contentType: false,
        enctype: 'json',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        success: function(data){
            document.querySelector(".content").innerHTML = data.html
            let lang = getLang()
            window.scrollTo(0, 0);
            replaceHrefOnOnclick()
            if (el){
                history.pushState({
                        'section':data['section_url']
                    },
                    '',
                    `/${lang}/section/${el.dataset['url']}/`
                )
            }
            if (window.location.href !== `${window.location.origin}/${lang}/`){
                document.title = data.title
            }
            resetSlider()
            autoPlaySlider()
            replace_select_language()
        },
        error: function (data){
            if (data.status !== 0){
                alert(data.errors)
            }
        }
    });
}


function getLang () {
    let lang = ''
    if (window.location.href.includes("/en/")){
        lang = 'en'
    } else if (window.location.href.includes("/ru/")){
        lang = 'ru'
    }
    return lang
}

function replace_select_language () {
    let select = document.querySelector(".name_language")
    if (getInfoAboutUser()[0] === 'mobile' || getInfoAboutUser()[0] === 'laptop'){
        select = document.querySelector(".name_language.curtain")
    }

    let lang_f_replace = getLang()
    select.innerHTML = lang_f_replace
}

function replaceHrefOnOnclick () {
    let elements = document.querySelectorAll('.section_btn')
    let i = 0
    elements.forEach(function (){
        let cur_el = elements[i]
        if (cur_el.attributes.hasOwnProperty("href")){
            cur_el.setAttribute("onclick",`renderContent(this)`)
            let str = cur_el.outerHTML
            let str_f_replace = cur_el.href
            str_f_replace = str_f_replace.replace(`${window.location.origin}`,'')
            str_f_replace = `href="${str_f_replace}"`
            str = str.replace(str_f_replace,'')
            cur_el.outerHTML = str
        }
        i++
    })
}

function faq_open_close () {
    let faq = document.querySelector(".faq_container")
    faq.classList.toggle("open")
    faq.classList.toggle("close")
}

function open_select_language () {
    let el = document.querySelector(".language_select")
    if (getInfoAboutUser()[0] === 'mobile' || getInfoAboutUser()[0] === 'laptop'){
        el = document.querySelector(".language_select.curtain")
    }
    el.classList.toggle("open")
    el.classList.toggle("close")
}

function select_language (el) {
    let txt = el.innerHTML
    let select = document.querySelector(".name_language")
    if (getInfoAboutUser()[0] === 'mobile' || getInfoAboutUser()[0] === 'laptop'){
        select = document.querySelector(".name_language.curtain")
    }
    select.innerHTML = txt
    let lang_f_replace = getLang()
    lang_f_check = txt.toLowerCase()
    // txt.toLowerCase() is selected lang:138
    window.location.href = window.location.href.replace(`${lang_f_replace}`,txt.toLowerCase())
    history.pushState({
        'lang':lang_f_replace
    },null,window.location.href.replace(`${lang_f_replace}`,txt.toLowerCase()))
    open_select_language()
}


// curtain
function openCurtain (el) {
    let curtain = document.querySelector(".curtain")
    curtain.classList.toggle("open")
    curtain.classList.toggle("close")
    if (el.src.includes('burger_menu')){
        el.src = '/static/images/close_menu.svg'
    } else if (el.src.includes('close_menu')){
        el.src = '/static/images/burger_menu.svg'
    }
    openOverlay()
}

function openOverlay () {
    let overlay = document.querySelector(".block_overlay")
    overlay.classList.toggle("show")
    overlay.classList.toggle("hide")
    removeScrollBody()
}

function removeScrollBody () {
    let body = document.querySelector("body")
    body.classList.toggle("n_scroll")
}

// slider

function change_slide (index_this_slide,type,list_lenght,new_slide_inf){
    // stopAutoPlaySlider()
    let new_index_slide = null
    let this_slide = document.querySelector(`[data-id-slide="${index_this_slide}"]`)
    let iterator_slide = document.querySelector(".iterator_slide")
    if (type === 'next'){
        new_index_slide = parseInt(index_this_slide) + 1
    } else if (type === 'back'){
        new_index_slide = parseInt(index_this_slide) - 1
    }
    if (parseInt(new_index_slide) > parseInt(list_lenght)){
        new_index_slide = 1
    } else if (parseInt(new_index_slide) < 1){
        new_index_slide = list_lenght
    }
    let slide_f_show = document.querySelector(`[data-id-slide="${new_index_slide}"]`)
    if (slide_f_show){
        slide_f_show.classList.add("show")
        slide_f_show.classList.remove("hide")
        this_slide.classList.remove("show")
        this_slide.classList.add("hide")

        iterator_slide.innerHTML = `${new_index_slide} / ${list_lenght}`
    }
    if (new_slide_inf){
        return slide_f_show
    }
}

function autoPlaySlider () {
    let next_slide = null
    let new_slide = null
    if (document.querySelector(".functions_btns_slider")){
        if (!autoplayInterval){
            autoplayInterval = setInterval(function (){
                let datainf_cont
                let dataset = null
                if (!new_slide){
                    datainf_cont = document.querySelector(".functions_btns_slider")

                } else {
                    datainf_cont = new_slide.querySelector(".functions_btns_slider")
                }
                dataset = datainf_cont.dataset
                if (dataset){
                    let index_this_slide = dataset['indexSlide']
                    let list_lenght = dataset['lenghtSlides']
                    if (parseInt(list_lenght) > 1){
                        new_slide = change_slide(index_this_slide,'next',list_lenght,'new_slide_inf')
                    } else {
                        if (autoplayInterval){
                            clearInterval(autoplayInterval)
                            autoplayInterval = null
                            showOneSlide(index_this_slide)
                        }
                    }
                }
            },5000)
        } else {
            // autoPlaySlider()
        }
    }
}

function showOneSlide (index_this_slide) {
    let slide = document.querySelector(`[data-id-slide="${index_this_slide}"]`)
    slide.classList.add("show")
    slide.classList.remove("hidden")
}

function resetSlider () {
    if (autoplayInterval){
        clearInterval(autoplayInterval)
        autoplayInterval = null
    }
}

// function stopAutoPlaySlider () {
//     if (autoplayInterval){
//         clearInterval(autoplayInterval)
//     }
// }

// form feedback
function sendFormfeedback (el){
    if (!document.querySelector(".container_content_form_feedback").classList.contains('hide')){
        event.preventDefault()
        let form = el.form
        let formData = new FormData(form)
        let btn_form = document.querySelector(".button_form_feedback")
        if (!btn_form.classList.contains("hide")){
            btn_form.classList.add('hide')
        }
        let language = $('html').attr('lang');
        formData.append('lang', language)
        $.ajax({
            headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
            url: '/send_feedback_form/',
            type: "POST",
            // async: true,
            cache: false,
            processData: false,
            enctype: 'multipart/form-data',
            contentType: false,
            // contentType: "application/json; charset=utf-8",
            data: formData,
            success: function(data){
                document.querySelector(".place_f_after_send").innerHTML = data.html
                document.querySelector(".place_f_after_send").classList.remove("hide")
                document.querySelector(".container_content_form_feedback").classList.add('hide')
            },
            error: function (data){
                document.querySelector(".form_feedback_content").innerHTML = data.responseJSON.left_form_html
                document.querySelector(".checkbox_container").innerHTML = data.responseJSON.right_form_html
                btn_form.classList.remove('hide')
            }
        });
    }
}

function deleteErrorsInput (el) {
    let parent = el.parentNode
    let errors_container = parent.querySelector(".error_input_html")
    if (errors_container){
        let input = parent.querySelector(".input_form_feedback")
        let checkbox_label = parent.querySelector(".label_feedback_form_checkbox")
        if (input){
            input.classList.remove('error')
        } else if (checkbox_label){
            checkbox_label.classList.remove("error")
        } else {
            let textarea = document.querySelector(".textarea_form_feedback")
            textarea.classList.remove("error")
        }

        let str = errors_container.outerHTML
        str = str.replace(str,'')
        errors_container.outerHTML = str
    }
}

function resetForm () {
    let form = document.querySelector(".container_content_form_feedback")
    form.classList.remove("hide")
    let elements_form = document.querySelectorAll('.el_form_feedback')
    for (let i = 0;i < elements_form.length;i++){
        let cur_el = elements_form[i]
        if (cur_el.value) {
            cur_el.value = ''
        }
        if (cur_el.checked){
            cur_el.checked = false
        }
        let label_w_error = cur_el.parentNode.querySelector(".label_feedback_form_checkbox.error")
        if (label_w_error){
            label_w_error.classList.remove("error")
        }
    }
    document.querySelector(".place_f_after_send").classList.add('hide')
    let btn_form = document.querySelector(".button_form_feedback")
    if (btn_form.classList.contains("hide")){
        btn_form.classList.remove('hide')
    }
}

function changeSlideProject (el,type) {
    let cur_slide = document.querySelector(".el_container_projects_slider.show")

    let dataset = cur_slide.dataset
    if (dataset){
        let index_cur_slide = parseInt(dataset['indexSlideProj'])
        let count_slides = parseInt(dataset['countSlidesProj'])
        let new_index_slide = null
        if (type === 'next'){
            new_index_slide = index_cur_slide + 1
        } else if (type === 'back'){
            new_index_slide = index_cur_slide - 1
        }
        if (new_index_slide > count_slides){
            new_index_slide = 1
        } else if (new_index_slide < 1){
            new_index_slide = count_slides
        }
        let slide_f_processing = document.querySelector(`[data-index-slide-proj="${new_index_slide}"]`)
        if (slide_f_processing){
            slide_f_processing.classList.toggle("show")
            slide_f_processing.classList.toggle("hide")
            cur_slide.classList.toggle("show")
            cur_slide.classList.toggle("hide")
        }
    }
}