/*
 *
 *   INSPINIA - Responsive Admin Theme
 *   version 2.2
 *   Internally modified!
 */

function pageResize(initial) {
    var width = $('body').outerWidth();
    inspiniaHelper.handleTouchCapability();

    if (initial) {
        inspiniaHelper.cachedMenuCollapseState = $('body').hasClass('mini-navbar')? 'collapsed' : 'expanded';
    }

    if (width < 991.98 || (inspiniaHelper.isTouchDevice && $(this).height() < 980 && width < 991.98)) {
        if (!$('body').hasClass('body-small')) {
            $('body').removeClass('mini-navbar');
            $('body').addClass('body-small');
        }
    } else {
        if (!initial && $('body').hasClass('body-small')) {
            if ($('body').hasClass('mini-navbar') && inspiniaHelper.cachedMenuCollapseState !== 'collapsed')
                $('body').removeClass('mini-navbar');
            else if (inspiniaHelper.cachedMenuCollapseState === 'collapsed')
                $('body').addClass('mini-navbar');

            $('body').removeClass('body-small');
        }        
    }

    pageLastSize = $(this).width();
}
//Moved from document.ready
pageResize(true);

$(document).ready(function () {
    // Add body-small class if window less than 768px
    //pageResize(true);

    inspiniaHelper.init();

    // MetsiMenu
    $('#side-menu').metisMenu();

    // Collapse ibox function
    //$('.collapse-link').click( function() {
    //    var ibox = $(this).closest('div.ibox');
    //    var button = $(this).find('i');
    //    var content = ibox.find('div.ibox-content');
    //    content.slideToggle(200);
    //    button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
    //    ibox.toggleClass('').toggleClass('border-bottom');
    //    setTimeout(function () {
    //        ibox.resize();
    //        ibox.find('[id^=map-]').resize();
    //    }, 50);
    //});
    $('body').on('click', '.collapse-link', function () {
        var ibox = $(this).closest('div.ibox');
        var button = $(this).find('i');
        var content = ibox.find('div.ibox-content');
        content.slideToggle(200);
        button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
        ibox.toggleClass('').toggleClass('border-bottom');
        setTimeout(function () {
            ibox.resize();
            ibox.find('[id^=map-]').resize();
        }, 50);
    });


    // Close ibox function
    $('.close-link').click(function () {
        var content = $(this).closest('div.ibox');
        content.remove();
    });

    // Fullscreen ibox function
    $('.fullscreen-link').click(function () {
        var ibox = $(this).closest('div.ibox');
        var button = $(this).find('i');
        $('body').toggleClass('fullscreen-ibox-mode');
        button.toggleClass('fa-expand').toggleClass('fa-compress');
        ibox.toggleClass('fullscreen');
        setTimeout(function () {
            $(window).trigger('resize');
        }, 100);
    });

    // Close menu in canvas mode
    $('.close-canvas-menu').click(function () {
        $("body").toggleClass("mini-navbar");
        SmoothlyMenu();
    });

    // Open close right sidebar
    $('.right-sidebar-toggle').click(function () {
        $('#right-sidebar').toggleClass('sidebar-open');
    });

    $('.navbar-static-side > .sidebar-collapse > ul > li > a').off("mousedown mouseup click touchstart touchend touch");
    $('.navbar-static-side > .sidebar-collapse > ul > li > a').on("click touch", function (e) {
        let sameClick = $(this).parent("li").hasClass("active-dropdown");
        $(this).closest("ul").find(".active").removeClass("active").removeClass("active-dropdown");

        if ($(this).parent("li").hasClass("dropdown")) {
            if (!sameClick) $(this).parent("li").addClass("active active-dropdown");
            else $(this).parent("li").removeClass("active active-dropdown");

            if ($(this).parent("li").find("ul").length > 0) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
        }
    });

    // mimic main navigation item Hover behavior, when Auto-test. In Auto-test hover event triggering can be unreliable.
    if (isAutoTest) {
        var atMimicHover = function (e) {
            e.stopImmediatePropagation();
            var $item = $(this);
            if ($item.hasClass('at-mimic-hover')) {
                return;
            }
            var $subMenu = $item.children('ul.dropdown-menu');
            $('.navbar-static-side > .sidebar-collapse > ul > li:not(.nav-header)').removeClass('at-mimic-hover')

            if ($item.hasClass('dropdown') && $subMenu.length > 0) {
                $item.addClass('at-mimic-hover');
            }
        };
        var atMimicHoverClear = function (e) {
            $('.at-mimic-hover').removeClass('at-mimic-hover');
        };

        $('.navbar-static-side > .sidebar-collapse > ul > li:not(.nav-header)').off('click', atMimicHover).on('click', atMimicHover);
        $('body').off('click', atMimicHoverClear).on('click', atMimicHoverClear);
        $('.navbar-static-side > .sidebar-collapse > ul > li:not(.nav-header)').off('mouseleave', atMimicHoverClear).on('mouseleave', atMimicHoverClear);
    }

    // Initialize slimscroll for right sidebar
    $('.sidebar-container').slimScroll({
        height: '100%',
        railOpacity: 0.4,
        wheelStep: 10
    });

    // Open close small chat
    $('.open-small-chat').click(function () {
        $(this).children().toggleClass('fa-comments').toggleClass('fa-remove');
        $('.small-chat-box').toggleClass('active');
    });

    // Initialize slimscroll for small chat
    $('.small-chat-box .content').slimScroll({
        height: '234px',
        railOpacity: 0.4
    });

    // Small todo handler
    $('.check-link').click(function () {
        var button = $(this).find('i');
        var label = $(this).next('span');
        button.toggleClass('fa-check-square').toggleClass('fa-square-o');
        label.toggleClass('todo-completed');
        return false;
    });

    // Minimalize menu
    $('.navbar-minimalize').click(function () {
        inspiniaHelper.toggleMainMenu(true);
        SmoothlyMenu();

        var opened = $(document).width() < 769 ?
            ($("body").hasClass("mini-navbar") ? "open" : "close") :
            ($("body").hasClass("mini-navbar") ? "close" : "open");

        $.post($("#siteMenuStatesUrl").val(), { isOpened: opened });
        localStorage.setItem("isMenuCollapsed", opened === 'close');
    });

    // Tooltips demo
    $('.tooltip-demo').tooltip({
        selector: "[data-toggle=tooltip]",
        container: "body"
    });

    // Move modal to body
    // Fix Bootstrap backdrop issu with animation.css
    $('.modal').appendTo("body");

    // Full height of sidebar
    function fix_height() {
        var heightWithoutNavbar = $("body > #wrapper").height() - 61;
        $(".sidebard-panel").css("min-height", heightWithoutNavbar + "px");

        var $mobileMenu = $('#mobile-menu');
        var mobileMenuHeight = $mobileMenu.css('display') === 'none'? 0 : $mobileMenu.outerHeight();
        var navbarHeight = $('nav.navbar-default').height();
        var wrapperHeigh = $('#page-wrapper').height();
        var windowHeight = $(window).height();
        var viewportHeight = windowHeight - mobileMenuHeight;

        if ($('body').hasClass('fixed-nav')) {
            viewportHeight = windowHeight - 60;
        }
        else if (navbarHeight > wrapperHeigh) {
            viewportHeight = navbarHeight - mobileMenuHeight;
        }

        else if (navbarHeight < wrapperHeigh) {
            viewportHeight = windowHeight - mobileMenuHeight;
        }

        $('#page-wrapper').css("min-height", viewportHeight + "px");
        $('#wrapper').css('height', 'calc(100% - ' + mobileMenuHeight + 'px)')
    }
    fix_height();

    // Fixed Sidebar
    $(window).bind("load", function () {
        if ($("body").hasClass('fixed-sidebar')) {
            $('.sidebar-collapse').slimScroll({
                height: '100%',
                railOpacity: 0.9
            });
        }
    })

    // Move right sidebar top after scroll
    $(window).scroll(function () {
        if ($(window).scrollTop() > 0 && !$('body').hasClass('fixed-nav')) {
            $('#right-sidebar').addClass('sidebar-top');
        } else {
            $('#right-sidebar').removeClass('sidebar-top');
        }
    });

    $(document).bind("load resize scroll", function () {
        if (!$("body").hasClass('body-small')) {
            fix_height();
        }
    });

    $(window).on("resize", function () {
        fix_height();
    });

    $("[data-toggle=popover]")
            .popover();

    // Add slimscroll to element
    $('.full-height-scroll').slimscroll({
        height: '100%'
    })
});


// Minimalize menu when screen is less than 768px
$(window).bind("resize", function () {
    pageResize();
});

// Local Storage functions
// Set proper body class and plugins based on user configuration
$(document).ready(function () {
    if (localStorageSupport) {

        var collapse = localStorage.getItem("collapse_menu");
        var fixedsidebar = localStorage.getItem("fixedsidebar");
        var fixednavbar = localStorage.getItem("fixednavbar");
        var boxedlayout = localStorage.getItem("boxedlayout");
        var fixedfooter = localStorage.getItem("fixedfooter");

        var body = $('body');

        if (fixedsidebar == 'on') {
            body.addClass('fixed-sidebar');
            $('.sidebar-collapse').slimScroll({
                height: '100%',
                railOpacity: 0.9
            });
        }

        if (collapse == 'on') {
            if (body.hasClass('fixed-sidebar')) {
                if (!body.hasClass('body-small')) {
                    body.addClass('mini-navbar');
                }
            } else {
                if (!body.hasClass('body-small')) {
                    body.addClass('mini-navbar');
                }

            }
            inspiniaHelper.cachedMenuCollapseState = 'collapsed';
        }

        if (fixednavbar == 'on') {
            $(".navbar-static-top").removeClass('navbar-static-top').addClass('navbar-fixed-top');
            body.addClass('fixed-nav');
        }

        if (boxedlayout == 'on') {
            body.addClass('boxed-layout');
        }

        if (fixedfooter == 'on') {
            $(".footer").addClass('fixed');
        }
    }
});

// check if browser support HTML5 local storage
function localStorageSupport() {
    return (('localStorage' in window) && window['localStorage'] !== null)
}

// For demo purpose - animation css script
function animationHover(element, animation) {
    element = $(element);
    element.hover(
        function () {
            element.addClass('animated ' + animation);
        },
        function () {
            //wait for animation to finish before removing classes
            window.setTimeout(function () {
                element.removeClass('animated ' + animation);
            }, 2000);
        });
}

function SmoothlyMenu() {
    if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) {
        // Hide menu in order to smoothly turn on when maximize menu
        $('#side-menu').hide();
        // For smoothly turn on menu
        setTimeout(
            function () {
                $('#side-menu').fadeIn(500);
            }, 100);
    } else if ($('body').hasClass('fixed-sidebar')) {
        $('#side-menu').hide();
        setTimeout(
            function () {
                $('#side-menu').fadeIn(500);
            }, 300);
    } else {
        // Remove all inline style from jquery fadeIn function to reset menu state
        $('#side-menu').removeAttr('style');
    }
}

// Dragable panels
function WinMove() {
    var element = "[class*=col]";
    var handle = ".ibox-title";
    var connect = "[class*=col]";
    $(element).sortable(
        {
            handle: handle,
            connectWith: connect,
            tolerance: 'pointer',
            forcePlaceholderSize: true,
            opacity: 0.8
        })
        .disableSelection();
}


