// source --> https://itancia.com/wp-content/plugins/the-events-calendar/common/build/js/tribe-common.js?ver=9c44e11f3503a33e9540 
String.prototype.className=function(){return"string"!=typeof this&&!this instanceof String||"function"!=typeof this.replace?this:this.replace(".","")},String.prototype.varName=function(){return"string"!=typeof this&&!this instanceof String||"function"!=typeof this.replace?this:this.replace("-","_")},function(){const t=new URL(window.location.href).hash;if(!t||!t.match("#(tribe|tec)"))return;let e=!0;const n=new MutationObserver((function(){e=!0}));n.observe(window.document,{attributes:!0,childList:!0,characterData:!0,subtree:!0});const i=function(){if(e)e=!1,setTimeout(i,250);else{n.takeRecords(),n.disconnect();const e=document.getElementById(t.substring(1));e&&e.scrollIntoView()}};i()}(),window.tribe=window.tribe||{},window.tec=window.tec||{},window.tec=window.tec||{},window.tec.common=window.tec.common||{},window.tec.common.tribeCommon={};
// source --> https://itancia.com/wp-content/plugins/the-events-calendar/build/js/views/breakpoints.js?ver=4208de2df2852e0b91ec 
tribe.events=tribe.events||{},tribe.events.views=tribe.events.views||{},tribe.events.views.breakpoints={},function(e,t){"use strict";const n=e(document);t.selectors={container:'[data-js="tribe-events-view"]',dataScript:'[data-js="tribe-events-view-data"]',breakpointClassPrefix:"tribe-common--breakpoint-"},t.breakpoints={},t.setContainerClasses=function(e,n){Object.keys(n.breakpoints).forEach((function(i){const s=t.selectors.breakpointClassPrefix+i;t.breakpoints[i]=n.breakpoints[i],e.outerWidth()<n.breakpoints[i]?e.removeClass(s):e.addClass(s)}))},t.handleResize=function(e){t.setContainerClasses(e.data.container,e.data.data)},t.unbindEvents=function(e){e.off("resize.tribeEvents",t.handleResize).off("beforeAjaxSuccess.tribeEvents",t.deinit)},t.bindEvents=function(e,n){e.on("resize.tribeEvents",{container:e,data:n},t.handleResize).on("beforeAjaxSuccess.tribeEvents",{container:e},t.deinit)},t.deinit=function(e,n,i){t.unbindEvents(e.data.container)},t.initTasks=function(n,i){n instanceof jQuery||(n=e(n)),t.bindEvents(n,i),t.setContainerClasses(n,i),n.data("tribeEventsBreakpoints",{initialized:!0})},t.init=function(n,i,s,a){s instanceof jQuery||(s=e(s));const o=s.data("tribeEventsBreakpoints");o&&o.initialized||t.initTasks(s,a)},t.setup=function(n){const i=e(n);if(!i.is(t.selectors.container))return;const s=i.find(t.selectors.dataScript);let a={};s.length&&(a=JSON.parse(s.text().trim())),t.initTasks(i,a)},t.ready=function(){n.on("afterSetup.tribeEvents",t.selectors.container,t.init)},e(t.ready)}(jQuery,tribe.events.views.breakpoints),window.tec=window.tec||{},window.tec.events=window.tec.events||{},window.tec.events.views=window.tec.events.views||{},window.tec.events.views.breakpoints={};
// source --> https://itancia.com/wp-content/plugins/itancia-backend/assets/js/slider.js?ver=6.9.4 
const swipedetect = (el, callback) => {
    let touchsurface = el,
        swipedir,
        startX,
        startY,
        distX,
        distY,
        threshold = 100, //required min distance traveled to be considered swipe
        restraint = 80, // maximum distance allowed at the same time in perpendicular direction
        allowedTime = 300, // maximum time allowed to travel that distance
        elapsedTime,
        startTime,
        handleswipe = callback || function(swipedir) {}

    touchsurface.addEventListener('touchstart', (e) => {
        let touchobj = e.changedTouches[0]
        swipedir = 'none'
        dist = 0
        startX = touchobj.pageX
        startY = touchobj.pageY
        startTime = new Date().getTime() // record time when finger first makes contact with surface
        // e.preventDefault()
    }, false)

    touchsurface.addEventListener('touchend', (e) => {
        let touchobj = e.changedTouches[0]
        distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
        distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
        elapsedTime = new Date().getTime() - startTime // get time elapsed
        if (elapsedTime <= allowedTime) { // first condition for awipe met
            if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint) { // 2nd condition for horizontal swipe met
                swipedir = (distX < 0) ? 'left' : 'right' // if dist traveled is negative, it indicates left swipe
            } else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint) { // 2nd condition for vertical swipe met
                swipedir = (distY < 0) ? 'up' : 'down' // if dist traveled is negative, it indicates up swipe
            }
        }
        handleswipe(swipedir)
        // e.preventDefault()
    }, false)
}

class Slider {
    constructor(slider) {
        this.slider = slider;
        this.sliderWrapper = this.slider.querySelector('.slider-wrapper');
        this.slides = this.slider.querySelectorAll('.slide');
        this.pagination = this.slider.querySelector('.slider-pagination');
        this.paginationBullets = this.pagination.querySelectorAll('.slider-pagination-bullet');
        this.totalSlides = this.slides.length;
        this.sliderNav = this.slider.querySelectorAll('.slider-nav .slider-direction');
        this.activeIndex = -1;
        this.idle = true;
        this.timer = slider.dataset.timer * 1000;
        this.autoplayMode = true;
        this.init();
    }

    removeClasses(nodeList, cssClasses) {
        for (let i = 0; i < nodeList.length; i++) {
            nodeList[i].classList.remove(...cssClasses);
        }
    }

    addClasses(nodeList, cssClasses) {
        for (let i = 0; i < nodeList.length; i++) {
            nodeList[i].classList.add(...cssClasses);
        }
    }

    autoplay() {
        if (this.autoplayMode) {
            this.interval = setInterval(() => { this.changeSlide('next') }, this.timer);
        }
    }

    stopAutoplay() {
        clearInterval(this.interval)
    }

    waitForIdle() {
        this.idle = true;
    }

    navControl() {

        swipedetect(this.sliderWrapper, (swipedir) => {
            if (this.idle) {
                let swiperDirection;
                if (swipedir == 'left') {
                    this.changeSlide('next')
                }

                if (swipedir == 'right') {
                    this.changeSlide('prev')
                }
            }

        });
        this.sliderNav.forEach((el) => {
            el.addEventListener('click', e => {
                e.preventDefault()
                if (this.autoplayMode) {
                    this.stopAutoplay()
                }

                if (this.idle) {
                    let direction = el.classList.contains('next') ? 'next' : 'prev';
                    this.changeSlide(direction);
                }
            })
        })
    }

    changeSlide(direction) {

        this.idle = false;
        this.slider.classList.remove('prev', 'next');

        if (direction == 'next') {
            this.activeIndex = (this.activeIndex + 1) % this.totalSlides;
            this.slider.classList.add('next');
        } else {
            this.activeIndex = (this.activeIndex - 1 + this.totalSlides) % this.totalSlides;
            this.slider.classList.add('prev');
        }

        this.removeClasses(this.slides, ['prev', 'active'])

        let prevItems = [...this.slides]
            .filter(item => {
                let prevIndex;
                if (this.slider.classList.contains('prev')) {
                    prevIndex = this.activeIndex == this.totalSlides - 1 ? 0 : this.activeIndex + 1;
                } else {
                    prevIndex = this.activeIndex == 0 ? this.totalSlides - 1 : this.activeIndex - 1;
                }

                return item.dataset.index == prevIndex;
            });

        //set active

        let activeItems = [...this.slides]
            .filter(item => {
                return item.dataset.index == this.activeIndex;
            });

        this.addClasses(prevItems, ['prev']);
        this.addClasses(activeItems, ['active']);

        const activeImageItem = this.slider.querySelector('.active');
        const prevImageItem = this.slider.querySelector('.prev');

        this.paginationControl();

        prevImageItem.addEventListener('transitionend', () => {
            this.waitForIdle()
        }, {
            once: true
        });

        if (!this.slider.classList.contains('loaded')) {
            setTimeout(() => {
              this.slider.classList.add('loaded')
            }, 100)
        }
        // this.slider.addEventListener('transitionend', () => {
        // 	this.slider.classList.add('done')
        // }, {
        // 	once: true
        // })
    }

    paginationSetStyle() {
        this.paginationBullets.forEach((el, i) => {
            el.style.width = (100 / this.slides.length) + '%';
        })
    }

    paginationControl() {
        //set active

        const paginationIndex = this.paginationBullets[this.activeIndex]
        this.removeClasses(this.paginationBullets, ['active'])
        paginationIndex.classList.add('active')
    }

    start() {
        this.slides.forEach((el, i) => {
            el.setAttribute('data-index', i)
        })
        this.paginationSetStyle();

        // make sure initial transition occurs
        setTimeout(() => {

            this.changeSlide('next');
            this.autoplay();
        }, 100)
    }

    init() {
        this.start()
        this.navControl();
    }
}

window.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.slider-container').forEach(el => {
        new Slider(el)
    })
});