;(function ($) {  

    'use strict';

    function woostifyClosePopup() {
        var popups = document.querySelectorAll('.woostify-popup');

        if ( popups.length == 0 ) {
            return;
        }

        popups.forEach(function (popup) {
            
            var popup_toggle_close = popup.querySelector('.woostify-popup-toggle-close');
            
            var popup_setting = popup.getAttribute('data-popup-setting');
            var popup_data_json = JSON.parse(popup_setting);
            var popupClosed = (popup_setting != null )? popup_data_json.popupClosed : '';

            var popup_data = popup.getAttribute('data-woostify-popup');
            var popup_data_arr = ( popup_data != '')? popup_data.split(':') : '' ;
            var popup_id = ( popup_data_arr != '' )? popup_data_arr[1] : '';

            var localStorageKey = 'popup_opened_id_' + popup_id; 
            var localStorageValue = popupClosed;

            if (popupClosed === 'off') {
                localStorage.setItem( localStorageKey, localStorageValue );
            }

            if ( popup_toggle_close ) {
 
                popup_toggle_close.addEventListener('click', function (e) {

                    if (popupClosed === 'on') {
                        localStorage.setItem( localStorageKey, localStorageValue );
                    }

                    closePopup(popup);

                });
            }

            popup.addEventListener('click', function (e) {

                var target = e.target;
                if (target.closest('.woostify-popup-lightbox')) {
                    return;
                }

                closePopup(popup);
                
            });
   
        });

    }

    function closePopup( popup ) { 

        if( !popup.classList.contains('active') ){
            return;
        }

        var popup_inner = popup.querySelector('.woostify-popup-inner');
        var popup_data = popup.getAttribute('data-popup-setting');
        var popup_data_json = JSON.parse(popup_data);
        var popupScrollLock = popup_data_json.popupScrollLock;
        var animationDuration = popup_data_json.animationDuration;
        var closeAnimation = popup_data_json.closeAnimation;

        popup_inner.classList.add( closeAnimation );
        popup_inner.classList.add('reverse');
        setTimeout(() => {
            popup_inner.classList.remove(closeAnimation);
            popup_inner.classList.remove('reverse');
            popup.classList.remove('active');
            document.body.style.overflow = '';
        }, animationDuration * 1000 );

    }

    function woostifyOpenPopup() {  
        var popups = document.querySelectorAll('.woostify-popup');

        if ( popups.length == 0 ) {
            return;
        }

        popups.forEach( function ( popup ) {

            var popup_data = popup.getAttribute('data-woostify-popup');
            var popup_data_arr = ( popup_data != '')? popup_data.split(':') : '' ;
            var popup_id = ( popup_data_arr != '' )? popup_data_arr[1] : '';

            var localStorageKey = 'popup_opened_id_' + popup_id;
            var localStorageValue = localStorage.getItem( localStorageKey  );
     
            if ( localStorageValue !== 'on' ) {
                var popup_action = popup.getAttribute('data-popup-action');
   
                if ( popup_action ) {
                    switch( popup_action ) {
                        case 'on-page-load':
                            woostifyPopupOnPageLoad( popup );
                            break;
                        case 'on-click':
                            woostifyPopupOnClick( popup );
                            break;
                        case 'on-scroll':
                            woostifyPopupOnScroll( popup );
                            break;
                        case 'on-scroll-to-element':
                            woostifyPopupOnScrollToElement( popup );
                            break;   
                        case 'on-after-inactivity':
                            woostifyPopupOnAfterInactivity( popup );
                            break; 
                        case 'on-page-exit-intent':
                            woostifyPopupOnPageExitIntent( popup );
                            break;
                        default:
                            break;
                    }
                }
            }

            


        });
    }

    function openPopup( popup ) {
        var popup_inner = popup.querySelector('.woostify-popup-inner');
        var popup_data = popup.getAttribute('data-popup-setting');
        var popup_data_json = JSON.parse(popup_data);
        var popupScrollLock = popup_data_json.popupScrollLock;
        var openAnimation = popup_data_json.openAnimation;
        var animationDuration = popup_data_json.animationDuration;
        var animationDurationTime = parseInt(animationDuration) * 1000;

        if ( popupScrollLock == 'scroll-lock') {
            document.body.style.overflow = 'hidden';
        }

        popup.classList.add('active');
        popup_inner.classList.add(openAnimation);
        setTimeout(() => {
            popup_inner.classList.remove(openAnimation);
        },  animationDurationTime );
    }

    function woostifyPopupOnClick( element ) {
        var popup = element;

        var popup_data = popup.getAttribute('data-popup-setting');
        var popup_data_json = JSON.parse(popup_data);
        var popupModeAction = popup_data_json.popupModeAction;
        var onClickCount = 0;
        var onElementClass = '';
        var popup_id = popup.getAttribute('id');
        if ( ( Object.keys(popupModeAction).length != 0 ) ) {
            onClickCount = popupModeAction.onClickCount;
            onElementClass = popupModeAction.onElementClass;
        }
        localStorage.setItem(popup_id, onClickCount);
        
        if ( popup.classList.contains('active') ) {
            return;
        }

        var woostifyHandler = function (e) {
            e.preventDefault();

            var target = e.target;
            var popup_lightbox = target.closest('.woostify-popup-lightbox');
            var popup_on_click_count = localStorage.getItem(popup_id);
     
            if ( popup_lightbox ) {
                return;
            }
            
            if ( popup_on_click_count > 0) {
                return;
            }
            
            openPopup(popup);
            onClickCount = 1;
            localStorage.setItem(popup_id, onClickCount);

        };

        if ( onElementClass != '') { 
            document.querySelector(onElementClass).addEventListener('click', woostifyHandler);
        }else{
            document.addEventListener('click', woostifyHandler);
        }

    }

    function woostifyPopupOnPageLoad( element ) {
        var popup = element;
        openPopup(popup);
    }

    function woostifyPopupOnScroll( element ) {  
        var popup = element;

        var popup_data = popup.getAttribute('data-popup-setting');
        var popup_data_json = JSON.parse(popup_data);
        var popupModeAction = popup_data_json.popupModeAction;
        var popupScrollDistance = -1;
        var popupScrollOffset = 0;
        var isUp = false;
    
        if ( Object.keys(popupModeAction).length != 0 ) {
            popupScrollDistance = popupModeAction.scrollDistance;
            popupScrollOffset = popupModeAction.scrollOffset;
            isUp = (popupModeAction.scrollDirection == 'up')? true : false;
        }
        
        let currentScrollY = scrollY;
        
        var woostifyHandler = ( event ) => {
            let scrollOffset = popupScrollOffset;

            if (popupScrollDistance.toString().indexOf('px') > -1) {
                scrollOffset = parseFloat(scrollOffset);
            }

            if (popupScrollDistance.toString().indexOf('%') > -1) {
                let body = document.body;
                let html = document.documentElement;

                let height = Math.max(
                    body.scrollHeight,
                    body.offsetHeight,
                    html.clientHeight,
                    html.scrollHeight,
                    html.offsetHeight
                );
                
                scrollOffset = (parseFloat(scrollOffset) / 100) * height;
            }

            if (popupScrollDistance.toString().indexOf('vh') > -1) {
                let innerHeight = window.innerHeight;
                scrollOffset = (parseFloat(scrollOffset) / 100) * innerHeight;
            }

            if (isUp) {
                if (scrollY > currentScrollY) {
                    currentScrollY = scrollY;
                } else {
                    if (Math.abs(currentScrollY - scrollY) > scrollOffset) {
                        openPopup(popup);
                        window.removeEventListener(
                            'scroll',
                            woostifyHandler,
                            true
                        );
                    }
                }
            } else {
                if (scrollOffset <= scrollY) {
                    openPopup(popup);
                    window.removeEventListener(
                        'scroll',
                        woostifyHandler,
                        true
                    );
                }
            }
        }

        window.addEventListener('scroll', woostifyHandler, true);
       
    }

    function checkVisible(elm) {
        var rect = elm.getBoundingClientRect();
        var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
        return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
    }

    function woostifyPopupOnScrollToElement( element ) {  
        var popup = element;

        var popup_data = popup.getAttribute('data-popup-setting');
        var popup_data_json = JSON.parse(popup_data);
        var popupModeAction = popup_data_json.popupModeAction;
        var scrollToElement = '';

        if( Object.keys(popupModeAction).length != 0 ){
            scrollToElement = popupModeAction.scrollToElement ;
        } 

        var selector = document.querySelector(scrollToElement);
   
        if ( !selector ) {
            return;
        }

        var woostifyHandler = function (event) {  
         
            if ( !checkVisible(selector) ) {
                return;
            }

            openPopup(popup);
            window.removeEventListener('scroll', woostifyHandler, true);

        }

        window.addEventListener('scroll', woostifyHandler, true);
       
    }

    function woostifyPopupOnAfterInactivity( element ) {  
        var popup = element;

        var popup_data = popup.getAttribute('data-popup-setting');
        var popup_data_json = JSON.parse(popup_data);
        var popupModeAction = popup_data_json.popupModeAction;
        var afterInactivityTime = 10;

        if ( Object.keys(popupModeAction).length != 0 ) {
            afterInactivityTime = popupModeAction.afterInactivityTime;
        }
        
        var afterInactivityTimeSecond = parseInt(afterInactivityTime) * 1000;

        setTimeout(()=>{
            openPopup(popup);
        }, afterInactivityTimeSecond );
       
    }

    function woostifyPopupOnPageExitIntent( element ) {  
        var popup = element;

        var woostifyHandler = ( event ) => {
            if (
                event.clientY <= 0 ||
                event.clientX <= 0 ||
                event.clientX >= window.innerWidth ||
                event.clientY >= window.innerHeight
            ) {
                
                openPopup(popup);
                document.removeEventListener('mouseout', woostifyHandler);

            }
        }

        document.addEventListener('mouseout', woostifyHandler);
       
    }

    

    function woostifyBuilderAddonPopup() {
        woostifyOpenPopup();
        woostifyClosePopup();
    }

    document.addEventListener(
        'DOMContentLoaded',
        function() {
            woostifyBuilderAddonPopup();
        }
    );

})(jQuery);