///<reference Path='jquery.js' />
/*jquery div ul li span a machpanel menu handling start*/

function findMenuItemPosition(JQueryObject) {
    var itemPos;
    if (JQueryObject.offset().top == undefined || JQueryObject.offset().top == 0)
        itemPos = findMenuItemPosition(JQueryObject.parent());
    else {
        if (JQueryObject.offset().top > 280)
            itemPos = JQueryObject.offset().top;
        else
            itemPos = JQueryObject.offset().top - 140;
    }
    return itemPos;
}

function InitializeMenu() {


    ////jquery.slimscroll.js
    //try {
    //    var currentTheme = getCookie('MachTheme').split("=")[1];
    //    var scrollColor, themeRailColor;

    //    if (currentTheme == 1) {
    //        scrollColor = '#376399';
    //        themeRailColor = '#fff';//'#b0d3ff';
    //    }
    //    else if (currentTheme == 2) {
    //        scrollColor = '#919191';
    //        themeRailColor = '#d1d1d1';
    //    }
    //    else
    //        scrollColor = '#a1a1a1';

    //    var slimScrollDivHeight = 400;
    //    //var slimScrollDivHeight = $('.containerTable').height() * 60 / 100;
    //    //slimScrollDivHeight = (slimScrollDivHeight > 800 || slimScrollDivHeight < 700) ? 800 : slimScrollDivHeight;


    //    $('.treeContainer, .menuContainer').slimScroll({
    //        height: slimScrollDivHeight + 'px',
    //        size: '10px',
    //        color: scrollColor,
    //        opacity: 1,
    //        railVisible: true,
    //        railColor: themeRailColor,
    //        railOpacity: 1,
    //        distance: '0px',
    //        allowPageScroll: true,
    //        wheelStep:3
    //    });


    //    //smooth mouse wheel scrolling handling

    //    var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';
    //    //for firefox additional handling needed to identify the mouse wheel  event
    //    var wheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : wheelEvent;

    //    // Now bind the event to the desired element
    //    $('.menuContainer, .treeContainer').on(wheelEvent, function (e) {
    //        var oEvent = e.originalEvent;
    //        //var delta  = oEvent.deltaY || oEvent.wheelDelta;

    //        var delta = 0;
    //        if (oEvent.wheelDelta)
    //            delta = oEvent.wheelDelta / 120;
    //        else if (oEvent.detail)
    //            delta = -oEvent.detail / 3;

    //        $(this).stop().animate({
    //            scrollTop: $(this).scrollTop() - (200 * delta)
    //        }, 1500);

    //        if (oEvent.returnValue)
    //            oEvent.returnValue = false;
    //        return false;
    //    });

    //} catch (e) { }



    //function isEventSupported(eventName) {
    //    var el = document.createElement('div');
    //    eventName = 'on' + eventName;
    //    var isSupported = (eventName in el);
    //    if (!isSupported) {
    //        el.setAttribute(eventName, 'return;');
    //        isSupported = typeof el[eventName] == 'function';
    //    }
    //    el = null;
    //    return isSupported;
    //}

    ////find and select current page item in menu and bring to front
    //$('.menuLink').each(function () {
    //    $this = $(this);
    //    //menuItem, menuItemSelected
    //    if ($this.attr('href')) {
    //        var patt = new RegExp($this.attr('href').toString(), "i");
    //        if (patt.exec(window.location.href.toString())) {
    //            $('ul.subMenu').hide(); //hide all sub menu items.
    //            $this.parents('ul.subMenu').show().css('display', 'table'); //show all parent sub menus of current menu item.
    //            $('.menuItem').removeClass('menuItemSelected');//remove menu selection from all menu items
    //            $('.toggleLink').removeClass('subMenuExpanded').addClass('subMenuSuppressed'); //remove collapse icon and add expand icon on all sub menu item link
    //            $this.parents('span.menuItem').first().addClass('menuItemSelected'); //add menu selection class to current page menulink parent menu item only
    //            $this.parents('ul.subMenu').siblings('span.expandableItem').find('a.toggleLink').addClass('subMenuExpanded').removeClass('subMenuSuppressed');//remove expand icon and add collapse icon on current link parent sub menu item link
    //        }
    //    }
    //});


    //scroll to the selected item
    //collapsible
    setTimeout(function () {

        if ($('.menuItemSelected').parent('li').parent('ul.subMenu').length > 0) {

            var focusedItemPos = $('.menuItemSelected').parent('li').parent('ul.subMenu').position().top - 35;
            try {
                $('#cp-menu-wrapper').animate({
                    scrollTop: focusedItemPos//findMenuItemPosition($('.menuItemSelected'))
                }, 200);

                //change bar postion of slim scroll if it is applied.
                if ($('#cp-menu-wrapper').siblings('.slimScrollBar').length > 0) {
                    delta = focusedItemPos;
                    var maxTop = $('#cp-menu-wrapper').outerHeight() - $('#cp-menu-wrapper').siblings('.slimScrollBar').outerHeight();
                    var offsetTop = delta / $('#cp-menu-wrapper')[0].scrollHeight * $('#cp-menu-wrapper').outerHeight();
                    offsetTop = Math.min(Math.max(offsetTop, 0), maxTop);
                    $('#cp-menu-wrapper').siblings('.slimScrollBar').css({ top: offsetTop + 'px' });
                }


            } catch (e) { console.log(e); }

        }

    }, 200);

    ////tree
    //setTimeout(function () {
    //    try {
    //        $('.treeContainer').animate({
    //            scrollTop: $('.ctl00_TV_Menu_2').position().top - 2//findMenuItemPosition($('.menuItemSelected'))
    //        }, 1000);
    //    } catch (e) { }
    //}, 300);

    //hide all suppressed sub menus
    $('.subMenuSuppressed').each(function () {
        $(this).parent('.itemContent').parent('.menuItem').parent('li').children('.subMenu').hide();
    });

    if ($("body").attr("dir") != null && $("body").attr("dir").toUpperCase() == 'RTL') {
        $('.toggleLink').addClass('FlipImg');

        var MarginLeft = $('.toggleLink').css('margin-left');
        var MarginRight = $('.toggleLink').css('margin-right');

        $('.toggleLink').css('margin-right', MarginLeft);

        $('.toggleLink').css('margin-left', MarginRight);

        $('.menuOption').css('direction', 'ltr');

        var menuSettingsMarginLeft = $('.menuSettings').css('margin-left');
        var menuSettingsMarginRight = $('.menuSettings').css('margin-right');

        $('.menuSettings').css('margin-right', menuSettingsMarginLeft);

        $('.menuSettings').css('margin-left', menuSettingsMarginRight);

    }

    //if current item has submenu and no link then we need to register event handler for toggle the submenu
    $('.mpmenu .menuLink.hasSub:not(.hasLink)').each(function () {
        $(this).click(function (event) {
            $(this).parent().next('.toggleLink').trigger('click');
            event.preventDefault();
            /*if ($(this).parent().next('.toggleLink').hasClass('subMenuExpanded')) {
                collapseSubMenu($(this).parent().next('.toggleLink'), event, true);
                event.preventDefault();
            }
            else if ($(this).parent().next('.toggleLink').hasClass('subMenuSuppressed')) {
                CollapseAllSiblingMenus(event, $(this));
                expandSubMenu($(this).parent().next('.toggleLink'), event, true);
                event.preventDefault();
            }*/
        });
    });

    //for special toggle link when menu item has a link and expand functionality too.
    $('.mpmenu .toggleLink').each(function () {
        $(this).click(function (event) {
            if ($(this).hasClass('subMenuExpanded')) {
                collapseSubMenu($(this), event, true);
            }
            else if ($(this).hasClass('subMenuSuppressed')) {
                CollapseAllSiblingMenus(event, $(this));
                expandSubMenu($(this), event, true);
            }
        });
    });

    //for menulink haslink anchor 'a' tag add click handler to show page load wrapper div.
    //setTimeout(() => {
    $('a.menuLink.hasLink:not([data-show-progress])').each(anchorClickShowProgressHandler);
    //}, 0);
}

function CollapseAllSiblingMenus(e, itemLink) {
    itemLink.parent('.itemContent').parent('.expandableItem').parent('li').parent('ul .subMenu').parent().each(
        function () {
            var parentLi;
            if ($(this).is('li')) {
                parentLi = $(this);
            }
            else if ($(this).parent().is('li')) {
                parentLi = $(this).parent();
            }

            $('.subMenu .subMenuExpanded', parentLi).each(function () { collapseSubMenu($(this), e, true); });
        });
}

function expandSubMenu(jQueryObject, e, doEasing) {

    jQueryObject.parent('.itemContent').parent('.expandableItem').parent('li').parent('ul .subMenu').parent()
        .each(function () {
            var parentLi;
            if ($(this).is('li')) {
                parentLi = $(this);
            }
            else if ($(this).parent().is('li')) {
                parentLi = $(this).parent();
            }

            if (parentLi) {
                setTimeout(function () { expandSubMenu(parentLi.children('.expandableItem').first().children('.itemContent').first().children('.subMenuSuppressed').first(), e, false); }, 210);
            }
        });


    //sub menu is hidden, we need to show the sub menu now
    //and also update class for this link to show collapse icon instead of expand.
    jQueryObject.removeClass('subMenuSuppressed');
    jQueryObject.addClass('subMenuExpanded');
    if (doEasing)
        jQueryObject.parent('.itemContent').parent('.menuItem').parent('li').children('.subMenu').first().show("blind", null, 500);
    else
        jQueryObject.parent('.itemContent').parent('.menuItem').parent('li').children('.subMenu').first().show();

    if (e)
        e.preventDefault();
    //slimScrollToActiveElement(jQueryObject);
}

function collapseSubMenu(jQueryObject, e, doEasing) {
    //sub menu is shown, we need to hide the sub menu now
    //and also update class for this link to show expand icon instead of collapse.
    jQueryObject.removeClass('subMenuExpanded');
    jQueryObject.addClass('subMenuSuppressed');
    if (doEasing)
        jQueryObject.parent('.itemContent').parent('.menuItem').parent('li').children('.subMenu').hide("blind", null, 700);
    else
        jQueryObject.parent('.itemContent').parent('.menuItem').parent('li').children('.subMenu').hide();
    if (e)
        e.preventDefault();
    //slimScrollToActiveElement(jQueryObject);
}

function slimScrollToActiveElement($element) {
    if ($element.position())
        if ($('#cp-menu-wrapper').siblings('.slimScrollBar').length > 0) {
            setTimeout(function () {
                $slimscroll = $('#cp-menu-wrapper').slimScroll({ scrollTo: $element.get(0).offsetTop - 15 });

            }, 710);
            setTimeout(function () { $('#cp-menu-wrapper').next('.slimScrollBar').next('.slimScrollRail').first().mouseover(); }, 2000);
        }
        else
            $(window).animate({ scrollTop: $element.position().top }, 200);
}


/*jquery div ul li span a machpanel menu handling end*/


/*Sidebar Menu Handling Start*/
function selectPage(source) {
    if (source.value && source.value != '') {
        $('.page-loader-wrapper').show();
        window.location = source.value.replace(/~\//g, '/');
    }
}

async function getMenu() {
    let postRequest = { ...fetchPost };
    postRequest.body = JSON.stringify({ referrer: window.location.href });

    await fetch('/webservices/machpanelservice.asmx/GetMenu', postRequest)
        .then(r => r.json()).then((data) => {
            let jData = JSON.parse(data.d);
            $('div#cp-menu-wrapper').html(jData.menuContent.replace(/~\//g, '/'));

            let $searchDdl = $('select#ddl-search-menu');

            let menuSearchOpts = JSON.parse(jData.menuSearchOpts)
            menuSearchOpts.items.forEach((i) => {
                let dc = '';

                if (i['data-content'] && i['data-content'].toString().match(/>/g)) {
                    dc = '<span>' + i['data-content'].replace(/>/g, "&nbsp;<i class='glyphicon glyphicon-chevron-right'></i>&nbsp;") + '</span>';
                    $searchDdl.append('<option value="' + i.value + '" data-content="' + dc + '">' + i.text + '</option>')
                }
                else
                    $searchDdl.append('<option value="' + i.value + '">' + i.text + '</option>')
            });
        })
        .catch(function (e) {
            displayErrorMsg(e);
        });
}

//setTimeout(
//    () => {
getMenu()
    .then(InitializeMenu)
    .then(() => { try { $('select#ddl-search-menu').selectpicker('refresh'); } catch { } });
//    }, 100);

/*Sidebar Menu Handling End */