//ignorei18n_start
// This is the known base for all help links
// Related products for LHS

var SEARCH_KEYS = OFFLINE_KEYS.onprem;
var HELP_ROOT = getHelpRoot();
const HELP_SWITCH_ROOT = {
    cloud: "data-source-configuration/windows/overview.html",
    onprem: "whats-new-in-log360.html",
    ela:"overview/get-started.html"
}
// Get current file name from URL or default to 'index.html'
const currentFile = location.pathname.split('/').pop().split('#')[0].split('?')[0] || 'index.html';

// Get current tab from sessionStorage or default to 'onPrem'
var currentTab = sessionStorage.getItem('mainTab') || 'onPrem';


var dynamicTemplates = {
    "onPrem": {
        relatedProducts: ` <h3>相关产品</h3>
                        <ul>
                            <li class="wsm-lhs-prd-ic wsm-ic-admp"><a title="ADManager Plus" target="_blank" href="https://www.manageengine.cn/products/ad-manager/index.html?log360HelpLhs"><span>ADManager Plus</span> <div class="short-desc">Active Directory管理和报表</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-adap"><a title="ADAudit Plus" target="_blank" href="https://www.manageengine.cn/products/active-directory-audit/index.html?log360HelpLhs"><span>ADAudit Plus</span> <div class="short-desc">实时Active Directory审核和UBA</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-adssp"><a href="https://www.manageengine.cn/products/self-service-password/?log360HelpLhs" target="_blank" title="ADSelfService Plus"><span>ADSelfService Plus</span> <div class="short-desc">MFA、SSO和SSPR的身份安全</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-erp"><a title="Exchange Reporter Plus" target="_blank" href="https://www.manageengine.cn/products/exchange-reports/index.html?log360HelpLhs"><span>Exchange Reporter Plus</span> <div class="short-desc">Exchange Server审核和报表</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-ad360"><a title="AD360" target="_blank" href="https://www.manageengine.cn/active-directory-360/index.html?log360HelpLhs"><span>AD360</span> <div class="short-desc">综合身份和访问管理</div></a></li>
                        </ul>`,
        topMenu: ` <ul class="right-menu">
                        <li><span>X</span></li>
                        <li><a href="https://www.manageengine.cn/log-management/?helpdoc" target="_blank">概览</a></li>
                        <li><a href="https://www.manageengine.cn/log-management/resources.html?helpdoc" target="_blank">资源</a></li>
                        <li class="norView"> <a href="https://www.manageengine.cn/log-management/demo.html?helpdoc" target="_blank">演示</a></li>
                        <li> <a href="https://www.manageengine.cn/log-management/get-quote.html?helpdoc#request" target="_blank">获取报价</a> </li>
                        <li> <a href="https://www.manageengine.cn/log-management/support.html?helpdoc#request" target="_blank">支持</a> </li>
                        <li class="dwnload-btn"><a class="btn-dwn-top" href="https://www.manageengine.cn/log-management/download.html?helpdoc" target="_blank">下载 <span class="nav-dwn-icon">&nbsp;</span></a></li>
                    </ul>`,
        footer: ` <div class="card">
                    <h4>Visit our <br> community</h4>
                    <p>Post your questions in the forum.</p>
                    <span>Learn more</span>
                    <a class="overlay-link" href="https://pitstop.manageengine.com/portal/en/community/log360?log360_helpdoc" target="_blank">&nbsp;</a>
                </div>
                <div class="card">
                    <h4>Request additional <br>resources</h4>
                    <p>Send us your requirements.</p>
                    <span>Learn more</span>
                    <a class="overlay-link" href="https://www.manageengine.com/log-management/support.html?log360_helpdoc" target="_blank">&nbsp;</a>
                </div>
                <div class="card">
                    <h4>Need implementation <br> assistance?</h4>
                    <p>Try OnboardPro</p>
                    <span>Learn more</span>
                    <a class="overlay-link" href="https://www.manageengine.com/onboarding/iam-and-siem-onboarding.html?log360_helpdoc" target="_blank">&nbsp;</a>
                </div>`,
        searchUrl: `https://www.manageengine.com/log-management/help/search-results.html`,
        pdfLink: 'ManageEngine_Log360_UserGuide.pdf'
    },
    "cloud": {
        relatedProducts: ` <h3>相关产品</h3>
                        <ul>
                            <li class="wsm-lhs-prd-ic wsm-ic-log360 twolink"><span>Log360 (<a title="Log360" target="_blank" href="https://www.manageengine.cn/log-management/?log360CloudHelpLhs">本地</a> | <a title="Log360" target="_blank" href="https://www.manageengine.cn/cloud-siem/?log360CloudHelpLhs">云</a>)</span> <div class="short-desc">综合SIEM和UEBA</div></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-ad360"><a title="AD360" target="_blank" href="https://www.manageengine.cn/active-directory-360/index.html?log360CloudHelpLhs"><span>AD360</span> <div class="short-desc">综合身份和访问管理</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-admp"><a title="ADManager Plus" target="_blank" href="https://www.manageengine.cn/products/ad-manager/index.html?log360CloudHelpLhs"><span>ADManager Plus</span> <div class="short-desc">Active Directory管理和报表</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-adap"><a title="ADAudit Plus" target="_blank" href="https://www.manageengine.cn/products/active-directory-audit/index.html?log360CloudHelpLhs"><span>ADAudit Plus</span> <div class="short-desc">实时Active Directory审核和UBA</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-adssp"><a href="https://www.manageengine.cn/products/self-service-password/?log360CloudHelpLhs" target="_blank" title="ADSelfService Plus"><span>ADSelfService Plus</span> <div class="short-desc">MFA、SSO和SSPR的身份安全</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-ela"><a title="EventLog Analyzer" target="_blank" href="https://www.manageengine.cn/products/eventlog/?lhsadmp"><span>EventLog Analyzer</span> <div class="short-desc">实时日志分析和报表</div></a></li>
                            <li class="wsm-lhs-prd-ic wsm-ic-erp"><a title="Exchange Reporter Plus" target="_blank" href="https://www.manageengine.cn/products/exchange-reports/index.html?log360CloudHelpLhs"><span>Exchange Reporter Plus</span> <div class="short-desc">Exchange Server审核和报表</div></a></li>
                        </ul>`,
        topMenu: ` <ul class="right-menu">
                    <li><a href="https://www.manageengine.cn/cloud-log-management/index.html?helpdoc?utm_source=manageengine&amp;utm_medium=referral&amp;utm_campaign=index&amp;utm_content=cta_header">概览</a></li>
                    <li><a href="https://www.manageengine.cn/cloud-log-management/demo.html?utm_source=manageengine&amp;utm_medium=referral&amp;utm_campaign=index&amp;utm_content=cta_header">演示</a></li>
                    <li><a href="https://www.manageengine.cn/cloud-log-management/pricing-details.html?helpdoc?utm_source=manageengine&amp;utm_medium=referral&amp;utm_campaign=index&amp;utm_content=cta_header">价格</a></li>
                    <li><a href="https://www.manageengine.cn/cloud-log-management/support.html?helpdoc?utm_source=manageengine&amp;utm_medium=referral&amp;utm_campaign=index&amp;utm_content=cta_header">支持</a></li>
                    <li> <a class="btn btn-danger" href="https://log360cloud.manageengine.com/rest/v1/signup?utm_source=manageengine&amp;utm_medium=referral&amp;utm_campaign=index&amp;utm_content=cta_header">注册</a> </li>
                    <li> <a class="btn btn-default" href="https://log360cloud.manageengine.com/rest/v1/login?utm_source=manageengine&amp;utm_medium=referral&amp;utm_campaign=index&amp;utm_content=cta_header">登录</a> </li>
                </ul>`,
        footer: `<div class="card">
                    <h4>Visit our <br> community</h4>
                    <p>Post your questions in the forum.</p>
                    <span>Learn more</span>
                    <a class="overlay-link" href="https://pitstop.manageengine.com/portal/en/community/eventlog-analyzer?log360cloud" target="_blank">&nbsp;</a>
                </div>
                <div class="card">
                    <h4>Request additional <br>resources</h4>
                    <p>Send us your requirements.</p>
                    <span>Learn more</span>
                    <a class="overlay-link" href="https://www.manageengine.com/cloud-siem/support.html?log360cloud" target="_blank">&nbsp;</a>
                </div>
                <div class="card">
                    <h4>Need implementation <br> assistance?</h4>
                    <p>Try OnboardPro</p>
                    <span>Learn more</span>
                    <a class="overlay-link" href="https://www.manageengine.com/onboarding/iam-and-siem-onboarding.html?log360cloud" target="_blank">&nbsp;</a>
                </div>`,
        searchUrl: `https://www.manageengine.com/cloud-siem/help/search-results.html`,
        pdfLink: 'ManageEngine_Log360_Cloud_UserGuide.pdf'
    },
    "ela": {
        relatedProducts: ` <h3>Related Products</h3>
                            <ul>
								<li class="wsm-lhs-prd-ic wsm-ic-log360 twolink"><span>Log360 (<a title="Log360" target="_blank" href="https://www.manageengine.com/log-management/?elaHelpLhs">On-Premise</a> | <a title="Log360" target="_blank" href="https://www.manageengine.com/cloud-siem/?elaHelpLhs">Cloud</a>)</span> <div class="short-desc">Comprehensive SIEM and UEBA</div></li>
								<li class="wsm-lhs-prd-ic wsm-ic-ad360"><a title="AD360" target="_blank" href="https://www.manageengine.com/active-directory-360/index.html?elaHelpLhs"><span>AD360</span> <div class="short-desc">Integrated Identity &amp; Access Management</div></a></li>
                            	<li class="wsm-lhs-prd-ic wsm-ic-admp"><a title="ADManager Plus" target="_blank" href="https://www.manageengine.cn/products/ad-manager/index.html?elaHelpLhs"><span>ADManager Plus</span> <div class="short-desc">Active Directory Management &amp; Reporting</div></a></li>
                            	<li class="wsm-lhs-prd-ic wsm-ic-adap"><a title="ADAudit Plus" target="_blank" href="https://www.manageengine.cn/products/active-directory-audit/index.html?elaHelpLhs"><span>ADAudit Plus</span> <div class="short-desc">Real-time Active Directory Auditing and UBA</div></a></li>
                            	<li class="wsm-lhs-prd-ic wsm-ic-adssp"><a href="https://www.manageengine.cn/products/self-service-password/?elaHelpLhs" target="_blank" title="ADSelfService Plus"><span>ADSelfService Plus</span> <div class="short-desc">Identity security with MFA, SSO, and SSPR</div></a></li>
                            	<li class="wsm-lhs-prd-ic wsm-ic-erp"><a title="Exchange Reporter Plus" target="_blank" href="https://www.manageengine.cn/products/exchange-reports/index.html?elaHelpLhs"><span>Exchange Reporter Plus</span> <div class="short-desc">Exchange Server Auditing &amp; Reporting</div></a></li>
                            </ul>`,
        topMenu: ` <ul class="right-menu">
								<li><span>X</span></li>
								<li><a href="https://www.manageengine.cn/products/eventlog/?helpdoc" target="_blank">Overview</a></li>
								<li><a href="https://www.manageengine.cn/products/eventlog/resources.html?helpdoc" target="_blank">Resources</a></li>
								<li class="norView"> <a href="https://www.manageengine.cn/products/eventlog/request-demo.html?helpdoc" target="_blank">Demo</a></li>
								<li> <a href="https://www.manageengine.cn/products/eventlog/get-quote.html?helpdoc#request" target="_blank">Get Quote</a> </li>
								<li> <a href="https://www.manageengine.cn/products/eventlog/support.html?helpdoc#request" target="_blank">Support</a> </li>
								<li class="dwnload-btn"><a class="btn-dwn-top" href="https://www.manageengine.cn/products/eventlog/download.html?helpdoc" target="_blank">Download <span class="nav-dwn-icon">&nbsp;</span></a></li>
							</ul>`,
        footer: `<div class="card">
                        <h4>Visit our <br> community</h4>
                        <p>Post your questions in the forum.</p>
                        <span>Learn more</span>
                        <a class="overlay-link" href="https://pitstop.manageengine.com/portal/en/community/eventlog-analyzer?ela_helpdoc" target="_blank">&nbsp;</a>
                    </div>
                    <div class="card">
                        <h4>Request additional <br>resources</h4>
                        <p>Send us your requirements.</p>
                        <span>Learn more</span>
                        <a class="overlay-link" href="https://www.manageengine.cn/products/eventlog/support.html?ela_helpdoc" target="_blank">&nbsp;</a>
                    </div>
                    <div class="card">
                        <h4>Need implementation <br> assistance?</h4>
                        <p>Try OnboardPro</p>
                        <span>Learn more</span>
                        <a class="overlay-link" href="https://www.manageengine.com/onboarding/iam-and-siem-onboarding.html?ela_helpdoc" target="_blank">&nbsp;</a>
                    </div>`,
        searchUrl: `https://www.manageengine.com/log-management/help/search-results.html`,
        pdfLink: 'ManageEngine_Eventlog_Analyzer_UserGuide.pdf'
    }
}

function filterNavByPlatform(navItems, platforms) {
    var result = [];
    function shouldInclude(item) {
        return platforms.indexOf(item.platform) !== -1;
    }
    function cloneItem(item) {
        var copy = {
            url: item.url,
            title: item.title,
            platform: item.platform
        };
        if (item.product) {
            copy.product = item.product;
        }
        if (item.children && item.children.length > 0) {
            var filteredChildren = [];
            for (var i = 0; i < item.children.length; i++) {
                var child = item.children[i];
                var filteredChild = cloneItem(child);
                if (filteredChild) {
                    filteredChildren.push(filteredChild);
                }
            }
            if (filteredChildren.length > 0) {
                copy.children = filteredChildren;
            } else if (!shouldInclude(item)) {
                return null; // Remove empty parent if it's not in the platform list
            }
        }
        return shouldInclude(item) || (copy.children && copy.children.length > 0) ? copy : null;
    }
    for (var i = 0; i < navItems.length; i++) {
        var filtered = cloneItem(navItems[i]);
        if (filtered) {
            result.push(filtered);
        }
    }
    return result;
}

function appendDynamicTemplates(tab) {
    var _elem = {
        relatedProducts: document.getElementById('relatedProducts'),
        topMenu: document.querySelector('.right-menu'),
        footer: document.querySelector('.foo-cards'),
        search: document.querySelector('#form-hockey_v1'),
        download: document.querySelector('#downloadPDF')
    }

    _elem.relatedProducts.innerHTML = dynamicTemplates[tab].relatedProducts;
    _elem.topMenu.innerHTML = dynamicTemplates[tab].topMenu;
    _elem.footer.innerHTML = dynamicTemplates[tab].footer;
    // _elem.search.setAttribute('action', dynamicTemplates[tab].searchUrl);
    _elem.download.setAttribute('href', HELP_ROOT + dynamicTemplates[tab].pdfLink);
    relatedProuctsScriptBinding();
}

function getHelpRoot() {
    var path = window.location.pathname;

    // Normalize backslashes (in case of file protocol on Windows)
    path = path.replace(/\\/g, '/');

    // Match up to and including the /help/ folder
    var match = path.match(/^(.*?\/help\/)/i);

    if (match && match[1]) {
        return match[1]; // e.g., /itsf/build/help/
    }

    // Fallback: if /help/ not found, use full dirname
    return path.substring(0, path.lastIndexOf('/') + 1);
}

function expandParents(_anchor_) {
 var parent = _anchor_.parentNode;
while (parent && parent.tagName.toLowerCase() !== 'body') {
if (parent.tagName.toLowerCase() === 'li' && parent.classList.contains('has-children')) {
parent.classList.add('open');
var nestedUl = parent.querySelector('ul');
if (nestedUl) {
nestedUl.style.display = 'block';
 }
 }
// Stop when we reach the root ul with 'first-level-menu' class
if (parent.tagName.toLowerCase() === 'ul' && parent.classList.contains('first-level-menu')) {
break;
 }
parent = parent.parentNode;
 }
// Call separate scroll function
scrollActiveItemToCenter(_anchor_);
}
function scrollActiveItemToCenter(_anchor_, thresholdPercentage = 40) {
 // Scroll the active item to the specified threshold percentage of the lhs-section
var lhsSection = document.querySelector('.lhs-section');
if (lhsSection && _anchor_) {
var containerHeight = lhsSection.clientHeight;
var itemTop = _anchor_.offsetTop;
var itemHeight = _anchor_.offsetHeight;
var threshold = thresholdPercentage / 100;
var scrollTop = itemTop - (containerHeight * threshold) + (itemHeight / 2);
lhsSection.scrollTop = Math.max(0, scrollTop);
 }
}


function renderMenu(items,isFirstLevel) {
    if(isFirstLevel===undefined){isFirstLevel=true;}

    var ul = document.createElement('ul');
    var expandQueue = [];

    if(isFirstLevel){
        ul.className = 'first-level-menu';
    }
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        var li = document.createElement('li');

        if (item.url) {
            var a = document.createElement('a');

            var fullUrl = HELP_ROOT + item.url.replace(/^\/+/, '');
            a.setAttribute('href', fullUrl);
            a.textContent = item.title;

            if (isCurrentPage(fullUrl)) {
                a.className = 'active';
                expandQueue.push(a); // store for post-render expansion
            }

            li.appendChild(a);
        } else {
            var span = document.createElement('span');
            span.className = 'menu-label';
            span.textContent = item.title;
            li.appendChild(span);
        }

        if (item.children && item.children.length > 0) {
            li.className += ' has-children';
            var childUl = renderMenu(item.children,false);
            childUl.style.display = 'none';
            li.appendChild(childUl);
        }

        ul.appendChild(li);
    }

    // Expand active link ancestors outside the loop
    setTimeout(function () {
        for (var j = 0; j < expandQueue.length; j++) {
            expandParents(expandQueue[j]);
        }
    }, 0);

    return ul;
}

function isCurrentPage(itemUrl) {
    var current = window.location.pathname;

    // Strip host and protocol from itemUrl to compare path only
    var link = document.createElement('a');
    link.href = itemUrl;

    var normalizedLink = link.pathname.replace(/^\/+/, '');
    var normalizedCurrent = current.replace(/^\/+/, '');

    return normalizedLink === normalizedCurrent;
}

function injectSearchKeys(tab) {
    SEARCH_KEYS = OFFLINE_KEYS[tab];
}

function getFilteredNavData() {
    var selectedPlatforms = ['on-prem', 'common'];
    if (currentTab === 'cloud') {
        selectedPlatforms = ['cloud', 'common'];
    }

    return filterNavByPlatform(nav, selectedPlatforms);
}

function loadLHStree() {
    var selectedPlatforms = ['on-prem', 'common'];
    if (currentTab === 'cloud') {
        selectedPlatforms = ['cloud', 'common'];
    }

    var data = getFilteredNavData();
    var container = document.getElementById('lhs-menu');
    container.innerHTML = '';
    container.appendChild(renderMenu(data,true));

    // Tab highlight logic
    var tabs = document.querySelectorAll('.lhs-tabs a');
    for (var i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove('active');
    }

    var activeTab = document.querySelector('.lhs-tabs a[data-main-tab="' + currentTab + '"]');
    if (activeTab) {
        activeTab.classList.add('active');
    }
    appendDynamicTemplates(currentTab);
    injectSearchKeys(currentTab);

}

function switchTab(newTab) {
    currentTab = newTab;
    sessionStorage.setItem('mainTab', currentTab);
    // loadLHStree();
    if (currentTab === 'cloud') {
        window.location.href = HELP_ROOT + HELP_SWITCH_ROOT.cloud;
    } else {
        window.location.href = HELP_ROOT + HELP_SWITCH_ROOT.onprem;
    }
}

function relatedProuctsScriptBinding() {
    $('#relatedProducts h3').on('click', function () {
        $('#lhs-menu ul ul').slideUp(200);
        $('#lhs-menu li').removeClass('open');
        $(this).next('ul').slideToggle(200);
        $(this).toggleClass('open');
    });

    // $('.related-products li .short-desc').slideUp();
    $('.related-products li').on('mouseenter', function (e) {
        $(this).find('.short-desc').stop().slideDown();
    });
    $('.related-products li').on('mouseleave', function (e) {
        $(this).find('.short-desc').stop().slideUp();
    });
}

/**
 * Initializes all LHS related functions and event bindings
 */
function initLHS() {
    loadLHStree();
    // Tab click handler
    $('.lhs-tabs a').on('click', function () {
        switchTab($(this).data('main-tab'));
    });

    // Menu label click handler for expanding/collapsing
    $(document).on('click', '.menu-label', function () {
        const $parentLi = $(this).parent();
        const $siblings = $parentLi.siblings('.has-children');

        $('#relatedProducts ul').slideUp(200);
        $('#relatedProducts h3').removeClass('open');

        // Close all sibling menus
        $siblings.removeClass('open').children('ul').slideUp(200);

        // Toggle current menu
        $parentLi.toggleClass('open');
        $(this).siblings('ul').slideToggle(200);
    });
}

/**
 * Sets breadcrumbs based on current page and menu structure
 */
function setBreadcrumbs() {
    const data = currentTab === 'onPrem' ? nav : nav;
    let path = [];

    // Recursive search for currentFile in menu data
    function findPath(items, trail) {
        for (const item of items) {
            const newTrail = [...trail, item];
            if (item.url) {
                // Normalize file path for comparison
                const itemFileParts = item.url.split('/');
                const itemFileName = itemFileParts.pop();
                const itemFolderName = itemFileParts.length ? itemFileParts.pop() : null;

                const currentPathParts = location.pathname.split('/');
                const currentFileName = currentPathParts.pop();
                const currentFolderName = currentPathParts.length ? currentPathParts.pop() : null;

                let isMatch = false;
                if (itemFolderName) {
                    isMatch = (itemFileName === currentFile && itemFolderName === currentFolderName);
                } else {
                    isMatch = (itemFileName === currentFile);
                }

                if (isMatch) {
                    path = newTrail;
                    return true;
                }
            }
            if (item.children && findPath(item.children, newTrail)) {
                return true;
            }
        }
        return false;
    }

    findPath(data, []);

    // Home breadcrumb: set url based on currentTabwith-log360/standard-options/log-receiver.html
    const homeTitle = 'Home';
        let homeUrl ="";
        if( currentTab === 'onPrem'){
        homeUrl = HELP_ROOT + HELP_SWITCH_ROOT.onprem;
        } else if( currentTab === 'cloud'){
        homeUrl = HELP_ROOT + HELP_SWITCH_ROOT.cloud;
        } else if( currentTab === 'ela'){
        homeUrl = HELP_ROOT + HELP_SWITCH_ROOT.ela;
        }

    // Render breadcrumbs as <nav><ul><li>...</li></ul></nav>
    const $ul = $('<ul></ul>');

    // Add Home as first breadcrumb
    $ul.append(
        $('<li></li>').append(
            $('<a></a>').attr('href', homeUrl).text(homeTitle)
        )
    );

    path.forEach((item, idx) => {
        if (item.url && idx < path.length - 1) {
            $ul.append(
                $('<li></li>').append(
                    $('<a></a>').attr('href', item.url).text(item.title)
                )
            );
        } else {
            $ul.append(
                $('<li></li>')
                    .attr('aria-current', 'page')
                    .text(item.title)
            );
        }
    });
    $('#breadcrumbs').empty().append($ul);
}
function flatten(items) {
    let flatList = [];
    for (const item of items) {
        if (item.url) { flatList.push(item); }
        if (item.children) { flatList = flatList.concat(flatten(item.children)); }
    }
    return flatList;
}
/**
 * Appends bottom navigation (prev/next) links in .page-center based on current page
 */
function setBottomNavigation() {
    const data = getFilteredNavData();
    let flatList = flatten(data);
    // Flatten menu items recursively



    // Find current index
    const currentIndex = flatList.findIndex(item => {
        const itemFileParts = item.url.split('/');
        const itemFileName = itemFileParts.pop();
        const itemFolderName = itemFileParts.length ? itemFileParts.pop() : null;

        const currentPathParts = location.pathname.split('/');
        const currentFileName = currentPathParts.pop();
        const currentFolderName = currentPathParts.length ? currentPathParts.pop() : null;

        if (itemFolderName) {
            return itemFileName === currentFile && itemFolderName === currentFolderName;
        }
        return itemFileName === currentFile;
    });

    // Get prev/next items
    const prevItem = currentIndex > 0 ? flatList[currentIndex - 1] : null;
    const nextItem = currentIndex < flatList.length - 1 ? flatList[currentIndex + 1] : null;

    // Build navigation HTML
    const $nav = $('<nav class="btm-navigation"></nav>');
    if (prevItem) {
        $nav.append(
            $('<a></a>')
                .addClass('to-prev')
                .attr('href', HELP_ROOT + prevItem.url)
                .attr('aria-label', `Go to previous topic: ${prevItem.title} (level 2)`)
                .text('Previous Topic')
        );
    }
    if (nextItem) {
        $nav.append(
            $('<a></a>')
                .addClass('to-next')
                .attr('href', HELP_ROOT + nextItem.url)
                .attr('aria-label', `Go to next topic: ${nextItem.title} (level 2)`)
                .text('Next Topic')
        );
    }

    // Append or remove navigation in .page-center
    const $container = $('.page-center');
    $container.find('.btm-navigation').remove();
    if (prevItem || nextItem) {
        $container.append($nav);
    }
}

function initMediaViewer() {
    // Enlarge image on click
    $(document).on('click', '.image-pop', function () {
        const src = $(this).attr('src');
        const modalHtml = `
            <div id="myModal" class="myModal">
                <div id="innerModal" class="innerModal">
                    <img id="modal-content" class="modal-content" src="${src}">
                </div>
            </div>`;
        $('body').append(modalHtml).css({ overflow: 'hidden' });
        $('.help_top_pane').css('border-bottom', 'none');
    });

    // Close modal on background click or Escape key
    $(document).on('click', '.myModal', function () {
        $(this).remove();
        $('body').css({ overflow: 'auto' });
        $('.help_top_pane').css('border-bottom', '1px solid #eeeeee');
    });
    $(document).on('keydown', function (e) {
        if (e.key === 'Escape') {
            $('.myModal').remove();
            $('body').css({ overflow: 'auto' });
            $('.help_top_pane').css('border-bottom', '1px solid #eeeeee');
        }
    });

    // Toggle zoom on image click
    $(document).on('click', '#modal-content', function (e) {
        e.stopPropagation();
        $('#myModal, #innerModal, #modal-content').toggleClass('zoomed');
        $('#innerModal').toggleClass('innerZoomed');
        $('#modal-content').toggleClass('modal-zoomed');
    });
}

function animateSmoothScrollOnContentLinks() {
    /***
     * when clicking an link elements to smoothly transit to the destionation content
     */

    $('.page-center a[href^="#"]').click(function (e) {
        var target = $(this.hash);
        var x = target.offset().top + $('.page-center').scrollTop() - 99;
        $('html,body').stop().animate({
            'scrollTop': x
        }, 200);
    });
}

function pageClickevents() {
    $('.selected-lang').on('click', function () {
        $('.language-list').slideToggle(200);
    });
    $('.ql-tab span').on('click', function () {
        const $this = $(this);
        const tabId = $this.data('target');
        $('.ql-tab span').removeClass('active');
        $this.addClass('active');
        $('.ql-content').hide();
        $('.ql-content[data-content="' + tabId + '"]').fadeIn(200);
    });

    $('.lhs-mobile-trigger').on('click', function () {
        $('.page-lhs').toggleClass('open-lhs');
    });

    $('.hamburger-icon').on('click', function () {
        $(this).toggleClass('act');
        $('.main-menu').toggleClass('open');
    });

    $('.mobile-search-icon').on('click', function () {
        $('.menu-search-container').toggleClass('show');
    });

}

function initSearchResults(searchKeys) {
    var searchInput = document.getElementById('hockey_v1-query');
    var resultList = document.querySelector('#top-search-dropdown');
    if (!searchInput || !resultList || typeof searchKeys === 'undefined') { return; }
    var currentSelectedIndex = -1;
    var noResultsTemplate = `
        <li class="top-search-no-results">
            <div class="no-results-content">
                <p>No results found for your search.</p>
                <div class="search-external-link">
                    Try searching on the ManageEngine website:
                    <a href="#" target="_blank" id="external-search-link">
                    </a>
                </div>
            </div>
        </li>
    `;

    function updateExternalSearchLink(query) {
        var link = document.getElementById('external-search-link');
        if (link) {
            var baseUrl = dynamicTemplates[currentTab] && dynamicTemplates[currentTab].searchUrl
                ? dynamicTemplates[currentTab].searchUrl
                : 'https://www.manageengine.com/log-management/help/search-results.html';
            link.href = `${baseUrl}?query=${encodeURIComponent(query)}`;
            link.textContent = `${query}`;
        }
    }

    function renderResults(results, query) {
        resultList.innerHTML = '';
        currentSelectedIndex = -1;
        if (results.length === 0) {
            resultList.style.display = 'block';
            resultList.innerHTML = noResultsTemplate;
            updateExternalSearchLink(query);
            return;
        }
        resultList.style.display = 'block';
        results.forEach(function (item) {
            var li = document.createElement('li');
            var a = document.createElement('a');
            a.textContent = item.title;
            // Use HELP_ROOT for relative URLs
            var url = item.url.startsWith('http') ? item.url : HELP_ROOT + item.url.replace(/^\/+/, '');
            a.href = url.replace(/\\/g, '/');
            li.appendChild(a);
            resultList.appendChild(li);
        });
    }

    function updateSelection() {
        var items = resultList.querySelectorAll('li:not(.top-search-no-results)');
        items.forEach(function (item, index) {
            if (index === currentSelectedIndex) {
                item.classList.add('selected');
                // Scroll the selected item into view
                scrollIntoView(item);
            } else {
                item.classList.remove('selected');
            }
        });
    }

    function scrollIntoView(element) {
        var containerTop = resultList.scrollTop;
        var containerBottom = containerTop + resultList.clientHeight;
        var elementTop = element.offsetTop;
        var elementBottom = elementTop + element.offsetHeight;

        if (elementTop < containerTop) {
            // Element is above visible area
            resultList.scrollTop = elementTop;
        } else if (elementBottom > containerBottom) {
            // Element is below visible area
            resultList.scrollTop = elementBottom - resultList.clientHeight;
        }
    }

    // Track hovered index
    var hoveredIndex = -1;

    // Mouse hover event to update hoveredIndex
    resultList.addEventListener('mousemove', function (e) {
        var items = resultList.querySelectorAll('li:not(.top-search-no-results)');
        for (var i = 0; i < items.length; i++) {
            if (items[i] === e.target || items[i].contains(e.target)) {
                hoveredIndex = i;
                for (var j = 0; j < items.length; j++) {
                    if (j === hoveredIndex) {
                        items[j].classList.add('hovered');
                    } else {
                        items[j].classList.remove('hovered');
                    }
                }
                break;
            }
        }
    });

    // Mouse leave resets hoveredIndex
    resultList.addEventListener('mouseleave', function () {
        hoveredIndex = -1;
        var items = resultList.querySelectorAll('li:not(.top-search-no-results)');
        items.forEach(function (item) {
            item.classList.remove('hovered');
        });
    });

    searchInput.addEventListener('input', function (e) {
        var query = e.target.value.trim();
        if (!query) {
            resultList.innerHTML = '';
            resultList.style.display = 'none';
            return;
        }
        var queryLower = query.toLowerCase();
        var results = searchKeys.filter(function (item) {
            return item.keys.some(function (key) {
                return key.toLowerCase().includes(queryLower);
            }) || item.title.toLowerCase().includes(queryLower);
        });
        renderResults(results, query);
    });

    searchInput.addEventListener('keydown', function (e) {
        // Only handle arrow keys if the dropdown is visible and has results
        if (resultList.style.display === 'none' || resultList.innerHTML === '') {
            return;
        }

        var items = resultList.querySelectorAll('li:not(.top-search-no-results)');
        if (items.length === 0) { return; }

        // If hoveredIndex is set, use it as the starting point for arrow navigation
        if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && hoveredIndex !== -1) {
            currentSelectedIndex = hoveredIndex;
            hoveredIndex = -1; // Reset hoveredIndex after using it
        }

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            currentSelectedIndex++;
            if (currentSelectedIndex >= items.length) {
                currentSelectedIndex = 0; // Loop back to first item
            }
            updateSelection();
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            currentSelectedIndex--;
            if (currentSelectedIndex < 0) {
                currentSelectedIndex = items.length - 1; // Loop to last item
            }
            updateSelection();
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (currentSelectedIndex >= 0 && currentSelectedIndex < items.length) {
                var selectedLink = items[currentSelectedIndex].querySelector('a');
                if (selectedLink) {
                    window.location.href = selectedLink.href;
                }
            }
        } else if (e.key === 'Escape') {
            resultList.innerHTML = '';
            resultList.style.display = 'none';
            currentSelectedIndex = -1;
        }
    });

    document.addEventListener('click', function (e) {
        if (!resultList.contains(e.target) && e.target !== searchInput) {
            resultList.innerHTML = '';
            resultList.style.display = 'none';
            currentSelectedIndex = -1;
        }
    });
}

// Document ready: sequentially initialize LHS functions
$(document).ready(function () {

    // Initialize LHS menu and related products
    initLHS();

    // Call setBreadcrumbs after menu is loaded
    setBreadcrumbs();

    // Call bottom navigation after breadcrumbs
    setBottomNavigation();

    // Initialize media viewer for images
    initMediaViewer();

    // Initialize smooth scroll for content links 
    animateSmoothScrollOnContentLinks();

    // Initialize click events for page elements
    pageClickevents();

    // Call this function after DOM is ready
    initSearchResults(SEARCH_KEYS);

});

//ignorei18n_end