/**
 * Created by Valavanis on 28/12/2016.
 */

$.extend( window.ef_navbar = function(){
    return ef_navbar.init();
}, {

    init: function(){
        this.groupKey();
        this.dropLists();
        this.nestedDropLists();
        this.notifications();
        this.communication();
        this.roleAccounts();
        this.handleDroplistMaxSize();
        this.gamificationPoints();
        this.calendarEvents();
        this.timeoutTimer();
        this.languageSelector();
        this.hideLogoOnSmallScreens();
        return this;
    },

    languageSelector: function() {
        $('.ef-language-select').on('click', function(evt) {
            evt.preventDefault();
                $.fn.efront('setEfrontCookie', 'selected_language', $(this).data('lang'), { 'path':'/' });
                $.fn.efront( "ajax", $.fn.efront( "url", { ctg:'start',ajax:1,lang:$(this).data('lang')}), { }, function(response, textStatus, jqXHR) {
                    location.reload();
                }, function(response, textStatus, jqXHR) {
                    location.reload();
                });
            // location = location;
        });
    },

    timeoutTimer: function () {
        const timeoutContainer = $('#ef-timeout-timer-container');
        if (timeoutContainer.length == 0) {
            return;
        }

        const dropdownTimer = timeoutContainer.find('.ef-timeout-timer-dropdown');
        const navbarTimer = timeoutContainer.find('.ef-timeout-timer-navbar');
        const hasNavbarTimer = navbarTimer.length > 0;

        const timeout = parseInt(timeoutContainer.data('timeout')) * 1000;
        const tenminutes = 600000;
        const onehour = 3600000;
        const slowInterval = 60000; // 1m
        const fastInterval = 1000; // 1s

        let lastRefresh = Date.now();
        let timeleft = timeout;
        let modalShown = false;
        let refreshFlag = false;
        let attemptedLogout = false;
        let isVisible = false;

        const showModalWhen = Math.max(20000, 0.1 * timeout);
        const checkLastAccessWhen = Math.max(30000, 0.15 * timeout);

        let timer = setTimeout(intervalCallback, getInterval());

        const obs = new IntersectionObserver(obsCallback);
        obs.observe(dropdownTimer[0]);

        timeoutContainer.find('.refresh-button').on('click', function (evt) {
            evt.stopPropagation();
            reset();
        });

        timeoutContainer.find('.timeout-dropdown-toggle').on('click', function (evt) {
            timeleft = lastRefresh + timeout - Date.now();
            renderCountdown(dropdownTimer);
        });

        renderCountdown(dropdownTimer);
        renderNavbarCountdown();

        function renderCountdown(element){
            element.text(moment.utc(timeleft).format('HH:mm:ss'));
            element.attr('datetime', moment.utc(timeleft).format('[PT]H[H]m[M]s[S]'));
        }

        function renderNavbarCountdown () {
            if (hasNavbarTimer) {
                if (timeleft < onehour) {
                    navbarTimer.show();
                    renderCountdown(navbarTimer);
                } else {
                    navbarTimer.hide();
                }
            }
        }

        function intervalCallback () {
            timeleft = lastRefresh + timeout - Date.now();

            if (isVisible) {
                renderCountdown(dropdownTimer);
            }

            renderNavbarCountdown();

            if (timeleft <= checkLastAccessWhen && !refreshFlag) {
                checkLastAccessed();
            }
            else if (timeleft <= showModalWhen && !modalShown) {
                $.fn.efront('confirm', {
                    'body': $.fn.efront('translate', 'You seem to be away from your device. For security reasons, unless you choose to continue, you will be automatically signed out of the platform in #time#',
                    {time: '<b><time id="counter-time-out" role="timer"></time></b>'}),
                    'title': $.fn.efront('translate', 'Idle notice - Session sign out'),
                    'success': {
                        'class_name': 'btn-primary',
                        "label": $.fn.efront('translate', 'Continue using portal'),
                        'callback': function() {
                            reset();
                        }
                    },
                    'fail': {
                        "label": $.fn.efront('translate', 'Sign out now'),
                        'callback': function () {
                            attemptedLogout = true;
                            window.location = $.fn.efront('url', { ctg: 'logout', inactivity: timeout / 1000 });
                        }
                    }
                });
                modalShown = true;
            }

            if (modalShown) {
                const counterTimeOut = $('#counter-time-out');
                renderCountdown(counterTimeOut);
            }

            if (timeleft <= 0) {
                checkLastAccessed();
            }

            if (!attemptedLogout) {
                scheduleInterval();
            }
        }

        function reset() {
            timeleft = timeout;
            lastRefresh = Date.now();
            modalShown = false;
            $.fn.efront('ajax', location.toString(), {data: {'ajax': 1, 'refresh_logout_timer': 1}});
            refreshFlag = false;
            renderCountdown(dropdownTimer);
            renderNavbarCountdown();
        }

        function getInterval() {
            if (
                isVisible
                || timeleft < tenminutes
                || (hasNavbarTimer && timeleft < onehour)
            ) {
                return fastInterval;
            }

            return slowInterval;
        }

        function scheduleInterval() {
            clearTimeout(timer);

            const interval = getInterval();
            let nextInterval = timeleft % interval;

            if (nextInterval <= 0) {
                nextInterval = interval;
            }

            timer = setTimeout(intervalCallback, nextInterval);
        }

        function obsCallback(entries) {
            wasVisible = isVisible;
            isVisible = entries[0].isIntersecting;
            if (wasVisible != isVisible) {
                timeleft = lastRefresh + timeout - Date.now();

                if (isVisible) {
                    renderCountdown(dropdownTimer);
                }

                scheduleInterval();
            }
        }

        function getLastAccessed(callback) {

            return $.ajax({
                url: location.toString(),
                data: {
                    'ajax': 1,
                    'check_logout_timer': 1,
                    'skipSession': 1
                },
                success: callback
            });
        }

        function checkLastAccessed() {
            refreshFlag = true;

            getLastAccessed(function (response) {
                if (response.success && response.data.last_accessed_period > 0) {
                    const lastAccessedPeriod = response.data.last_accessed_period * 1000;
                    const timeRemaining = timeout - lastAccessedPeriod;

                    if ((timeRemaining > (timeleft + 1000)) && (timeRemaining > 0)) {
                        refreshFlag = false;
                        lastRefresh = Date.now() - lastAccessedPeriod;
                        timeleft = timeRemaining;
                        scheduleInterval();
                    } else {
                        attemptLogout();
                    }
                } else {
                    logout();
                }
            });
        }

        function attemptLogout() {
            if (timeleft <= 0) {
                logout();
            }
        }

        function logout() {
            clearTimeout(timer);

            if (true !== attemptedLogout) {
                attemptedLogout = true;

                if (typeof (window.scorm_popup) != 'undefined') {
                    window.scorm_popup.close();
                }
                window.location = $.fn.efront('url', {ctg: 'logout', inactivity: timeout / 1000});
            }
        }
    },

    calendarEvents: function(){
        $( "#ef-navbar" ).find( "#add-calendar-event" ).click(function(){
            $.fn.efront('modal', { 'header': 'Add Event', 'url': $.fn.efront('url', { 'ctg': 'calendar', 'add':1, 'popup':1 }) });
            //eFront.Modal({ size: 'lg', url: $.fn.efront('url', { 'ctg': 'calendar', 'add':1 }) });
        });
        return this;
    },

    gamificationPoints: function(){
        $( ".gamification-points-button:not('.disabled')" ).click(function( e ){
            const isActive = $(this).data('user-active') === 1;
            if (isActive) {
                e.preventDefault();
                eFront.Modal({
                    size: "lg", url: $( this ).attr( "href" )
                });
            } else {
                e.preventDefault();
                bootbox.alert({
                    title: $.fn.efront('translate', 'Leaderboard'),
                    message: $.fn.efront('translate', 'Inactive users do not have access to the gamification leaderboard.'),
                    className: 'gamification-alert-for-inactive-users'
                });
            }
        });

        $( ".gamification-points-button.disabled" ).click(function( e ){
            e.preventDefault();
            e.stopPropagation();
        });
        return this;
    },

    handleDroplistMaxSize: function(){

        var windowLastHeight  = 0;
        var elementLastHeight = 0;
        var $elements = $( "#ef-navbar ul#ef-navigation > li > ul.dropdown-menu" );
        var $navbar   = $( "#ef-navbar" );

        $( window ).on( "resize.navbar", function(){

            var windowHeight = $( this ).height();
            if( windowLastHeight === windowHeight ){
                return null;
            }
            windowLastHeight = windowHeight;

            var elementHeight = parseInt( windowHeight - $navbar.outerHeight() - 15 );
            if( elementLastHeight === elementHeight ){
                return null;
            }
            elementLastHeight = elementHeight;
            $elements.css({ maxHeight: elementHeight + "px" });

        } ).trigger( "resize" );

        return this;

    },

    hideLogoOnSmallScreens: function(){
        var $navbar     = $( "#ef-navbar" );
        var $logo       = $( "#ef-navbar #ef-logo" );
        var $userNavBar = $( "#ef-navbar #userNavBar" );

        $( window ).on( "resize.navbar", function(){
            if($logo.outerWidth() + $userNavBar.outerWidth() > $navbar.outerWidth()) {
                $logo.hide();
            } else {
                $logo.show();
            }
        } ).trigger( "resize" );
        return this;

    },

    roleAccounts: function(){

        var $accounts = $( ".container ul.nav.navbar-nav li#user-roles a.ef-switch-account" );

        $accounts.on('click', function(event) {
            if (!$(this).data('id')) {  //prevent self-switching
                return;
            }

            var ending = window.location.host + '/';

            if (location.toString().slice(-ending.length) === ending) { //in case there is no ctg  (http://domain)
                parent.location = $.fn.efront('url', { 'switch_account': $(this).data('id') }, location.toString() + 'start');
            } else {
                parent.location = $.fn.efront('url', { 'switch_account': $(this).data('id') }, location.toString())
            }
        });
        return this;
    },

    communication: function(){
        var $communication = $('#ef-navbar li#communication');

        $communication.find('ul li.mark-all button').on('click', function() {
            var url = $(this).data('url');

            $.fn.efront('ajax', url, { }, function(response, textStatus, jqXHR) {
                location.reload();
            });
        });
        return this;
    },

    groupKey: function(){
        $( "#ef-navbar #ef-group-key" ).click(function( e ){
            eFront.Modal({
                size: "md2",
                url: $.fn.efront( "url", { ctg: "groups", op: "group_key" } )
            });
        });
        return this;
    },

    notifications: function(){
        $( "#ef-navbar .nav-list-alerts ul li a.message-link" ).click(function(){
            $.fn.efront( "ajax", $.fn.efront( "url", {
                ctg: "start", ajax: 1, alert_id: $( this ).data( "id" )
            } ), {}, function( r, s, x ){
                window.location = r.data.url;
            } );
        });

        return this;
    },

    dropLists: function(){
        $( "#ef-navbar .container ul.nav.navbar-nav li button.dropdown-toggle" ).each(function(){

            // this is required to workaround a bug with bootstrap+firefox
            // firefox creates a synthetic "click" event when spacebar is pressed on a button
            // bootstrap, however, handles both the click and the keydown event, and toggles the dropdown twice,
            // immediately hiding it again
            // see https://github.com/twbs/bootstrap/issues/20303
            $( this ).on('keydown', function(event){
                if(event.key == " ") {
                    event.stopPropagation();
                }
            });

            var $parent = $( this ).parent();

            $parent.on( "show.bs.dropdown", function( e ){
                $( this ).find( "ul, ul li" ).filter(":animated").finish();
                $( this ).find( "> .dropdown-menu" ).stop().css({ display: "block" }).animate({
                    opacity: 1, marginTop: "0px"
                }, 150);
            } );

            $parent.on( "hide.bs.dropdown", function( e ){
                $( this ).find( "> .dropdown-menu" ).stop().css({ display: "block" }).animate({
                    opacity: 0, marginTop: "-15px"
                }, 150, function(){
                    $( this ).css({ display: "none" });
                    $( this ).find( "a.dropdown-item.nested.active ~ ul a.dropdown-back" ).trigger( "click" );
                });
            } );

        });

        //items were clickable although hidden
        $("ul.dropdown-menu").click(function (e) {
            if ($(this).css('opacity') == 0) e.preventDefault();
        });


        return this;
    },

    nestedBreakPoint: 4, //Excepts back li item

    nestedDropLists: function(){

        var $nav = $( "#ef-navbar .container ul.nav.navbar-nav" );

        $nav.find( "li ul li a.dropdown-item" ).each(function(){
            var $this = $( this );
            var $list = $this.next( "ul" ).find( "li" );

            $list = $list.filter(function(){
                return !!!$( this ).hasClass( "divider" );
            });

            if( $list.length > ef_navbar.nestedBreakPoint ){
                $this.addClass( "nested" );
            } else if( $list.length > 1 ){
                $this.addClass( "inline" );
                $this.parent().prev().hide();
            }
        });

        $nav.find( "li ul li a.dropdown-item.nested" ).click(function( e ){

            if( e.originalEvent !== undefined ){
                e.preventDefault();
                e.stopPropagation();
            }

            var $ul = $( this ).next( "ul" );
            var $li = $ul.parents( "ul.dropdown-menu" ).find( "> li" );
            var $up = $ul.parents( "ul" ).eq( 0 );

            if(!$( this ).hasClass( "nested" ) ){
                return this;
            }

            $( this ).addClass( "active" );
            $ul.css({ display: "block", overflowY: "auto" });
            $up.css({ overflowY: "auto" } );

            var $height = $ul.outerHeight() + "px";

            $ul.stop().animate({ marginLeft: "0%" }, 900, "easeOutExpo");
            $li.stop().animate({ marginLeft: "-30%" }, 900, "easeOutExpo", function () {
                $ul.parent().siblings().css({display: 'none'});
            });
            $up.stop().animate({ height: $height }, 900, "easeOutExpo");
        });

        $nav.find( "li ul li a.dropdown-back" ).click(function( e ){

            if( e.originalEvent !== undefined ){
                e.preventDefault();
                e.stopPropagation();
            }

            var $ul = $( this ).parents( "ul" ).eq( 0 );
            $ul.parent().siblings().css({display: 'block'});
            var $li = $ul.parents( "ul" ).eq( 0 ).find( "> li" );
            var $up = $ul.parents( "ul" ).eq( 0 );

            var $heightOld = $up.height();
            $up.css({ height: "auto" });
            var $height = $up.outerHeight() + "px";
            $up.css({ height: $heightOld + "px" });

            $ul.stop().animate({ marginLeft: "100%" }, 900, "easeOutExpo", function(){
                $( this ).siblings( "a.dropdown-item.nested.active" ).removeClass( "active" );
                $( this ).css({ display: "none", overflowY: "hidden" });
            });
            $li.stop().animate({ marginLeft: "0%" }, 900, "easeOutExpo");
            $up.stop().animate({ height: $height }, 900, "easeOutExpo", function(){
                $( this ).css({ height: "auto", overflowY: "auto" });
            });

        });

    },
} );
