/**
 * Popups frontend.js
 */

(function() {
    
    if (typeof $ === 'undefined') $ = jQuery;
    $(function() {
        popups.init();
    } );

} )(jQuery);

var popups = new function() {
    
    this.on_init = [];
    this.on_scroll = [];
    this.on_idle = [];
    this.on_exit = [];

    this.init = function() {

        $('.popups .popup').each(function() {
            var show_popup = true;
            var conditions = $(this).data('conditions');
            // console.log(conditions);
            if (show_popup && conditions.delay != 'off') {
                // check delay condition
                show_popup = false;
                var count = sessionStorage.getItem('count');
                if (!count) count = 0; 
                if (parseInt(count) > parseInt(conditions.delay)) show_popup = true;
            }
            if (show_popup && conditions.referer != 'off') {
                // check referer condition
                show_popup = false;
                var is = document.referrer;
                var should = conditions.referer.value;
                if (conditions.referer.condition === "is") {
                    if (should === is) show_popup = true;
                } 
                else if (conditions.referer.condition === "is_not") {
                    if (should !== is) show_popup = true;
                } 
                else if (conditions.referer.condition === "has") {
                    if (is.indexOf(should) > -1) show_popup = true;
                } 
                else if (conditions.referer.condition === "has_hot") {
                    if (is.indexOf(should) == -1) show_popup = true;
                }
            }
            if (conditions.device != 'off' || conditions.browser != 'off') {
                // check device/browser condition
                compatibility.check();
                var me = $('html').data('device');
                if (show_popup && conditions.device != 'off') {
                    show_popup = false;
                    if (conditions.device.indexOf(me.system) > -1) show_popup = true;
                }
                if (show_popup && conditions.browser != 'off') {
                    show_popup = false;
                    if (conditions.browser.indexOf(me.browser) > -1) show_popup = true;
                }
            }
            
            if (show_popup) {
                var trigger = $(this).data('trigger');
                // console.log(trigger);
                if (trigger.on_init != 'off') {
                    popups.on_init.push(this);
                    var that = this;
                    setTimeout(function() {
                        popups.maybe_open(that);
                    }, trigger.on_init*1000);
                }
                if (trigger.on_scroll != 'off') {
                    popups.on_scroll.push(this);
                }
                if (trigger.on_idle != 'off') {
                    popups.on_idle.push(this);
                }
                if (trigger.on_exit != 'off') {
                    popups.on_exit.push(this);
                }
            }
            else $(this).remove();
        });

        // set will-change if necessary
        if ( $('.popups .popup .popup_overlay[data-effect]').length > 0 ) {
            $('body .navigation .header_wrapper').css('will-change', 'filter');
        }

        var lastScroll = $(document).scrollTop();
        $(window).on('scroll', function(event) {
            var scroll_pos = $(document).scrollTop();
            var scroll_max = $(document).height()-$(window).height();
            // console.log(scroll_pos);
            // console.log(scroll_max);
            var dir = 'down';
            if (scroll_pos < lastScroll) dir = 'up';
            // console.log(dir);
            $.each(popups.on_scroll, function() {
                var trigger = $(this).data('trigger');
                var scroll_trigger = trigger.on_scroll.replace('px','');
                if (scroll_trigger.indexOf('%') > -1) 
                    scroll_trigger = scroll_max*(scroll_trigger.replace('%','')/100.0);
                // console.log(scroll_trigger);
                if ((scroll_pos > scroll_trigger && lastScroll < scroll_trigger && dir == 'down'))
                    popups.open(this);
                // if ((scroll_pos < scroll_trigger && lastScroll > scroll_trigger && dir == 'up'))
                //     popups.open(this);
            });
            lastScroll = scroll_pos;
        });
        
        var timer = []
        $(window).on('mousemove', function(event) {
            // console.log("abort idle timer");
            $.each(timer, function() {
                clearTimeout(this);
            });
            $.each(popups.on_idle, function() {
                var trigger = $(this).data('trigger');
                var that = this;
                var timeout = setTimeout(function() {
                    popups.open(that);
                }, trigger.on_idle*1000);
                
                var index = timer.indexOf(timeout);
                if (index > -1) timer[index] = timeout;
                else timer.push(timeout);
            });
        });
        
        $(window).on('mouseout', function(event) {
            event = event ? event : window.event;
            var from = event.relatedTarget || event.toElement;
            if ( (!from || from.nodeName == "HTML") && event.clientY <= 100 ) {
                // console log("left top bar");
                $.each(popups.on_exit, function() {
                    popups.open(this);
                });
            }
        });

        /**
         * Open popup on click (custom)
         * @example https://www.website.de/site/?open-popup=search
         * @param {int|string} 'open-popup' Set this URL-parameter with the popup post-id or slug.
         */
        $('[href*="open-popup="]').on('click keyup', function(e) {
            e.preventDefault();
            var match = $(this).attr('href').match(/open-popup=[^#&?]+/);
            if (match) {
                var slugOrID = match[0].replace('open-popup=', '');
                openGreydPopup( slugOrID );
            }
        })
    }

    this.maybe_open = function(el) {
        var popup = $(el);
        // console.log("maybe open popup "+popup.attr('id'));
        index = -1;
        $.each(popups.on_init, function() {
            if ($(this).attr('id') == popup.attr('id')) 
                index = popups.on_init.indexOf(this);
        });
        if (index > -1) popups.open(el);
    }
    this.open = function(el) {
        if ($('html').hasClass('not_compatible')) return;
        
        var popup = $(el);
        var overlay = popup.find('.popup_overlay');
        var wrapper = popup.find('.popup_content .popup_wrapper');
        // console.log("open popup "+popup.attr('id'));

        if (popup.hasClass('hidden')) {
            popup.removeClass('hidden');
            
            if (typeof nav !== 'undefined' && typeof nav.closeMenus === 'function' ) nav.closeMenus();

            var busy = popup.data('busy');
            if (typeof busy !== 'undefined' && busy == 'yes') return;
            popup.data('busy', 'yes');
    
            // animate
            setTimeout( function() {
                var anim = popup.data('anim_type');
                var time = 0;
                if (typeof anim !== 'undefined') {
                    time = popup.data('anim_time');
                    var opacity = overlay.data('opacity');
                    if (anim == 'fade') {
                        popup.css( {"opacity": '1'} );
                    }
                    else if (anim.indexOf('slide_') == 0) {
                        overlay.css( {"top": '0', "left": '0', "opacity": opacity} );
                        popup.css( {"top": '0', "left": '0'} );
                    }
                    else {
                        var dur_old = wrapper.css('transition-duration');
                        var dur = (time/1000.0);
                        if (anim == 'scale')
                            wrapper.css('transform', 'scale(1)');
                        else if (anim == 'flip_vertical')
                            wrapper.css('transform', 'rotateY(0deg)');
                        else if (anim == 'flip_horizontal')
                            wrapper.css('transform', 'rotateX(0deg)');
                        else if (anim == 'flip_3d')
                            wrapper.css('transform', 'rotate3d(1,1,1,0) scale(1)');
                        overlay.css( {"opacity": opacity} );
                    }
                }
                // overlay
                var effect = overlay.data('effect');
                if (typeof effect !== 'undefined') {
                    popups.addFilter(effect, time);
                }
                var noscroll = overlay.data('noscroll');
                if (typeof noscroll !== 'undefined' && noscroll === true) {
                    popups.blockScroll(popup.attr('id'));
                }
                
                var highest = popup.data('highest');
                if (typeof highest !== 'undefined' && highest === true) {
                    // console.log("close all with lower prio");
                    var current = popup;
                    while (current.prev().length > 0) {
                        current = current.prev();
                        popups.close(current);
                    }
                }
                var hashtag = popup.data('hashtag');
                if (typeof hashtag !== 'undefined' && hashtag === true) {
                    window.location.hash = popup.attr('name');
                }
                
                setTimeout(function() {
                    popup.data('busy', 'no');
                }, time);
            }, 0 );
        }
    }

    this.btnClose = function(el) {
        if (typeof nav !== 'undefined' && typeof nav.checkKey === 'function' && nav.checkKey(event)) return true;
        this.close(el);
    }
    this.close = function(el) {
        var popup = $(el).closest('.popup');
        var overlay = popup.find('.popup_overlay');
        var wrapper = popup.find('.popup_content .popup_wrapper');
        // console.log("close popup "+popup.attr('id'));

        if (!popup.hasClass('hidden')) {

            var busy = popup.data('busy');
            if (typeof busy !== 'undefined' && busy == 'yes') return;
            popup.data('busy', 'yes');
    
            // animate
            var anim = popup.data('anim_type');
            var time = 0;
            if (typeof anim !== 'undefined') {
                time = popup.data('anim_time');
                if (anim == 'fade') {
                    popup.css( {"opacity": '0'} );
                }
                else if (anim.indexOf('slide_') == 0) {
                    if (anim == 'slide_top') {
                        overlay.css( {"top": '100%', "opacity": '0'} );
                        popup.css( {"top": '-100%'} );
                    }
                    else if (anim == 'slide_bottom') {
                        overlay.css( {"top": '-100%', "opacity": '0'} );
                        popup.css( {"top": '100%'} );
                    }
                    else if (anim == 'slide_left') {
                        overlay.css( {"left": '100%', "opacity": '0'} );
                        popup.css( {"left": '-100%'});
                    }
                    else if (anim == 'slide_right') {
                        overlay.css( {"left": '-100%', "opacity": '0'} );
                        popup.css( {"left": '100%'} );
                    }
                }
                else {
                    var dur_old = wrapper.css('transition-duration');
                    var dur = (time/1000.0);
                    if (anim == 'scale')
                        wrapper.css('transform', 'scale(0)');
                    else if (anim == 'flip_vertical')
                        wrapper.css('transform', 'rotateY(-90deg)');
                    else if (anim == 'flip_horizontal')
                        wrapper.css('transform', 'rotateX(-90deg)');
                    else if (anim == 'flip_3d')
                        wrapper.css('transform', 'rotate3d(1,1,1,240deg) scale(0)');
                    overlay.css( {"opacity": '0'} );
                }
                setTimeout( function() { popup.addClass('hidden') }, time );
            }
            else {
                popup.addClass('hidden');
            }

            // overlay
            var effect = overlay.data('effect');
            if (typeof effect !== 'undefined') {
                popups.removeFilter(effect, time);
            }
            var noscroll = overlay.data('noscroll');
            if (typeof noscroll !== 'undefined' && noscroll === true) {
                popups.unblockScroll(popup.attr('id'));
            }
            
            var once = popup.data('once');
            if (typeof once !== 'undefined' && once === true) {
                setTimeout(function() {
                    var cookiename = popup.data('cookie');
                    if ( cookiename && cookiename.length > 0 ) {
                        document.cookie = cookiename+"=true;"+( $("html").hasClass("ie") ? "" : " expires=0;")+" path=/";
                    }
                    // console.log("deleting popup ... "+popup.attr('name'));
                    popups.remove(popup);
                }, time);
            }

            const videos = popup[0].querySelectorAll(".wp-block-video video, .wp-block-embed iframe");
            if ( NodeList.prototype.isPrototypeOf(videos) ) {
                videos.forEach(video => {
                    if (video.tagName == "VIDEO") video.pause();
                    if (video.tagName == "IFRAME") {
                        const src = video.src;
		                video.src = src;
                    }
                });
            }

            setTimeout(function() {
                popup.data('busy', 'no');
            }, time);
        }
    }

    this.btnToggle = function(el) {
        if (typeof nav !== 'undefined' && typeof nav.checkKey === 'function' && nav.checkKey(event)) return true;
        this.toggle(el);
    }
    this.toggle = function(el) {
        if ( $(el).hasClass('hidden') )
            popups.open(el);
        else
            popups.close( $(el).children()[0] );
    }

    this.remove = function(popup) {
        var id = popup.attr('id');
        var index = -1;
        $.each(popups.on_scroll, function() {
            if ($(this).attr('id') == id) index = popups.on_scroll.indexOf(this);
        });
        if (index > -1) popups.on_scroll.splice(index, 1);
        index = -1;
        $.each(popups.on_idle, function() {
            if ($(this).attr('id') == id) index = popups.on_idle.indexOf(this);
        });
        if (index > -1) popups.on_idle.splice(index, 1);
        index = -1;
        $.each(popups.on_exit, function() {
            if ($(this).attr('id') == id) index = popups.on_exit.indexOf(this);
        });
        if (index > -1) popups.on_exit.splice(index, 1);
        index = -1;
        $.each(popups.on_init, function() {
            if ($(this).attr('id') == id) index = popups.on_init.indexOf(this);
        });
        if (index > -1) popups.on_init.splice(index, 1);
        popup.remove();
    }
    
    this.addFilter = function(effect, time) {
        var filters = $('section.popups').data('filter');
        if (typeof filters === 'undefined') filters = [];
        filters.push(effect);
        var index = filters.indexOf('none');
        if (index > -1) filters.splice(index, 1);
        // console.log(filters);

        $('section.popups').data('filter', filters);
        popups.setFilter(filters.join(' '), time);
    }
    this.removeFilter = function(effect, time) {
        var filters = $('section.popups').data('filter');
        if (typeof filters === 'undefined') filters = [];
        var index = filters.indexOf(effect);
        if (index > -1) filters.splice(index, 1);
        // console.log(filters);

        $('section.popups').data('filter', filters);
        if (filters.length == 0) filters = 'none';
        else filters = filters.join(' ');
        popups.setFilter(filters, time);
    }
    this.setFilter = function(filters, time) {
        var dur_old = $('body .main').css('transition-duration');
        var dur = (time/1000.0);
        $('body .main').css('transition-duration', dur+'s');
        $('body .navigation .header_wrapper').animate( {"transition-duration": dur+'s'}, 0, function() { 
            $('body .navigation .header_wrapper, body .main').css('filter', filters);
            setTimeout(function() {
                $('body .navigation .header_wrapper, body .main').css('transition-duration', dur_old);
            }, time+1);
        } );
    }

    this.blockScroll = function(id) {
        var blocker = $('section.popups').data('noscroll');
        if (typeof blocker === 'undefined') blocker = [];
        blocker.push(id);

        $('section.popups').data('noscroll', blocker);
        $('body').css('overflow', 'hidden');
    }
    this.unblockScroll = function(id) {
        var blocker = $('section.popups').data('noscroll');
        if (typeof blocker === 'undefined') blocker = [];
        var index = blocker.indexOf(id);
        if (index > -1) blocker.splice(index, 1);

        $('section.popups').data('noscroll', blocker);
        if (blocker.length == 0) $('body').css('overflow', 'auto');
        else $('body').css('overflow', 'hidden');
    }

}

/**
 * Open a GREYD.Popup by id or slug.
 * @param {mixed} popup Slug, ID or jQuery-object of the popup
 */
function openGreydPopup ( popup ) {
    if ( typeof popup === 'object' && popup.length ) {
        popups.open( popup );
    }
    else {
        var el = $( '#popup_'+popup );
        if ( !el.length ) {
            el = $( '.popup[name='+popup+']' );
        }
        if ( !el.length ) {
            el = $( '.popup[name='+popup.toLowerCase()+']' );
        }
        if ( el.length ) popups.open( el );
    }
}