var slider = document.querySelectorAll('.slider');
var posInitial, leftValue;

slider.forEach(slider => {
    var sliderItems = slider.querySelector('#items');

    if(sliderItems.getElementsByClassName('slide').length > 1) {
        slide(slider, sliderItems);
    } else {
        sliderItems.style.left = 0;
    }
});

function slide(wrapper, items) {
    var slides = items.getElementsByClassName('slide'),
        slidesLength = slides.length,
        firstSlide = slides[0],
        slideSize = firstSlide.offsetWidth,
        lastSlide = slides[slidesLength - 1],
        cloneFirst = firstSlide.cloneNode(true),
        cloneLast = lastSlide.cloneNode(true),
        index = 0,
        allowShift = true;

    // Clone first and last slide
    items.appendChild(cloneFirst);
    items.insertBefore(cloneLast, firstSlide);
    wrapper.classList.add('loaded');

    // Transition events
    items.addEventListener('transitionend', checkIndex);

    setInterval(() => { shiftSlide(1); }, 5000);

    function shiftSlide(dir) {
        items.classList.add('shifting');
        
        if (allowShift) {
            slideSize = firstSlide.offsetWidth;
            posInitial = items.offsetLeft;
            if (dir == 1) {
                items.style.left = (posInitial - slideSize) + "px";
                index++;
            } else if (dir == -1) {
                items.style.left = (posInitial + slideSize) + "px";
                index--;
            }
        };

        allowShift = false;
    }

    function checkIndex() {
        items.classList.remove('shifting');
        if (index == -1) {
            items.style.left = -(slidesLength * slideSize) + "px";
            index = slidesLength - 1;
        }
        if (index == slidesLength) {
            items.style.left = -(1 * slideSize) + "px";
            index = 0;
        }

        allowShift = true;
    }
}

function setSlideSize() {
    var cardSliderIndex = document.getElementById('card-slider-index'),
        slider = document.querySelectorAll('.slider'),
        sliderItems;

    if(cardSliderIndex) {
        document.documentElement.style.setProperty('--w-slider-index', cardSliderIndex.offsetWidth + 'px');
        slider.forEach(slider => {
            sliderItems = slider.querySelector('#items');
            if(sliderItems.getElementsByClassName('slide').length > 1) {
                sliderItems.style.left = -cardSliderIndex.offsetWidth + 'px';
            } else {
                sliderItems.style.left = 0;
            }
        });
    }
}

window.onload = setSlideSize;
window.onresize = setSlideSize;