import './styles/app.css';
import './js/jquery-3.7.1.min.js';
import {gsap, TimelineMax} from 'gsap';
import {ScrollTrigger} from "gsap/ScrollTrigger";
import {ScrollSmoother} from "gsap/ScrollSmoother";
import './js/owl.carousel.min.js';
import './js/toastr.min.js';
import './styles/toastr.min.css';
window.$ = $;
const params = new URLSearchParams(document.location.search);

gsap.registerPlugin(ScrollTrigger, ScrollSmoother);
let mm = gsap.matchMedia();
var scrollSmoother;
var touchDevice = window.matchMedia("(pointer: coarse)").matches


var locale = window.location.href.split('/')[3];
if (!['tr', 'en', 'de'].includes(locale)){locale="tr";}
let textError;
let textClose;
let successText;
let textErrorEmpty;
let textCopied;
switch (locale){
    case 'tr': 
        textClose = 'Kapat';
        successText = 'Mesajınız gönderildi';
        textCopied = 'Bağlantı başarıyla kopyalandı';
        textError = 'Bir hata oluştu';
        textErrorEmpty = 'Lütfen formu doldurun';
    break;
    case 'en': 
        textClose = 'Close';
        successText = 'Your message has been sent';
        textCopied = 'The link is successfully copied';
        textError = 'An Error Occurred';
        textErrorEmpty = 'Please fill the form';
    break;
    case 'de':
        textClose = 'Schließen';
        successText = 'Ihre Nachricht wurde gesendet';
        textCopied = 'Verbindung erfolgreich kopiert';
        textError = 'Ein Fehler Ist Aufgetreten';
        textErrorEmpty = 'Bitte füllen Sie das Formular aus';
        textError = 'Verbindung erfolgreich kopiert';
    break;
}



// Resize Handler
let brandsScroller = null;
let updateBrandsScroller = null;
function resize(){
    touchDevice = window.matchMedia("(pointer: coarse)").matches;
    setTimeout(()=>{initalizeNavCursor()}, 250);
    let activeEl = document.querySelector(".global-nav-links > li > a.active");
    if(activeEl){
        setTimeout(()=>{setNavCursorPosition(activeEl)},100);
    }
    let width = window.innerWidth;
    let height = window.innerHeight;
    if(brandsScroller){
        if(updateBrandsScroller){
            updateBrandsScroller(brandsScroller);
        }
    }
    if(typeof(homeSliderTrigger) != 'undefined'){
        homeSliderTrigger.refresh();
        homeSliderContentHeight = homeSliderContent.getBoundingClientRect().height;
        homeSliderSectionHeight = homeSliderContent.parentElement.parentElement.getBoundingClientRect().height;
    }
}
resize();
window.onresize = resize;


// Nav Cursor
var navCursor = document.querySelector(".nav-cursor");
let navCursorPositionSet = false;
let first = true;

function setNavCursorPosition(element){
    if (!element){return}
    let bounding = element.getBoundingClientRect();
    let func = gsap.to;
    if ((!navCursorPositionSet && !touchDevice) || first){func = gsap.set}
    func(navCursor, {x: bounding.x - parseInt($(".global-header").css("padding-left").replace("px", "")), width: bounding.width, duration: .25});
    first = false;
}
let currentEl = document.querySelector('.global-nav-links > li > a.current');
function initalizeNavCursor(){
    if (navCursor){
        if(!currentEl){setNavCursorPosition(document.querySelector(".global-nav-links li"))}
        else{setNavCursorPosition(currentEl);navCursorPositionSet = true;}
        document.querySelectorAll(".global-nav-links li > a").forEach((navItem)=>{
            if(!touchDevice) {
                if(navItem.matches(':hover')){setNavCursorPosition(event.currentTarget.parentElement)}
                navItem.addEventListener('mouseover', (event)=>{
                    setNavCursorPosition(event.currentTarget.parentElement);
                    navCursorPositionSet = true;
                })
            }
            else{
                navItem.addEventListener("click", (event)=>{
                    if (event.currentTarget.parentElement.querySelector(".nav-dropdown-wrapper")){
                        setNavCursorPosition(event.currentTarget);
                    }
                })
            }
        });
    }
}
if(navCursor){
    document.querySelectorAll(".global-nav-links li > a").forEach((navItem)=>{
        let navDropdown = navItem.parentElement.querySelector(".nav-dropdown");
        if(navDropdown){
            navItem.addEventListener('mouseenter', (event)=>{
                $('.global-nav-links > li > a.active').removeClass("active");
                event.currentTarget.classList.add('active');
                setNavCursorPosition(navItem)
            })
            navDropdown.addEventListener('mouseleave', (event)=>{
                if (!navItem.matches(":hover")){
                    navItem.classList.remove('active');
                }
            })
        }else{
            navItem.addEventListener('mouseenter', (event)=>{
                $('.global-nav-links > li > a.active').removeClass("active");
                setNavCursorPosition(navItem)
            })  
        }
    });
    document.querySelector(".global-nav-links").addEventListener('mouseleave', ()=>{
        let activeEl = event.currentTarget.querySelector('li a.active');
        if(activeEl){
            setNavCursorPosition(activeEl);
        }else if(currentEl)
            setNavCursorPosition(currentEl);
        else{
            navCursorPositionSet = false;
        }
    })
    document.querySelector(".nav-dropdown-close-wrapper").addEventListener("click", (event)=>{
        $('.global-nav-links > li > a.active').removeClass("active");
    })
    document.querySelector(".global-nav-links").addEventListener('mouseleave', (event)=>{
    })
    $(".nav-dropdown-wrapper").on("mouseover",(event)=>{setNavCursorPosition(event.currentTarget.parentElement)})
    if(currentEl){
        setNavCursorPosition(currentEl);
    }
}
initalizeNavCursor()



// Intro
const header = document.querySelector("header");
const introTop = document.querySelector(".intro-top");
const introImg = document.querySelector(".intro-img");
if (introTop){
mm.add("(min-width: 1024px)", () => {
    ScrollTrigger.create({
        trigger: ".main-section",
        pin: false,
        start: 'top top',
        end: '+=400',
        scrub: false,
        onUpdate: (self)=>{
            if (self.progress > 0.05){
                header.classList.add('active');
            }else{
                header.classList.remove('active');
            }
            if (introImg){
                let yIntro = ( introTop.getBoundingClientRect().height * (self.progress * 1.5) );
                let y = -( 60 * self.progress );
                let width = (98 + ( 2 * self.progress ))+"%";
                let radius = 80 - ( 80 * self.progress )
                gsap.set(introImg, {width: width, y: y, borderTopLeftRadius: radius, borderTopRightRadius: radius})
                gsap.set(introTop, {y: yIntro})
            }
        },
        onLeaveBack: ()=>{header.classList.remove('active');}
    });
});
}

/*
// Fade in on scroll
let projectContainer = document.querySelector(".project-container");
if (projectContainer){
var mainTimeline = new TimelineMax();
    let tl = gsap.timeline({
        scrollTrigger: {
            trigger: ".project-container",
            start: '100 bottom',
            end: "+=500",
            scrub: false,p
            markers: true
        }
    });
    document.querySelectorAll(".project-grid-item").forEach((item=>{
        tl.from(item, {alpha: 0, opacity: 0, y: 150, ease: "Power1.out"})
        mainTimeline.add(tl, '-=0.1');
    }));
}
*/

// Skip Buttons
function scrollToElement(elementSelector){
    let height = document.querySelector(elementSelector).getBoundingClientRect().height;
    let y = 80;
    if (height <= window.innerHeight){
        y = (window.innerHeight - height) / 2;
    }
    if(window.lenis){
        window.lenis.scrollTo(elementSelector, {offset: -y})
    }
}

function initalizeSkipButton(skipBtn){
    let data = skipBtn.getAttribute('data-skip');
    if (data){
        skipBtn.addEventListener('click', ()=>{
            scrollToElement(data)
        })
    }
}

document.querySelectorAll('.skip-button').forEach(initalizeSkipButton)
document.addEventListener("DOMContentLoaded", ()=>{
    if(params.get('tags') || params.get('s')){
        if (document.querySelector(".projects-wrapper")){scrollToElement(".projects-wrapper")}
    }
})


// Dropdown Boxes
function expandMenu(el, height, duration = .2) {
    $(el).removeAttr("style");
    gsap.from(el, {
        height: height,
        duration: duration,
        ease: "power1.out"
    })
}
function closeMenu(el, height, duration = .2) {
    gsap.to(el, {
        height: height,
        duration: duration,
        ease: "power1.out"
    })
}

document.querySelectorAll('.dd-box-container').forEach((container)=>{
    container.querySelectorAll('.dd-box-item').forEach((el)=>{
        el.addEventListener("click", (event)=>{
            event.stopPropagation();
            if(!(event.target==el || ($(event.target).closest('.no_propagation').length == 0))){
                return;
            }
            let activeElement = container.querySelector('.dd-box-item.active');
            if(activeElement){
                activeElement.classList.remove("active");
                closeMenu(activeElement.querySelector(".dd-box-content"), 24)
            }
            if (!(activeElement == event.currentTarget) || !(activeElement)){
                el.classList.add("active");
                expandMenu(event.currentTarget.querySelector(".dd-box-content"), 24)
            }
        })
    })
});

// Popup
function initalizePopup(popupWrapper){
    let closeEl = popupWrapper.querySelector(".popup-close");
    let popup = popupWrapper.querySelector(".popup");
    gsap.from(popup, {opacity: 0, y: 150, ease: "Power4.inOut", duration: .375});
    let close = (event)=>{
        gsap.to(popup, {opacity: 0, y: 150, ease: "Power4.inOut", duration: .375, onComplete: ()=>{popupWrapper.remove();}});
    };
    closeEl.addEventListener("click", close);
    let owl = popupWrapper.querySelector(".owl-carousel");
    if (owl){initalizeOwlCarousel(owl)}
    let owlNav = popupWrapper.querySelector(".popup-slider-navigator");
    if (owlNav){
        owlNavigator(owlNav.querySelector("[data-owl-next]"), "next");
        owlNavigator(owlNav.querySelector("[data-owl-prev]"), "prev");
    }
    $(popupWrapper).find(".input-select").each((index, item)=>{
        initalizeSelectInput(item);
        initalizeActivate(item);
        initalizeFocusoutInactive(item);
    })
}
document.addEventListener("DOMContentLoaded", ()=>{
    document.querySelectorAll(".popup-wrapper").forEach(initalizePopup);
})


// Office Slider
const officeSlider = document.querySelector(".office-slider-content > .slider");
const officeSliderBackground = document.querySelector(".office-slider .background");

function refreshSlider(event){
    try{
        let item = officeSlider.querySelector(".owl-stage").children[event.item.index].children[0];
        let count = event.item.count;
        if((count + "").length==1){count = "0"+count}
        $(".page-indicator-container > *:last-child").text(count);
        setTimeout(()=>{$(".slide-indicator").text(item.getAttribute("data-name"));}, 100)
        gsap.to(".slide-indicator", {duration: .2, ease: "Power1.out", opacity: 0, onComplete: ()=>{
            gsap.to(".slide-indicator", {duration: .5, ease: "Power1.in", opacity: 1})
        }})
        let index = event.item.index;
        index -= 1;
        if(index==0){index=event.item.count}
        if(index>event.item.count){index=index-event.item.count}
        if((index + "").length==1){index = "0"+index}
        setTimeout(()=>{$(".page-indicator").text(index);}, 100)
        gsap.to(".page-indicator", {duration: .2, ease: "Power1.out", opacity: 0, onComplete: ()=>{
            gsap.to(".page-indicator", {duration: .5, ease: "Power1.in", opacity: 1})
        }})
        let prev = officeSliderBackground.querySelector(".next");
        let main = officeSliderBackground.querySelector(".main");
        if(prev){
            main.src = prev.src;
            prev.remove();
        }
        let nextImage = document.createElement("img");
        nextImage.src = item.querySelector("img").src;
        nextImage.setAttribute('class', "next")
        officeSliderBackground.appendChild(nextImage);
        gsap.to(main, {opacity: 0})
        gsap.from(nextImage, {opacity: 0})
    }catch (e){
    }
}
$(officeSlider).on('changed.owl.carousel', (event)=>{
    refreshSlider(event);
});

// Owl Carousels
function updateSlider(event){
    let count = event.item.count;
    let index = Math.max(event.item.index, 2);
    document.querySelector(".page-indicator").innerHTML = (index - 1) + "/" + (count);
}

function initalizeOwlCarousel(carouselEl){
    let data = carouselEl.getAttribute('data-carousel');
    if (data){
        let options = JSON.parse(data.replaceAll("'", '"'));
        let carousel = $(carouselEl).owlCarousel(options);
        setTimeout(()=>{carousel.trigger('refresh.owl.carousel');if(options['smartSpeed']){carousel.trigger('play.owl.autoplay');}});
    }
}
document.querySelectorAll('.owl-carousel').forEach(initalizeOwlCarousel);

// Owl Carousel Nav Buttons
function owlNavigator(btn, type){
    let slider = btn.getAttribute(type == "next" ? "data-owl-next" : "data-owl-prev");
    if (slider){
        $(btn).on("click", (event)=>{if(event.currentTarget.classList.contains('disabled')){return};$(slider).trigger(type == "next" ? "next.owl.carousel" : "prev.owl.carousel");})
    }
}
document.querySelectorAll("[data-owl-next]").forEach((nextBtn)=>{owlNavigator(nextBtn, "next")})
document.querySelectorAll("[data-owl-prev]").forEach((prevBtn)=>{owlNavigator(prevBtn, "prev")})

// Brands Scroller
const brands = document.querySelector(".home-brands");
if (brands){
document.addEventListener('DOMContentLoaded', ()=>{
const brandsContent = document.querySelector(".brands-content");
const brandsProgress = document.querySelector(".brands-progress");
window.brandItemIndexes = [];
const brandItemGap = parseInt($(".brands-content > *").css('gap').replace('px'));
let brandsScrollerEnd = (document.querySelector('.brand-item:last-child').getBoundingClientRect().top - brandsContent.getBoundingClientRect().top);

updateBrandsScroller = (brandsScroller)=>{
    $(".brand-item").css({position: 'relative', top: 'unset', transform: 'unset'});
    window.brandItemIndexes.length = 0;
    let longest = 0;
    let totalMargin = 0;
    let brandItems = $('.brand-item');
    brandItems.each((index, item)=>{
        $(item).css({'margin-bottom': 0});
        let height = item.getBoundingClientRect().height;
        if (longest < height){longest = height};
        let pix = item.getBoundingClientRect().top - brandsContent.getBoundingClientRect().top;
        window.brandItemIndexes.push([(pix / brandsScrollerEnd).toFixed(3) || 0, item.getAttribute('data-color'), null]);
    });
    brandItems.each((index, item)=>{
        $(item).css({position: 'sticky', top: 160});
        let height = item.getBoundingClientRect().height;
        if (height < longest){
            $(item).css({'margin-bottom': longest - height});
            totalMargin += longest - height;
        }
    })
    brandsScrollerEnd = (document.querySelector('.brand-item:last-child').getBoundingClientRect().top - brandsContent.getBoundingClientRect().top) + (totalMargin);
    brandsScroller.scrollTrigger.vars.end = "+=" + brandsScrollerEnd;
    brandsScroller.scrollTrigger.refresh();
    brandsScroller.scrollTrigger.vars.onUpdate(brandsScroller.scrollTrigger);
    return window.brandItemIndexes;
};
brandsScroller = gsap.timeline({
    scrollTrigger: {
        pin: false,
        trigger: brandsContent,
        scrub: 1,
        start: "-=" + 160,
        end: "+=" + brandsScrollerEnd,
        onUpdate: (self)=>{
            let current = 0;
            for (let i = 0; i < window.brandItemIndexes.length; i++){
                let index = window.brandItemIndexes[i];
                if (self.progress >= index[0]){
                    current = i;
                }
            }
            for (let i = 0; i < window.brandItemIndexes.length; i++){
                let index = window.brandItemIndexes[i];
                if ((current != window.brandItemIndexes.length - 1) && self.progress >= window.brandItemIndexes[i][0]){
                    let threshold = (self.progress - index[0]);
                    $(".brand-item").eq(i).css('transform', 'translateY(' + (-150 * threshold) + 'px) scale(' + (1 - (.2 * threshold)) + ')');
                }
            }
            let percentage = self.progress * 100;
            $(brandsProgress).css({background: 'linear-gradient(rgb(62, 112, 113) '+percentage+'%, rgb(255, 255, 255) '+percentage+'%, rgb(255, 255, 255))'})
            $(brands).get(0).style.setProperty("--brand-color", window.brandItemIndexes[Math.max(0, current)][1])
        }
    }
});
updateBrandsScroller(brandsScroller);
})
}

// Home Slider
const homeSlider = document.querySelector(".home-slider");
if (homeSlider){
const homeSliderContent = document.querySelector(".home-slider-content");
let slideIndicator = homeSlider.querySelector(".slide-indicator");
let pageIndicator = homeSlider.querySelector(".page-indicator");
let textCarousel = homeSlider.querySelector('.home-slider-text-carousel');
let homeSliderIndex = 0;
let homeSliderIsPlaying=false;
$(".home-slider-navigator button").on('click', (event)=>{
    if(!event.currentTarget.classList.contains('disabled')){
        $(".home-slider-navigator button").each((index, item)=>{
            // Disable navigation buttons after clicking to wait for the end of the animation
            item.classList.add('disabled');
            setTimeout(()=>{item.classList.remove('disabled')}, 500);
        })
    }
})
$(textCarousel).on('changed.owl.carousel', function(event) {
    gsap.to(slideIndicator, {duration: .25, ease: "Power1.out", opacity: 0, onComplete: ()=>{
        $(slideIndicator).text(textCarousel.querySelector(".owl-stage").children[event.item.index].querySelector(".text-container").getAttribute('data-name'));
        gsap.to(slideIndicator, {duration: .25, ease: "Power1.in", opacity: 1})}})
    gsap.to(pageIndicator, {duration: .25, ease: "Power1.out", opacity: 0, onComplete: ()=>{
        $(pageIndicator).text((event.item.index + 1) + " - " + event.item.count);
        gsap.to(pageIndicator, {duration: .25, ease: "Power1.in", opacity: 1})
    }})
    let isBack = homeSliderIndex > event.item.index;
    let nEl = document.querySelector(".home-slider-images").children[event.item.index];
    let oEl = document.querySelector(".home-slider-images").children[homeSliderIndex];
    gsap.set(nEl, {zIndex: 2, xPercent: isBack ? 100 : -100});
    gsap.to(nEl, {xPercent: 0, ease: 'power2.inOut', duration: .5, onComplete: ()=>{
        gsap.set(nEl, {zIndex: 0});
        oEl.classList.remove('active');
        nEl.classList.add('active');
    }});
    homeSliderIndex = event.item.index;
});   
}

$(".input-parent").each((index, inputParent)=>{
    inputParent.addEventListener('focus', (e)=>{
        inputParent.querySelector('.input').focus()
    })
});

// Select Menu
function initalizeSelectInput(triggerEl, menuSelector = ".select-menu"){

    $(triggerEl).on("click", (event)=>{
        if (event.currentTarget.classList.contains("active")){
            return;
        }
        let el = event.currentTarget.querySelector(menuSelector);
        gsap.set(el, {opacity: 1, y: 200})
        gsap.to(el, {y: 0, duration: .5, ease: "elastic.out(1, 1)",})
    });
}
$(".input-select").each((index, item)=>{initalizeSelectInput(item)})
$(".dropdown-trigger").each((index, item)=>{initalizeSelectInput(item, ".dropdown-menu")})


// Language Selector
if (!touchDevice){
    $(".language-selector-content").on("mouseenter", (event)=>{
        let width = 65;
        if (window.innerWidth<=1024){width=50}
        let wrapper = event.currentTarget.parentElement;
        gsap.set(wrapper, {width: "auto"})
        gsap.from(wrapper, {duration: 0.125, width: width})
    });

    $(".language-selector-content").on("mouseleave", (event)=>{
        let width = 65;
        if (window.innerWidth<=1024){width= 50}
        let wrapper = event.currentTarget.parentElement;
        gsap.to(wrapper, {duration: 0.125, width: width})
    });
}else{
    $(".language-selector-content").on("click", (event)=>{
        let width = 65;
        if (window.innerWidth<=1024){width= 50}
        let wrapper = event.currentTarget.parentElement;
        if(!event.currentTarget.classList.contains('active')){
            gsap.set(wrapper, {width: "auto"})
            gsap.from(wrapper, {duration: 0.125, width: width})
        }else{
            gsap.to(wrapper, {duration: 0.125, width: width})
        }
    });
}


// Header Router
let headerRouterMenuWrapper = document.querySelector(".header-router-menu-wrapper");
let headerRouterMenu = document.querySelector(".header-router-menu");

function setHeaaderRouterMenuHeight(el=headerRouterMenu){
    $(".header-router-menu-wrapper").css("height", el.getBoundingClientRect().height)
}
$(".header-router-menu").on("click", (event)=>{event.stopPropagation();})
document.querySelectorAll(".header-router-item.has-content").forEach((routerItem)=>{
    routerItem.addEventListener("click", (event)=>{
        event.stopPropagation();
        event.currentTarget.classList.add('active');
        setHeaaderRouterMenuHeight(routerItem.querySelector(".content"));
    })
})
document.querySelectorAll(".header-router-item .content-back").forEach((backButton)=>{
    backButton.addEventListener("click", (event)=>{
        event.stopPropagation();
        event.currentTarget.parentElement.parentElement.classList.remove('active');
        setHeaaderRouterMenuHeight();
    })
})
$(".header-router-button").on("click", (event)=>{
    if (event.currentTarget.classList.contains("active")){
        $(event.currentTarget).find(".header-router-item.active").removeClass("active");
        setHeaaderRouterMenuHeight();
        return;
    }
    gsap.set(headerRouterMenuWrapper, {opacity: 1, y: 200})
    gsap.to(headerRouterMenuWrapper, {y: 0, duration: .5, ease: "elastic.out(1, 1)",})
})
setHeaaderRouterMenuHeight()


/* Filter Popup */
document.querySelectorAll(".filter-popup-button").forEach((filterButton)=>{
    filterButton.addEventListener("click", (event)=>{
        let searchWrapper = document.querySelector(".search-wrapper");
        let popupWrapper = document.createElement("div");
        popupWrapper.setAttribute("class", "popup-wrapper");
        let isNoSelect = document.querySelector(".tag-search").classList.contains("noselect");
        let content = `
        <div class="popup filter-popup" data-search-wrapper=".` + searchWrapper.getAttribute('class').split(' ').join('.') + `" >
            <div class="popup-top">
                <div class="logo-container">
                    <span class="popup-window-title">` + searchWrapper.querySelector('.filter-popup-button').innerHTML + `</span>
                </div>
                <div class="popup-close border-button">
                    <div class="icon cross-icon"></div>
                    ` + textClose + `
                </div>
            </div>
            <div class="popup-content">
                <div class="filter-select-container tag-search">
                    <span>`+ searchWrapper.querySelector(".tag-search span").innerHTML +`</span>
                    <div class="filter-select activate focusout_inactivate input-select no_propagation ` + ((isNoSelect) ? 'noselect' : '')  +  ` input-arrow arrow-down arrow-dark" tabindex="0">
                        <div class="selected input">`+ searchWrapper.querySelector(".tag-search .selected").innerHTML +`</div>
                        <div class="select-menu no_propagation"><ul>` + searchWrapper.querySelector(".tag-search .select-menu ul").innerHTML + `</ul></div>
                    </div>
                </div>
            </div>
        </div>`;
        popupWrapper.innerHTML = content;
        document.body.appendChild(popupWrapper);
        initalizePopup(popupWrapper);
        popupWrapper.querySelectorAll('.tag-search li a').forEach((selectButton)=>{
            selectButton.addEventListener('click', tagClick);
        });
    })
})

/* Search */

document.querySelectorAll('.select-menu').forEach((selectMenu)=>{
    selectMenu.setAttribute('data-lenis-prevent', '');
})

function tagClick(event){
    // Contact query type selection
    if(event.currentTarget.matches('.query-type .select-menu li a')){
        $(event.currentTarget).closest('.query-type').find('input').val($(event.currentTarget).text());
        setTimeout(()=>{$(event.currentTarget).closest('.select-menu-trigger').removeClass('active')}, 0);
        return
    }

    // Search tag selection
    let searchWrapper = $(event.currentTarget).closest('.search-wrapper');
    let popup;
    if (searchWrapper.length == 0){
        popup = $(event.currentTarget).closest('.popup');
        searchWrapper = $(popup.attr('data-search-wrapper'));
    }
    let index = $(event.currentTarget.parentElement).index();
    if (event.currentTarget.matches('.noselect li a')){searchWrapper.find('li a.active').removeClass('active')}
    $(searchWrapper).find(".select-menu ul li").eq(index).find("a").toggleClass('active');
    if (popup){
        $(popup).find(".select-menu ul li").eq(index).find("a").toggleClass('active');
        console.log($(popup).find(".select-menu ul li").eq(index).find("a").get(0))
    }
    realTimeSearch($(searchWrapper).find('input'));
}
$(".select-menu li a").on("click", tagClick);
document.querySelectorAll(".filter-popup-button")
let keyPressDelta = 0;
function realTimeSearch(inputItem){
    let url;
    let el;
    let loadingEl;
    let searchWrapper = document.querySelector('.search-wrapper');
    if(searchWrapper.classList.contains('blog-search-wrapper')){
        url = 'blog-search';
        el = document.querySelector('.blog-content');
        loadingEl = `<a class="blog-item standart">
        <div class="blog-img loading-content"></div>
        <div class="blog-item-content">
            <div class="tag-container"></div>
            <div class="blog-title loading-content" style="height: 1.5rem"></div>
            <div class="blog-date loading-content" style="height: 1.5rem"></div>
        </div>
    </a>`;
        if(!document.querySelector('.loading-content')){
            el.innerHTML = loadingEl.repeat(6);
        }
    }else if(searchWrapper.classList.contains('reference-search-wrapper')){
        url = 'reference-search';
        el = document.querySelector('.references-content');
        loadingEl = `<a class="reference-item">
                <div class="reference-item-img loading-content"></div>
                <div class="reference-item-title loading-content" style="height: 1.5rem"></div>
            </a>`
        if(!document.querySelector('.loading-content')){
            el.innerHTML = loadingEl.repeat(12);
        }
    }else{
        url = 'project-search';
        el = document.querySelector('.projects');
        loadingEl = `<div class="project-item">
                <div class="project-item-top" style="width: 100%">
                    <h2 class="loading-content" class="loading-content" style="height: ` + ((!touchDevice) ? '2.5rem;margin-top:20px' : '1.5rem') + `;width:60%;display: block;"></h2>
                </div>
                <div class="project-item-content">
                    <div class="project-logo loading-content" style="width: 40px;height: 40px"></div>
                    <div class="project-tags tag-container loading-content" style="height: 1.5rem; width: 100%;height: 30px"></div>                            
                </div>
            </div>`
        if(!document.querySelector('.loading-content')){
            el.innerHTML = loadingEl.repeat(4);
        }
    }
    keyPressDelta = new Date().getTime();

    // Get selected tags
    let tags = [];
    let tagText = [];
    let selectMenu = $($(inputItem).closest(".search-wrapper").find('.select-menu'));
    selectMenu.addClass('loading');
    $('.filter-select .select-menu').addClass('loading');
    selectMenu.find("li a.active").each((index, item)=>{
        tags.push(item.getAttribute("data-identifier"));
        tagText.push(item.innerHTML);
    }),
    tagText = tagText.join(", ");
    tagText = (tagText.length == 0) ? document.querySelector(".search-wrapper .selected").getAttribute('data-placeholder') : tagText;
    $(".search-wrapper .selected").text(tagText);
    $(".filter-select .selected").text(tagText);
    tags = tags.join(",");

    let query = $(inputItem).val();
    $(inputItem).closest('.search-wrapper').find('input').val(query);

    setTimeout(()=>{
        if(new Date().getTime() - keyPressDelta < 500){return;}
        $.ajax({
            url: window.urlRoot+locale+'/'+url+'?s='+query+'&tags='+tags,
            success: (data)=>{
                let parentEl = el.parentElement;
                if (parentEl.innerHTML + "" != data){
                    parentEl.innerHTML = data;
                };
                if (url == 'reference-search'){
                    document.querySelectorAll(".reference-item").forEach(initalizeReferenceItem)
                }
                let paramArray = {}
                if(query.length > 0){paramArray['s']=query;}
                if(tags.length > 0){paramArray['tags']=tags;}
                const newParams = new URLSearchParams(paramArray);
                window.history.pushState({}, "", "?" + newParams.toString());
                selectMenu.removeClass('loading');
                $('.filter-select .select-menu').removeClass('loading');
                $(el).css('height', 'auto');
            }
        })
    }, 500)
}
$(".search-wrapper .query-search input").on('input', (event)=>{realTimeSearch(event.currentTarget)})

// Contact

$('.send-email').on('click', ()=>{
    let contactForm = document.querySelector(".contact-form");
    let firstName = document.querySelector('#firstName').value;
    let lastName = document.querySelector('#lastName').value;
    let mail = document.querySelector('#mail').value;
    let queryType = document.querySelector('#query_type').value;
    let message = document.querySelector('#message').value;
    if(firstName==""||lastName==""||mail==""||queryType==""||message==""){toastr.error(textErrorEmpty);return;}
    contactForm.classList.add('loading');
    $.ajax({
        url: window.urlRoot+'send_email?firstName='+firstName+'&lastName='+lastName+'&queryType='+queryType+'&message='+message+'&mail='+mail,
        success: ()=>{
            toastr.success(successText);
            contactForm.classList.remove('loading');
        },
        error: ()=>{
            toastr.error(textError);
            contactForm.classList.remove('loading');
        }
    })
})


// References 

let referencePopupLoading = false;
function initalizeReferenceItem(referenceItem){
    referenceItem.addEventListener("click", (event)=>{
        let popupWrapper = document.querySelector(".popup-wrapper");
        if (popupWrapper || referencePopupLoading){return;}
        referencePopupLoading = true;
        setTimeout(()=>{
            if (referencePopupLoading){
                referenceItem.querySelector('.reference-item-img').classList.add('loading');
            }
        }, 100)
        $.ajax({
            url: window.urlRoot+locale+"/reference_popup/"+referenceItem.getAttribute('data-id'),
            success: (data)=>{
                referencePopupLoading = false;
                let popupWrapperWrapper = document.createElement("div");
                popupWrapperWrapper.innerHTML += data;
                document.body.appendChild(popupWrapperWrapper);
                popupWrapper = document.querySelector(".popup-wrapper");
                initalizePopup(popupWrapper);
                referenceItem.querySelector('.reference-item-img').classList.remove('loading');
            }
        })
    })
}
document.querySelectorAll(".reference-item").forEach(initalizeReferenceItem)

// Service Detail

$(".service-detail .text-container").each((index, textContainer)=>{
    let textEl = textContainer.querySelector('.text');
    if (!textEl){return;}
    let readMore = $(textContainer.querySelector('.read-more'));
    let glow = $(textContainer.querySelector('.glow'));
    let cappedHeight = textEl.getBoundingClientRect().height;
    $(textEl).css('max-height', 'unset');
    // Check if the text is overflowing
    if (textEl.getBoundingClientRect().height > cappedHeight){
        $(textEl).css('max-height', cappedHeight)
        readMore.on('click', (event)=>{
            event.preventDefault();
            $(textEl).css('max-height', 'unset');
            readMore.css('display', 'none');
            glow.css('display', 'none');
        });
    }else{
        readMore.css('display', 'none');
        glow.css('display', 'none');
    }
});


// Blog Detail Share

$(".share-content .link-icon").on('click', (event)=>{
    try{
        var dummy = document.createElement('input')
        let url = window.location.href;

        document.body.appendChild(dummy);
        dummy.value = url;
        dummy.select();
        document.execCommand('copy');
        document.body.removeChild(dummy);
        toastr.success(textCopied);
    }catch{
        toastr.error(textError);
    }
})

function initalizeActivate(el){
    $(el).on("click", (event)=>{
        event.stopPropagation();
        if(!el.classList.contains("no_propagation") || (event.target==el || ($(event.target).closest('.no_propagation')[0] == el) && !event.target.classList.contains('no_propagation'))){
            event.currentTarget.classList.toggle("active");
        }
    })   
}
function activate(event){
    event.currentTarget.classList.add("active");
}
function deactivate(event){
    event.currentTarget.classList.remove("active");
}
function initalizeActivateHover(el){
    if(!touchDevice){
        $(el).on("mouseenter", activate);
        $(el).on("mouseleave", deactivate);
    }else{
        initalizeActivate(el);
    }
}
function initalizeFocusoutInactive(el){
    $(el).on("focusout", (event)=>{
        event.currentTarget.classList.remove("active");
    })
}
$(".activate").each((_, item)=>{initalizeActivate(item)});
$(".activate_hover").each((_, item)=>{initalizeActivateHover(item)});
$(".focusout_inactivate").each((_, item)=>{initalizeFocusoutInactive(item)});
document.addEventListener('DOMContentLoaded', ()=>{
    $('.loader').css('display', 'none');
});