document.addEventListener("DOMContentLoaded", function (event){
    if(!window.jQuery) return;
    if(typeof jQuery === 'undefined') return;
    if (typeof UIkit === 'undefined') return;

    var parseQueryString = function() {

        var str = window.location.search;
        var objURL = {};

        str.replace(
            new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
            function( $0, $1, $2, $3 ){
                objURL[ $1 ] = $3;
            }
        );
        return objURL;
    };

    /* SLIDE UP */
    let lenaUp = (target, duration = 500) => {

        target.style.transitionProperty = 'height, margin, padding';
        target.style.transitionDuration = duration + 'ms';
        target.style.boxSizing = 'border-box';
        target.style.height = target.offsetHeight + 'px';
        target.offsetHeight;
        target.style.overflow = 'hidden';
        target.style.height = 0;
        target.style.paddingTop = 0;
        target.style.paddingBottom = 0;
        target.style.marginTop = 0;
        target.style.marginBottom = 0;
        window.setTimeout(() => {
            target.style.display = 'none';
            target.style.removeProperty('height');
            target.style.removeProperty('padding-top');
            target.style.removeProperty('padding-bottom');
            target.style.removeProperty('margin-top');
            target.style.removeProperty('margin-bottom');
            target.style.removeProperty('overflow');
            target.style.removeProperty('transition-duration');
            target.style.removeProperty('transition-property');
            //alert("!");
        }, duration);
    }

    /* SLIDE DOWN */
    let lenaDown = (target, duration = 500) => {

        target.style.removeProperty('display');
        let display = window.getComputedStyle(target).display;
        if (display === 'none') display = 'block';
        target.style.display = display;
        let height = target.offsetHeight;
        target.style.overflow = 'hidden';
        target.style.height = 0;
        target.style.paddingTop = 0;
        target.style.paddingBottom = 0;
        target.style.marginTop = 0;
        target.style.marginBottom = 0;
        target.offsetHeight;
        target.style.boxSizing = 'border-box';
        target.style.transitionProperty = "height, margin, padding";
        target.style.transitionDuration = duration + 'ms';
        target.style.height = height + 'px';
        target.style.removeProperty('padding-top');
        target.style.removeProperty('padding-bottom');
        target.style.removeProperty('margin-top');
        target.style.removeProperty('margin-bottom');
        window.setTimeout(() => {
            target.style.removeProperty('height');
            target.style.removeProperty('overflow');
            target.style.removeProperty('transition-duration');
            target.style.removeProperty('transition-property');
        }, duration);
    }


    var nextArrow = document.querySelector('.lena-arrow.lena-next');
    var prevArrow = document.querySelector('.lena-arrow.lena-prev');
    var indicators = document.querySelectorAll('.lena-indicator[data-state]');
    var yearSelector = document.querySelectorAll('li[data-year]');
    var moreBtns = document.querySelectorAll('[data-start]');
    var lessBtns = document.querySelectorAll('[data-end]');
    var dataTables = document.querySelectorAll('.dj-data-table');

    var simulateClick = function (elem) {
        // Create our event (with options)
        var evt = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: window
        });
        // If cancelled, don't dispatch our event
        var canceled = !elem.dispatchEvent(evt);
    };

    // Slideshow custom navigation
    if (prevArrow !== null) {
        prevArrow.addEventListener('click', function (e) {
            e.preventDefault();


            var parent = this.closest('.uk-slider');
            var currentNav = parent.querySelector('.el-nav li.uk-active');

            if (currentNav.previousSibling !== null) {
                simulateClick(currentNav.previousSibling);
            }

        });
    }
    if (nextArrow !== null) {
        nextArrow.addEventListener('click', function (e) {
            e.preventDefault();


            var parent = this.closest('.uk-slider');
            var currentNav = parent.querySelector('.el-nav li.uk-active');

            if (currentNav.nextSibling !== null) {
                simulateClick(currentNav.nextSibling);
            }

        });
    }
    if (indicators.length) {
        indicators.forEach(function (indicator) {
            indicator.addEventListener('click', function (e) {

                var container = this.closest('[uk-accordion]');


                var elem = this;

                var state = this.getAttribute('data-state');
                var icon = elem.querySelector('.uk-icon');
                var txt = elem.querySelector('.indicator-text');

                switch (parseInt(state)) {
                    case 1:
                        var vissibleElements = container.querySelectorAll('.el-item[lena-visible="1"]');
                        vissibleElements.forEach(function (vissibleElement) {
                            lenaUp(vissibleElement);
                            vissibleElement.setAttribute('lena-visible', 0);
                        })

                        icon.setAttribute('uk-icon', 'icon: chevron-down');
                        txt.innerHTML = Joomla.JText._('PLG_SYSTEM_DJLENAYOO_SHOW_ALL');
                        elem.setAttribute('data-state', 0);
                        break;

                    default :
                        var hiddenElements = container.querySelectorAll('.el-item[lena-visible="0"]');
                        hiddenElements.forEach(function (hiddenElement) {
                            lenaDown(hiddenElement);
                            hiddenElement.setAttribute('lena-visible', 1);
                        })
                        icon.setAttribute('uk-icon', 'icon: chevron-up')
                        txt.innerHTML = Joomla.JText._('PLG_SYSTEM_DJLENAYOO_HIDE');
                        elem.setAttribute('data-state', 1);
                        break;
                }


            })
        })
    }
    if (yearSelector.length) {
        yearSelector.forEach(function (yearSelector) {
            yearSelector.addEventListener('click', function (e) {
                e.preventDefault();
                year = this.getAttribute('data-year');
                console.log(year);


                return false;
            })
        })
    }

    // Articles lazyloading
    var articlesLoading = false;
    if (moreBtns.length) {
        moreBtns.forEach(function (moreBtn) {
            var containerId = moreBtn.getAttribute('data-container');
            var container = document.getElementById(containerId);
            var childs = container.querySelectorAll('.el-item');
            var childsCount = childs.length;

            moreBtn.setAttribute('data-start', childsCount);
            moreBtn.setAttribute('data-limit', childsCount);

            moreBtn.addEventListener('click', function (e) {
                e.preventDefault();

                if (!articlesLoading) {
                    articlesLoading = true;

                    var start = this.getAttribute('data-start');
                    var limit = this.getAttribute('data-limit');

                    var xmlHttp = new XMLHttpRequest();
                    xmlHttp.onreadystatechange = function () {
                        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {

                            var parser = new DOMParser();
                            var xmlDoc = parser.parseFromString(xmlHttp.responseText, "text/html");


                            var responseContainer = xmlDoc.getElementById(containerId);
                            if (responseContainer !== null) {
                                var items = responseContainer.querySelectorAll('.el-item');
                                items.forEach(function (item) {

                                    var itemContainer = item.parentElement;
                                    itemContainer.style.display = 'none';
                                    itemContainer.setAttribute('data-loaded', true);


                                    if (container.querySelector('.uk-grid-stack') !== null) {
                                        container.querySelector('.uk-grid-stack').append(itemContainer);

                                    } else {
                                        container.append(itemContainer);

                                    }

                                    lenaDown(itemContainer);

                                });

                                moreBtn.setAttribute('data-start', parseInt(start) + parseInt(limit));
                            }
                            articlesLoading = false;
                        }
                    }
                    xmlHttp.open("GET", '?tmpl=template&start=' + start + '&limit=' + limit, true); // true for asynchronous
                    xmlHttp.send(null);

                    var lessBtn = moreBtn.closest('.dj-more-indicators').querySelector('[data-end]');
                    lessBtn.style.opacity = '1';

                }


                return false;
            })

        });
    }
    if (lessBtns.length) {
        lessBtns.forEach(function (lessBtn) {
            var containerId = lessBtn.getAttribute('data-container');
            var container = document.getElementById(containerId);
            var childs = container.querySelectorAll('.el-item');
            var childsCount = childs.length;

            lessBtn.addEventListener('click', function (e) {
                e.preventDefault();

                if (!articlesLoading) {
                    articlesLoading = true;

                    var items = container.querySelectorAll('[data-loaded]');
                    items.forEach(function (item) {

                        lenaUp(item);


                    });

                    var moreBtn = lessBtn.closest('.dj-more-indicators').querySelector('[data-start]');
                    moreBtn.setAttribute('data-start', moreBtn.getAttribute('data-limit'));
                    lessBtn.style.opacity = '0';
                    articlesLoading = false;
                }


                return false;
            })

        });
    }

    // Custom data tables
    if (dataTables.length) {
        dataTables.forEach(function (dataTable) {

            var options = dataTable.querySelectorAll('.nice-select li[data-value]');
            var table = dataTable.querySelector('.uk-table');


            options.forEach(function (option) {
                option.addEventListener('click', function (e) {
                    e.preventDefault();

                    var year = parseInt(this.getAttribute('data-value'));
                    if (!isNaN(year)) {
                        table.querySelectorAll('[data-year]:not([data-year="' + year + '"]').forEach(function (notMatched) {
                            console.log(notMatched);
                            notMatched.classList.add('uk-visible@m');
                        });
                        table.querySelectorAll('[data-year="' + year + '"]').forEach(function (notMatched) {
                            console.log(notMatched);
                            notMatched.classList.remove('uk-visible@m');
                        });


                    }
                });
            })
        });
    }

    document.querySelectorAll('[href="#aplikuj"]').forEach(function (appBtn) {
        appBtn.addEventListener('click', function (e) {
            var itemContainer = this.closest('.el-item');
            var itemTitle = itemContainer.querySelector('.el-title').text;


            document.querySelector('input[name="Stanowisko"]').value = itemTitle;
        })

    });

    // Show/Hide Lena filters
    var showFiltersBtn = document.querySelectorAll('.lena-show-filters-btn');
    var hideFiltersBtn = document.querySelectorAll('.lena-hide-filters-btn');

    showFiltersBtn.forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();

            var hiddenElements = document.querySelectorAll('.djc2_filters.uk-hidden');
            var hideButton = this.parentNode.parentNode.querySelector('.lena-hide-filters-btn');

            hiddenElements.forEach(function (hiddenElement) {
                hiddenElement.classList.remove('uk-hidden');
                lenaDown(hiddenElement);
            });
            hideButton.classList.remove('uk-hidden');
            this.classList.add('uk-hidden');
        })
    })

    hideFiltersBtn.forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            var hiddenElements = document.querySelectorAll('.djc2_filters');
            var showButton = this.parentNode.parentNode.querySelector('.lena-show-filters-btn');

            hiddenElements.forEach(function (hiddenElement) {
                lenaUp(hiddenElement);
                setTimeout(function () {
                    hiddenElement.classList.add('uk-hidden');
                },500);
                //

            });
            showButton.classList.remove('uk-hidden');
            this.classList.add('uk-hidden');
        })
    })

    var filters = document.querySelectorAll('.djc2_filters');
    if (filters.length) {
        filters.forEach(function (filter) {
            console.log(filter);

        });
    }


    var lazyLoadContainers = document.querySelectorAll('.dj-content-lazy-load');
    if (lazyLoadContainers.length) {
        window.addEventListener('scroll', function () {
            var scrollOffset = this.scrollY;

            lazyLoadContainers.forEach(function (lazyLoadContainer) {
                var menuOffset = lazyLoadContainer.offsetHeight + lazyLoadContainer.offsetTop;
                var isLoading = lazyLoadContainer.getAttribute('data-loading');


                if (((window.innerHeight + window.scrollY) >= menuOffset) && isLoading == null) {
                    lazyLoadContainer.setAttribute('data-loading', true);
                    var xmlHttp = new XMLHttpRequest();
                    xmlHttp.onreadystatechange = function () {

                        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {

                            var parser = new DOMParser();
                            var xmlDoc = parser.parseFromString(xmlHttp.responseText, "text/html");


                            var responseContainer = xmlDoc.getElementById(lazyLoadContainer.getAttribute('id'));
                            if (responseContainer !== null) {
                                var items = responseContainer.querySelectorAll('.el-item');
                                items.forEach(function (item) {


                                    if (lazyLoadContainer.querySelector('.uk-grid-stack') !== null) {
                                        var itemContainer = item.parentElement;

                                        lazyLoadContainer.querySelector('.uk-grid-stack').append(itemContainer);
                                        lenaDown(itemContainer);
                                    } else {
                                        item.style.display = 'none';
                                        lazyLoadContainer.append(item);
                                        lenaDown(item);
                                    }


                                });


                            }
                            setTimeout(function () {
                                lazyLoadContainer.removeAttribute('data-loading');
                            }, 1000);
                        }
                    }
                    xmlHttp.open("GET", '?tmpl=template&start=' + lazyLoadContainer.querySelectorAll('.el-item').length, true); // true for asynchronous
                    xmlHttp.send(null);
                }
            });

        });
    }

    var switcher = document.querySelector('.lena-timeline-switcher');


    var switcherUI = UIkit.switcher(switcher);
    switcherUI.swiping = false;


    // Timelie
    UIkit.util.on('.lena-timeline-switcher', 'shown', function (e) {


        var year = e.target.getAttribute('data-year');


        var currentMobileBtn = document.querySelector('.lena-year-btn[data-year="' + year + '"]');
        var previous = document.querySelector('.lena-year-btn.active');
        var index = currentMobileBtn.getAttribute('data-index');
        var timeLineNav = document.querySelector('.uk-timeline-items').parentNode;


        var timeline = UIkit.slider(timeLineNav);
        timeline.show(parseInt(index));
    });
    // Timelie
    UIkit.util.on('.uk-timeline-container', 'itemshow', function (e) {


        console.log(e);
    });


    document.querySelectorAll('.uk-timeline-prev').forEach(function (timeLinePrev) {
        timeLinePrev.addEventListener('click', function (e) {
            e.preventDefault();

            var container = this.closest('.uk-timeline-container');
            var switcher = container.querySelector('.lena-timeline-switcher');


            var switcherUI = UIkit.switcher(switcher);
            var currentTimeLineIndex = switcherUI.index();

            console.log(switcherUI);

            var currentSlider = switcher.querySelector('.el-item.uk-active [uk-slider]');
            var sliderUI = UIkit.slider(currentSlider);
            var currentSlide = sliderUI.index;
            var slidesCount = sliderUI.slides.length;

            var nextYear = container.querySelector('.uk-timeline-mobile-nav [data-index="' + (currentTimeLineIndex - 1) + '"]');
            var firstYear = container.querySelector('.uk-timeline-mobile-nav [data-index="' + (switcherUI.children.length - 1) + '"]');


            var evt = new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: window
            });


            if ((currentSlide - 1) >= 0) {
                sliderUI.show(currentSlide - 1);
            } else if (nextYear) {

                nextYear.dispatchEvent(evt);
            } else if (firstYear) {
                firstYear.dispatchEvent(evt);
            }

            // switcherUI.show(switcherUI.index()+1);
            return false;
        })
    });

    document.querySelectorAll('.uk-timeline-next').forEach(function (timeLineNext) {
        timeLineNext.addEventListener('click', function (e) {
            e.preventDefault();

            var container = this.closest('.uk-timeline-container');
            var switcher = container.querySelector('.lena-timeline-switcher');


            var switcherUI = UIkit.switcher(switcher);
            var currentTimeLineIndex = switcherUI.index();

            console.log(switcherUI);

            var currentSlider = switcher.querySelector('.el-item.uk-active [uk-slider]');
            var sliderUI = UIkit.slider(currentSlider);
            var currentSlide = sliderUI.index;
            var slidesCount = sliderUI.slides.length;

            var nextYear = container.querySelector('.uk-timeline-mobile-nav [data-index="' + (currentTimeLineIndex + 1) + '"]');
            var firstYear = container.querySelector('.uk-timeline-mobile-nav [data-index="0"]');


            var evt = new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: window
            });


            if ((currentSlide + 1) < slidesCount) {
                sliderUI.show(currentSlide + 1);
            } else if (nextYear) {

                nextYear.dispatchEvent(evt);
            } else if (firstYear) {
                firstYear.dispatchEvent(evt);
            }

            // switcherUI.show(switcherUI.index()+1);
            return false;
        })
    });


    var menuContainer = document.querySelector('.lenafloat');


    setTimeout(function (e) {
        if (menuContainer !== null) {
            var menuOffset = menuContainer.offsetTop;

            document.addEventListener('scroll', function (e) {

                var windowScroll = window.scrollY;
                var endOffset = menuContainer.clientHeight + menuOffset - window.innerHeight;
                console.log(endOffset);

                if (windowScroll > menuOffset && windowScroll < endOffset) {

                    var diff = (windowScroll - menuOffset) + 80;


                    menuContainer.style.transform = 'translateY(' + diff + 'px)';
                } else if (windowScroll < menuOffset) {
                    menuContainer.style.transform = '';
                }
            })
        }
    }, 1000);
    var contactSubject = document.querySelector('[data-yooessentials-form-field="temat"] input[type="text"]');
    if(contactSubject !== null) {
        var productTitle = document.querySelector('#djcatalog h1.uk-h1');
        if(productTitle !== null) {
            console.log(contactSubject);
            contactSubject.value = productTitle.innerHTML.trim();
        }
    }


    if (typeof UIkit !== 'undefined') {
        // UI Kit slideshow counter
        UIkit.util.on('.uk-slideshow, .uk-slider', 'itemshown', function (e) {

            var counter = this.querySelector('.dj-counter-nav-current');
            var total = this.querySelector('.dj-counter-nav-total');

            if (total !== null) {
                var current = (e.detail[0].index + 1);

                if (parseInt(current) <= parseInt(total.innerHTML)) {
                    counter.innerHTML = current;
                }
            }

        });
    }
    var params = parseQueryString();
    // alert(params["foo"]);
    if(typeof params['mapa'] !== 'undefined') {

        var tabs = document.querySelectorAll('#lena-mapa-switcher > ul.uk-tab li');
        if(tabs.length) {
            tabs.forEach(function (tab) {
                if(tab.textContent.trim() == decodeURI(params['mapa']).trim()) {
                    tab.querySelector('a').click();
                    tab.querySelector('a').scrollIntoView();
                }

            })
        }
    }
});

jQuery(document).ready(function () {


    // Baza wiedzy
    jQuery('#baza_wiedzy li').on('click', function (e) {


        var link = jQuery(e.target).find("a.el-link");

        if (link.length) {
            console.log(link);
            link[0].click();
        }

    })

    var forms = jQuery('.lena-filters-form');
    var lenaFilters = forms.find('.lena-filter-column');

    // Select option in hidden select
    lenaFilters.on('click', '.sd-select .option', function (e) {
        e.preventDefault();

        var self = jQuery(this);

        var selectContainer = self.closest('.lena-filter-column');
        var select = selectContainer.find('.lena-filter-select').first();
        var optionId = parseInt(self.attr('data-id'));


        var selectOption = select.find('option[value' + ((isNaN(optionId)) ? '' : '=' + optionId) + ']');

        var optionIsChecked = (selectOption.attr('selected') == 'selected');
        console.log(optionIsChecked);
        if (optionIsChecked) {
            selectOption.removeAttr('selected');
        } else {
            selectOption.attr('selected', !optionIsChecked);
        }


        self.trigger('nice-select:update');
        if (!(event.ctrlKey || event.metaKey)) {
            self.closest('form.lena-filters-form').trigger('submit');
        }
        return false;
    })

    // Remove selected filter
    forms.on('click', '.sd-tag[data-attribute][data-option]', function (e) {
        e.preventDefault();

        var self = jQuery(this);

        var attributeId = self.attr('data-attribute');
        var attributeValue = self.attr('data-option');

        var select = forms.find('select[data-attribute=' + attributeId + ']');
        var option = select.find('option:selected[value=' + attributeValue + ']');

        option.removeAttr('selected');
        var filterContainer = option.closest('.lena-filter-column');
        var form = filterContainer.closest('.lena-filters-form');


        filterContainer.trigger('nice-select:update');
        self.remove();
        filterContainer.trigger('nice-select:update');
        form.trigger('filter-counter:refresh');
        if (!(event.ctrlKey || event.metaKey)) {
            select.closest('form.lena-filters-form').trigger('submit');
        }
    })

    // Remove all filters
    forms.on('click', '.lena-clear-tags', function (e) {
        e.preventDefault();

        var form = jQuery(this).closest('form.lena-filters-form');
        var selectedFilters = form.find('option:selected');

        selectedFilters.removeAttr('selected');
        form.trigger('submit');


    })

    // Update filters counter
    jQuery(document).on('filter-counter:refresh', '.lena-filters-form', function (e) {
        var self = jQuery(this);


        var tagsContainer = self.find('.sd-filter-tags').first();
        var counter = tagsContainer.find('.sd-tags-counter').first();
        var childs = tagsContainer.find('[data-attribute][data-option]');

        counter.text(childs.length);
    })

    // Update single filter label
    jQuery(document).on('nice-select:update', '.lena-filter-column', function (e) {
        var self = jQuery(this);


        var select = self.find('.lena-filter-select').first();


        var options = select.find('option');

        var textValues = [];

        options.each(function (index) {
            var optionValue = jQuery(this).attr('value');
            var optionIsChecked = !(typeof jQuery(this).attr('selected') == 'undefined');
            var niceSelectOption = self.find('.sd-select .option[data-id' + ((!isNaN(parseInt(optionValue)) ? '=' + optionValue : '')) + ']').first();

            if (optionIsChecked) {
                textValues.push(jQuery(this).text());

                if (!niceSelectOption.hasClass('selected')) {
                    niceSelectOption.addClass('selected');
                    niceSelectOption.addClass('focus');
                }


            } else if (!optionIsChecked && niceSelectOption.hasClass('selected')) {
                niceSelectOption.removeClass('selected');
                niceSelectOption.removeClass('focus');
            }


        });

        var label = select.attr('data-label');

        if (textValues.length > 0) {
            label = label + ' - ' + textValues.splice(',');
        }

        self.find('.sd-select .current').text(label);
    })

    // Optimize request
    forms.on('submit', function (e) {
        e.preventDefault();

        var formAction = jQuery(this).attr('action');
        var formData = jQuery(this).serializeArray();
        var request = {};
        var uri = '';


        formData.forEach(function (data) {
            if (typeof request[data.name] == 'undefined') {
                request[data.name] = [data.value];
            } else {
                request[data.name].push(data.value);
            }

        });

        var initialized = false;
        for (const [key, value] of Object.entries(request)) {
            if (!initialized) {
                uri += `?${key}=${value}`;
                initialized = true;
            } else {
                uri += `&${key}=${value}`;
            }


        }

        window.location.replace(formAction + uri + '#lena-breadcrumb-container');

        return false;
    })


    UIkit.util.on('#lena-products-table-container', 'shown', function (e) {

        var btns = jQuery('.lena-toggle-datatable');
        btns.find('.uk-icon').attr('uk-icon', 'chevron-up');
        btns.find('.uk-text-middle').text(Joomla.JText._('PLG_DJLENAYOO_HIDE_FILTERS'));


    });

    UIkit.util.on('#lena-products-table-container', 'hidden', function (e) {

        var btns = jQuery('.lena-toggle-datatable');
        btns.find('.uk-icon').attr('uk-icon', 'chevron-down');
        btns.find('.uk-text-middle').text(Joomla.JText._('PLG_DJLENAYOO_SHOW_FILTERS'));


    });



});




jQuery(document).on('click', '.uk-timeline-mobile-nav li', function (e) {
    var span = e.currentTarget.querySelector('span');
    var year = span.getAttribute('data-year');
    var index = span.getAttribute('data-index');
    console.log(parseInt(index));


    var evt = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window
    });
    // If cancelled, don't dispatch our event
    var canceled = !document.querySelector('.uk-timeline-nav a[data-year="' + year + '"]').dispatchEvent(evt);

    return false;
})


jQuery(document).on('click', '.lena-lazy-btn', function (e) {
    e.preventDefault();
    var container = jQuery(this).prev();
    var step = container.attr('data-step');
    var childs = container.find('.el-item.uk-hidden');
    var childsLen = childs.length;

    var currentStep = 0;
    childs.each(function (i, obj) {
        obj.classList.remove('uk-hidden');

        currentStep++;
        childsLen--;
        if (currentStep >= step) return false;
    });


    if (childsLen === 0) {
        jQuery(this).hide();
    }


    return false;
})
