 // 初始化导航栏拖动功能
    function initDragScroll() {
        var secondaryNav = document.querySelector('.secondary-nav');
        if (!secondaryNav) return;
        
        var isDown = false;
        var startX;
        var scrollLeft;
        
        // 鼠标按下事件 - 开始拖动
        secondaryNav.addEventListener('mousedown', function(e) {
            isDown = true;
            secondaryNav.style.cursor = 'grabbing';
            startX = e.pageX - secondaryNav.offsetLeft;
            scrollLeft = secondaryNav.scrollLeft;
            e.preventDefault(); // 防止拖动过程中选中文本
        });
        
        // 鼠标离开/抬起事件 - 停止拖动
        secondaryNav.addEventListener('mouseleave', function() {
            isDown = false;
            secondaryNav.style.cursor = 'grab';
        });
        
        secondaryNav.addEventListener('mouseup', function() {
            isDown = false;
            secondaryNav.style.cursor = 'grab';
        });
        
        // 鼠标移动事件 - 执行拖动滚动
        secondaryNav.addEventListener('mousemove', function(e) {
            if (!isDown) return;
            e.preventDefault();
            var x = e.pageX - secondaryNav.offsetLeft;
            var walk = (x - startX) * 2; // 滚动速度倍增器
            secondaryNav.scrollLeft = scrollLeft - walk;
        });
        
        // 鼠标滚轮事件 - 水平滚动
        secondaryNav.addEventListener('wheel', function(e) {
            e.preventDefault();
            secondaryNav.scrollLeft += e.deltaY;
        });
    }
    
    // 初始化页面
    window.onload = function() {
        loadTheme(); // 先载入主题
        resizeVideoContainer();
        initDragScroll(); // 初始化导航拖动功能
        
        // 初始化下拉菜单
        initDropdownMenu();
        
        // Search Icon Toggle
        const searchIcon = document.getElementById('search-icon');
        const searchPopout = document.getElementById('search-popout');
        if (searchIcon && searchPopout) {
            searchIcon.addEventListener('click', function(event) {
                event.stopPropagation(); // Prevent click from closing immediately
                searchPopout.classList.toggle('active');
                if (searchPopout.classList.contains('active')) {
                    // Optional: focus the input when shown
                    searchPopout.querySelector('input[type="text"]').focus();
                }
            });

            // Close popout if clicking outside
            document.addEventListener('click', function(event) {
                if (!searchPopout.contains(event.target) && !searchIcon.contains(event.target)) {
                    searchPopout.classList.remove('active');
                }
            });
             // Prevent form submission from closing popout immediately (optional)
             searchPopout.querySelector('form').addEventListener('submit', function() {
                 setTimeout(() => { searchPopout.classList.remove('active'); }, 100);
             });
        }

        // 设置MutationObserver来监控iframe内容变化
        var iframe = document.getElementsByName("foyin")[0];
        if (iframe) {
            // 检测iframe加载完成
            iframe.addEventListener('load', function() {
                var currentTheme = localStorage.getItem('theme') || document.body.className;
                applyThemeToIframe(currentTheme);
                
                // 尝试设置MutationObserver以监控iframe内容变化
                try {
                    if (iframe.contentDocument) {
                        var observer = new MutationObserver(function(mutations) {
                            applyThemeToIframe(currentTheme);
                        });
                        
                        observer.observe(iframe.contentDocument, {
                            childList: true,
                            subtree: true
                        });
                    }
                } catch(e) {
                    console.log("无法监控iframe内容变化:", e);
                }
            });
        }
    };
    
    // 初始化下拉菜单
    function initDropdownMenu() {
        var menuItems = document.querySelectorAll('.main-nav li');
        
        // 处理触摸设备上的点击事件
        menuItems.forEach(function(item) {
            var hasDropdown = item.querySelector('.dropdown-menu');
            
            if (hasDropdown) {
                var link = item.querySelector('a');
                var isTouch = false;
                
                // 对于移动设备，第一次点击显示菜单，第二次才跳转
                link.addEventListener('touchstart', function() {
                    isTouch = true;
                });
                
                link.addEventListener('click', function(e) {
                    if (isTouch && !item.classList.contains('menu-open')) {
                        e.preventDefault();
                        // 关闭其他打开的菜单
                        menuItems.forEach(function(otherItem) {
                            if (otherItem !== item) {
                                otherItem.classList.remove('menu-open');
                            }
                        });
                        item.classList.toggle('menu-open');
                    }
                });
            }
        });
        
        // 确保鼠标离开时关闭菜单
        document.addEventListener('mouseover', function(e) {
            var inMenu = false;
            var target = e.target;
            
            while (target && target !== document) {
                if (target.classList && (target.classList.contains('main-nav') || target.classList.contains('dropdown-menu'))) {
                    inMenu = true;
                    break;
                }
                target = target.parentNode;
            }
            
            if (!inMenu) {
                menuItems.forEach(function(item) {
                    item.classList.remove('menu-open');
                });
            }
        });
    }
    
    function updateNavWidth() {
    var nav = document.querySelector(".main-nav");
    var viewportWidth = window.innerWidth;

    if (viewportWidth < 1420) {
        nav.style.maxWidth = "25%";
        nav.style.marginRight = "20px";
    } else if (viewportWidth >= 1920) {
        nav.style.maxWidth = "50%";
        nav.style.marginRight = "60px";
    } else {
        nav.style.maxWidth = ""; // 其他情况使用默认 CSS
        nav.style.marginRight = ""; 
    }
}

// 页面加载时执行一次
updateNavWidth();

// 监听页面大小变化
window.addEventListener("resize", updateNavWidth);


  // 全局变量记录当前主题
    var currentTheme = 'day';
    
    // 页面加载完成后初始化主题
    document.addEventListener('DOMContentLoaded', function() {
        // 从localStorage加载主题设置
        loadTheme();
        
        // 监听所有链接点击，记录当前主题到会话存储
        document.addEventListener('click', function(e) {
            // 更新会话存储中的主题，这样即使页面刷新也能保持状态
            sessionStorage.setItem('theme', currentTheme);
        });
    });
    
    // 从本地存储中加载主题设置
    function loadTheme() {
        // 优先使用会话存储中的主题（处理刷新页面的情况）
        var savedTheme = sessionStorage.getItem('theme') || localStorage.getItem('theme') || 'day';
        console.log("加载主题，当前保存的主题是:", savedTheme);
        
        // 更新全局变量
        currentTheme = savedTheme;
        
        // 应用主题到主页面
        applyTheme(savedTheme);
        
        // 更新按钮文本
        updateButtonText(savedTheme);
        
        // 应用主题到iframe
        applyThemeToIframe(savedTheme);
        
        // 设置定期检查iframe主题的计时器，确保iframe内容变化时主题仍然保持
        setInterval(function() {
            refreshIframeTheme();
        }, 1000);
    }
    
    // 定期检查并刷新iframe主题
    function refreshIframeTheme() {
        var iframe = document.getElementsByName("foyin")[0];
        if (iframe && iframe.contentWindow) {
            try {
                // 设置一个特殊的cookie，iframe可以读取这个cookie
                document.cookie = "pageTheme=" + currentTheme + "; path=/; max-age=3600";
                
                // 直接尝试应用样式
                applyThemeToIframe(currentTheme);
            } catch(e) {
                console.log("刷新iframe主题时出错:", e);
            }
        }
    }
    
    // 切换主题
    function switchTheme() {
        console.log("切换主题被调用");
        
        // 切换主题
        var newTheme = currentTheme === "day" ? "night" : "day";
        console.log("新主题将设置为:", newTheme);
        
        // 更新全局变量
        currentTheme = newTheme;
        
        // 同时保存到localStorage和sessionStorage
        localStorage.setItem('theme', newTheme);
        sessionStorage.setItem('theme', newTheme);
        
        // 设置cookie，让iframe可以读取
        document.cookie = "pageTheme=" + newTheme + "; path=/; max-age=3600";
        
        // 应用新主题到主页面
        applyTheme(newTheme);
        
        // 更新按钮文本
        updateButtonText(newTheme);
        
        // 应用主题到iframe
        applyThemeToIframe(newTheme);
        
        return false; // 防止链接默认行为
    }
    
    // 应用主题到主页面
    function applyTheme(theme) {
        // 先移除所有可能的类名
        document.body.classList.remove("day", "night");
        document.body.classList.add(theme);
        console.log("body类已更新为:", document.body.className);
    }
    
    // 更新按钮文本
    function updateButtonText(theme) {
        var btnSwitch = document.getElementById("btnSwitch");
        if (btnSwitch) {
            btnSwitch.innerHTML = theme === "night" ? "浅色模式" : "深色模式";
            console.log("按钮文本已更新为:", btnSwitch.innerHTML);
        }
    }
    
    // 将主题应用到iframe的函数
    function applyThemeToIframe(theme) {
        try {
            var iframe = document.getElementsByName("foyin")[0];
            if (!iframe) return;
            
            try {
                // 如果iframe还没完全加载，等待它加载完成
                if (!iframe.contentDocument || !iframe.contentWindow || !iframe.contentWindow.document.body) {
                    console.log("iframe未完全加载，等待中...");
                    return; // 由setInterval定期检查
                }
                
                // 设置iframe的URL查询参数
                if (iframe.src.indexOf('?') === -1) {
                    // 如果当前URL没有查询参数，添加主题参数
                    if (iframe.src && !iframe.src.includes('theme=')) {
                        var separator = iframe.src.includes('?') ? '&' : '?';
                        // 不直接修改src，而是使用postMessage通信
                    }
                }
                
                // 向iframe传递主题信息
                iframe.contentWindow.postMessage({
                    action: 'setTheme',
                    theme: theme
                }, '*');
                
                // 直接修改iframe内的样式作为备份方法
                if (theme === "night") {
                    try {
                        var styleElement = iframe.contentDocument.getElementById("night-mode-style");
                        if (!styleElement) {
                            styleElement = iframe.contentDocument.createElement('style');
                            styleElement.id = "night-mode-style";
                            styleElement.textContent = `
                                .t2 { background: #1f1f1f !important; color: #6d6b6b !important; }
                                body { background: #1f1f1f !important; color: #6d6b6b !important; }
                                a { color: #6F6F6F !important; }
                            `;
                            iframe.contentDocument.head.appendChild(styleElement);
                        }
                    } catch(e) {
                        console.log("无法直接设置iframe样式:", e);
                    }
                } else {
                    try {
                        var darkStyle = iframe.contentDocument.getElementById("night-mode-style");
                        if (darkStyle) darkStyle.parentNode.removeChild(darkStyle);
                    } catch(e) {
                        console.log("无法移除iframe样式:", e);
                    }
                }
            } catch(e) {
                console.log("应用样式到iframe失败:", e);
            }
        } catch(e) {
            console.log("应用主题到iframe时出错:", e);
        }
    }
    
    // 监听来自iframe的消息
    window.addEventListener('message', function(event) {
        // 如果iframe请求当前主题
        if (event.data && event.data.action === 'getTheme') {
            // 向iframe发送当前主题
            try {
                event.source.postMessage({
                    action: 'setTheme',
                    theme: currentTheme
                }, '*');
            } catch(e) {
                console.log("", e);
            }
        }
    });
    
    // 修改Play函数，确保在切换iframe内容时保持主题
    function Play(id) {
        // 记录当前使用的主题
        sessionStorage.setItem('theme', currentTheme);
        
        // 在URL中添加主题参数
        var themeParam = "theme=" + currentTheme;
        var url = "n/f" + id;
        if (url.indexOf('?') === -1) {
            url += "?" + themeParam;
        } else {
            url += "&" + themeParam;
        }
        
        var iframe = document.getElementsByName("foyin")[0];
        
        // 记住原始onload处理函数
        var originalOnload = iframe.onload;
        
        // 设置新的onload处理函数
        iframe.onload = function() {
            // 延迟应用主题以确保iframe已完全加载
            setTimeout(function() {
                applyThemeToIframe(currentTheme);
            }, 100);
            
            // 再次延迟检查，确保样式被正确应用
            setTimeout(function() {
                applyThemeToIframe(currentTheme);
            }, 500);
            
            // 调用原始onload函数(如果有)
            if (typeof originalOnload === 'function') {
                originalOnload();
            }
        };
        
        // 更改iframe的src，添加主题参数
        iframe.src = url;
    }
	
	
	  // Responsive video container sizing with resolution detection
        function resizeVideoContainer() {
            var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            var mainContent = document.querySelector('.main-content');
            var videoContainer = document.querySelector('.video-container');
            
            // 根据分辨率调整页面布局
            if (windowWidth <= 1100) {
                document.querySelectorAll('.episode').forEach(function(el) {
                    el.style.padding = '6px 10px';
                    el.style.fontSize = '13px';
                });
            } else {
                document.querySelectorAll('.episode').forEach(function(el) {
                    el.style.padding = '8px 12px';
                    el.style.fontSize = '14px';
                });
            }
        }
        
        // IE8 compatible event listener
        if (window.addEventListener) {
            window.addEventListener('resize', resizeVideoContainer);
            window.addEventListener('load', resizeVideoContainer);
        } else if (window.attachEvent) {  // IE8
            window.attachEvent('onresize', resizeVideoContainer);
            window.attachEvent('onload', resizeVideoContainer);
        }

        // 标签切换功能
        document.addEventListener('DOMContentLoaded', function() {
            // 获取所有标签项和内容区
            var tabItems = document.querySelectorAll('.tab-item');
            var tabContents = document.querySelectorAll('.tab-content');
            
            // 鼠标悬停切换标签
            tabItems.forEach(function(item) {
                item.addEventListener('mouseenter', function() {
                    // 移除所有active类
                    tabItems.forEach(function(tab) {
                        tab.classList.remove('active');
                    });
                    tabContents.forEach(function(content) {
                        content.classList.remove('active');
                    });
                    
                    // 添加当前标签的active类
                    this.classList.add('active');
                    
                    // 显示对应内容
                    var tabId = this.getAttribute('data-tab');
                    document.getElementById(tabId).classList.add('active');
                });
            });
        });