/**
 * @author Eternal
 */
// var nav_item_0;
// var nav_item_1;
var nav_item_2;
var	language_setup="zh";
var wifi_exist=0;
var wifi_enable=0;
var g4_exist=0;
var g4_enable=0;
var ndi_exist=0;
var default_primary_color = 'blue';
var theme_colors = {
	blue: '#066fd1',
	indigo: '#4263eb',
	pink: '#d63384',
	red: '#dc2626',
	orange: '#ea580c',
	yellow: '#ca8a04',
	lime: '#65a30d',
	green: '#16a34a',
	teal: '#0f766e',
	cyan: '#0891b2',
	violet: '#7c3aed',
	fuchsia: '#c026d3'
};
// var ndi_enable=0;
function get_current_theme() {
	return localStorage.getItem('theme') || 'light';
}

function get_current_primary_color() {
	var color = localStorage.getItem('primaryColor') || default_primary_color;
	return theme_colors[color] ? color : default_primary_color;
}

function hex_to_rgb_string(hex) {
	var normalized = String(hex || '').replace('#', '');
	if (normalized.length !== 6) return '6, 111, 209';
	return parseInt(normalized.substring(0, 2), 16) + ', ' +
		parseInt(normalized.substring(2, 4), 16) + ', ' +
		parseInt(normalized.substring(4, 6), 16);
}

function clamp_color_channel(value) {
	return Math.max(0, Math.min(255, value));
}

function darken_hex_color(hex, factor) {
	var normalized = String(hex || '').replace('#', '');
	if (normalized.length !== 6) return '#055cae';
	var scale = typeof factor === 'number' ? factor : 0.16;
	var red = clamp_color_channel(Math.round(parseInt(normalized.substring(0, 2), 16) * (1 - scale)));
	var green = clamp_color_channel(Math.round(parseInt(normalized.substring(2, 4), 16) * (1 - scale)));
	var blue = clamp_color_channel(Math.round(parseInt(normalized.substring(4, 6), 16) * (1 - scale)));
	return '#' + ('0' + red.toString(16)).slice(-2) + ('0' + green.toString(16)).slice(-2) + ('0' + blue.toString(16)).slice(-2);
}

function apply_theme_to_document(doc) {
	if (!doc || !doc.documentElement || !doc.documentElement.style) return;
	var theme = get_current_theme();
	var color_value = theme_colors[get_current_primary_color()];
	doc.documentElement.setAttribute('data-theme', theme);
	doc.documentElement.style.setProperty('--tblr-primary', color_value);
	doc.documentElement.style.setProperty('--tblr-primary-rgb', hex_to_rgb_string(color_value));
	doc.documentElement.style.setProperty('--tblr-primary-darken', darken_hex_color(color_value, 0.16));
}

function sync_theme_to_iframe() {
	var iframe = document.getElementById('subframe');
	if (!iframe) return;
	try {
		var iframe_doc = iframe.contentDocument || (iframe.contentWindow ? iframe.contentWindow.document : null);
		apply_theme_to_document(iframe_doc);
	} catch (e) {}
}

function apply_theme_settings() {
	apply_theme_to_document(document);
	sync_theme_to_iframe();
	update_theme_icon();
	update_color_indicator();
	update_theme_panel_selection();
}

function update_theme_icon() {
	var icon = document.getElementById('theme_toggle_icon');
	if (!icon) return;
	if (get_current_theme() === 'dark') {
		icon.innerHTML = '<path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 12m-4 0a4 4 0 1 0 8 0a4 4 0 1 0 -8 0" /><path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7" />';
	} else {
		icon.innerHTML = '<path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454z" />';
	}
}

function update_color_indicator() {
	var indicator = document.getElementById('color_indicator');
	if (!indicator) return;
	indicator.style.backgroundColor = theme_colors[get_current_primary_color()];
}

function update_tool_button_states() {
	var panel_visible = !$('#theme_color_panel').hasClass('display_off');
	$('#theme_color_toggle').toggleClass('is-active', panel_visible);
}

function update_theme_panel_selection() {
	var current = get_current_primary_color();
	$('#theme_color_panel .theme-color-option').removeClass('active');
	$('#theme_color_panel .theme-color-option[data-color="' + current + '"]').addClass('active');
	update_tool_button_states();
}

function render_theme_color_panel() {
	var $panel = $('#theme_color_panel');
	if (!$panel.length || $panel.children().length) return;
	for (var key in theme_colors) {
		if (!theme_colors.hasOwnProperty(key)) continue;
		$panel.append('<button type="button" class="theme-color-option" data-color="' + key + '" style="background-color:' + theme_colors[key] + ';" aria-label="' + key + '"></button>');
	}
	update_theme_panel_selection();
}

function close_theme_color_panel() {
	$('#theme_color_panel').addClass('display_off');
	update_tool_button_states();
}

function toggle_theme_color_panel() {
	$('#theme_color_panel').toggleClass('display_off');
	update_tool_button_states();
}

function set_primary_color(color_name) {
	if (!theme_colors[color_name]) return;
	localStorage.setItem('primaryColor', color_name);
	apply_theme_settings();
	close_theme_color_panel();
}

function toggle_theme_mode() {
	var next_theme = get_current_theme() === 'dark' ? 'light' : 'dark';
	localStorage.setItem('theme', next_theme);
	apply_theme_settings();
}

function setup_theme_switcher() {
	render_theme_color_panel();
	apply_theme_settings();
	$('#theme_color_toggle').unbind('click').bind('click', function (e) {
		e.stopPropagation();
		toggle_theme_color_panel();
	});
	$('#theme_toggle').unbind('click').bind('click', function () {
		toggle_theme_mode();
	});
	$('#theme_color_panel').undelegate('.theme-color-option', 'click').delegate('.theme-color-option', 'click', function (e) {
		e.stopPropagation();
		set_primary_color($(this).attr('data-color'));
	});
	$(document).unbind('click.themepanel').bind('click.themepanel', function (e) {
		if (!$(e.target).closest('#theme_color_wrap').length) {
			close_theme_color_panel();
		}
	});
}

function get_i18n_text(key, fallback) {
	try {
		var text = $.i18n.prop(key);
		if (text && text !== key && text !== ('[' + key + ']')) {
			return text;
		}
	} catch (e) {}
	return fallback;
}

function init_menu_option(){
	$.ajax({
	    type: "GET",
	    url: "http://" + xc_gethost() + "/get_wifi",
		async: false,
	    dataType: "xml",
	    cache: false,
	    error: function () {
	    },
	    success: function (data) {
	    	var wifi_dev_exist=$(data).find("wifi_dev_exist").text();
	    	if(wifi_dev_exist==1){
	    		$("#wifi_option").removeClass("display_off");
	    		wifi_exist=1;
	    	}else if(wifi_dev_exist==0){
	    		$("#wifi_option").addClass("display_off");
	    		wifi_exist=0;
	    	}
			wifi_enable = $(data).find("wifi_enable").text();
			nav_item_2 = $("#main_nav .nav_item:eq(2)").next("ul").height();
	    }
	});

	$.ajax({
		type: "GET",
	    url: "http://" + xc_gethost() + "/get_g4",
		async: false,
	    dataType: "xml",
	    cache: false,
	    error: function () {
	    },
	    success: function (data) {
	    	g4_exist=$(data).find("g4_exist").text();
	    	if(g4_exist==1){
	    		$("#g4_option").removeClass("display_off");
	    	}else if(g4_exist==0){
	    		$("#g4_option").addClass("display_off");
	    	}
			g4_enable = $(data).find("g4_enable").text();
	    }
	});

	$.ajax({
		type: "GET",
	    url: "http://" + xc_gethost() + "/get_status",
		async: false,
	    dataType: "xml",
	    cache: false,
	    error: function () {
	    },
		success: function (data) {
	    	var show_switcher=$(data).find("show_switcher").text();
	    	if(show_switcher==1){
	    		$("#video_switch_option").removeClass("display_off");
				$("#video_turn_option").removeClass("display_off");
	    	}else if(show_switcher==0){
	    		$("#video_switch_option").addClass("display_off");
				$("#video_turn_option").addClass("display_off");
	    	}
			nav_item_2 = $("#main_nav .nav_item:eq(2)").next("ul").height();
			
	    	ndi_exist=$(data).find("ndi").text();
	    	if(ndi_exist==1){
	    		$("#ndi_option").removeClass("display_off");
	    	}else if(ndi_exist==0){
	    		$("#ndi_option").addClass("display_off");
	    	}
	    }
	});
	
	$.ajax({
		type: "GET",
	    url: "http://" + xc_gethost() + "/get_frp",
		async: false,
	    dataType: "xml",
	    cache: false,
	    error: function () {
	    },
	    success: function (data) {
	    	var showfrp=$(data).find("showfrp").text();
	    	if(showfrp==1){
	    		$("#frp_option").removeClass("display_off");
	    	}else if(showfrp==0){
	    		$("#frp_option").addClass("display_off");
	    	}
			nav_item_2 = $("#main_nav .nav_item:eq(2)").next("ul").height();
	    }
	});
}

function init_language(){
	// language_setup=$.cookie('language_setup');
	// if(language_setup==null){
		language_setup = getlanguage();
		if(language_setup == null){
			language_setup = navigator.language;
			if(!language_setup){
				language_setup = navigator.browserLanguage;
			}
		}
	// }
	language_setup=language_setup.toLowerCase();
}

function get_language_setup(){
		return language_setup;
}

function get_wifi_exist(){
	return wifi_exist;
}
function get_wifi_enable(){
	return wifi_enable;
}
function get_g4_exist(){
	return g4_exist;
}
function get_g4_enable(){
	return g4_enable;
}	
function setup_current_language(){
	jQuery.i18n.properties({
		name: 'common',
		path: 'lang/',
		mode: 'map',
		language: get_language_setup(),
		callback: function () {
			$('#index_status').html($.i18n.prop('index_status'));
			$('#index_playlist').html($.i18n.prop('index_playlist'));
			$('#index_system').html($.i18n.prop('index_system'));
			$('#index_advance').html($.i18n.prop('index_advance'));
			$('#index_deviceinfo').html($.i18n.prop('index_deviceinfo'));
			$('#index_network').html($.i18n.prop('index_network'));
			$('#index_wifi').html($.i18n.prop('index_wifi'));
			$('#index_g4').html($.i18n.prop('index_g4'));
			$('#index_ndi').html($.i18n.prop('index_ndi'));
			$('#index_remserial').html($.i18n.prop('index_remserial'));
			$('#index_frp').html($.i18n.prop('index_frp'));
			$('#index_pwd').html($.i18n.prop('index_pwd'));
			$('#index_systemout').html($.i18n.prop('index_systemout'));
			$('#index_chnlayout').html($.i18n.prop('index_chnlayout'));
			$('#index_layoutset').html($.i18n.prop('index_layoutset'));
			$('#index_osdsetup').html($.i18n.prop('index_osdsetup'));
			$('#index_cropsetup').html($.i18n.prop('index_cropsetup'));
			$('#index_videoswitch').html($.i18n.prop('index_videoswitch'));
			$('#index_videoturn').html($.i18n.prop('index_videoturn'));
			$('#index_factory').html($.i18n.prop('index_factory'));
			$('#index_update').html($.i18n.prop('index_update'));
			$('#index_reset').html($.i18n.prop('index_reset'));
			$('#index_reboot').html($.i18n.prop('index_reboot'));
			$('#index_restart').html($.i18n.prop('index_restart'));
			$('#index_language').html($.i18n.prop('index_language'));
			$('head title').html($.i18n.prop('index_title'));
			$('#theme_color_toggle').attr('title', get_i18n_text('encoding_choose_primary_color', 'Primary color'));
			$('#theme_toggle').attr('title', get_i18n_text('encoding_toggle_theme', 'Toggle theme'));
		}
	});
}

function setup_iframe_height(){
	var subpage_content_height=$("#subframe").contents().find("#main_content").outerHeight(true);
	// 设置实际需要的高度，不强制最小高度或额外增加高度
	if(subpage_content_height) {
		$("#subframe").height(subpage_content_height);
	}
}

function iframe_adjust_height(){
	var iframe = document.getElementById("subframe");
	if (iframe.attachEvent) {
		iframe.attachEvent("onload", function() {
			setup_iframe_height();
			sync_theme_to_iframe();
		});            
	} else {
		iframe.onload = function() {
			setup_iframe_height();
			sync_theme_to_iframe();
		};
	}
}

function change_event_handle(){
	var language_value=$("#LanSle option:selected").attr("value");
	var language_map = {
		"English": "en",
		"Chinese": "zh",
		"ChineseTW": "zh-tw",
		"German": "de",
		"Spanish": "es",
		"French": "fr",
		"Japanese": "ja",
		"Italian": "it",
		"Korean": "ko",
		"Portuguese": "pt",
		"Russian": "ru",
		"Turkish": "tr"
	};

	if(language_map[language_value]){
		language_setup = language_map[language_value];
		setup_current_language();
		var last_src=$("#subframe").attr("src");
		$("#subframe").attr("src","");
		$("#subframe").attr("src",last_src);
		// 更新面包屑导航
		updateBreadcrumb(last_src);
	}
	setlanguage(language_setup);
}

function init_language_select(){
	var lang_code = language_setup.toLowerCase();
	var language_select_map = {
		"en": "English",
		"en-us": "English",
		"zh": "Chinese",
		"zh-cn": "Chinese",
		"zh-tw": "ChineseTW",
		"de": "German",
		"es": "Spanish",
		"fr": "French",
		"ja": "Japanese",
		"it": "Italian",
		"ko": "Korean",
		"pt": "Portuguese",
		"ru": "Russian",
		"tr": "Turkish"
	};

	if(language_select_map[lang_code]){
		$("#LanSle").val(language_select_map[lang_code]);
		// Keep the language_setup as is for selected language
		if(lang_code == "en-us") language_setup = "en";
		if(lang_code == "zh-cn") language_setup = "zh";
	}else{
		$("#LanSle").val("English");
		language_setup="en";
	}
}

// 面包屑导航映射表
var breadcrumbMap = {
	'iframe/status.html': {main: 'index_status'},
	'iframe/playlist.html': {main: 'index_playlist'},
	'iframe/layoutset.html': {main: 'index_advance', sub: 'index_layoutset'},
	'iframe/crop.html': {main: 'index_advance', sub: 'index_cropsetup'},
	'iframe/osd.html': {main: 'index_advance', sub: 'index_osdsetup'},
	'iframe/deviceinfo.html': {main: 'index_system', sub: 'index_deviceinfo'},
	'iframe/network.html': {main: 'index_system', sub: 'index_network'},
	'iframe/wifi_config.html': {main: 'index_system', sub: 'index_wifi'},
	'iframe/g4_config.html': {main: 'index_system', sub: 'index_g4'},
	'iframe/ndi.html': {main: 'index_system', sub: 'index_ndi'},
	'iframe/remserial.html': {main: 'index_system', sub: 'index_remserial'},
	'iframe/frp.html': {main: 'index_system', sub: 'index_frp'},
	'iframe/pwd.html': {main: 'index_system', sub: 'index_pwd'},
	'iframe/system.html': {main: 'index_system', sub: 'index_systemout'},
	'iframe/videoswitch.html': {main: 'index_advance', sub: 'index_videoswitch'},
	'iframe/videoturn.html': {main: 'index_advance', sub: 'index_videoturn'},
	'iframe/factory.html': {main: 'index_system', sub: 'index_factory'},
	'iframe/update.html': {main: 'index_system', sub: 'index_update'},
	'iframe/reset.html': {main: 'index_system', sub: 'index_reset'},
	'iframe/reboot.html': {main: 'index_system', sub: 'index_reboot'},
	'iframe/restart.html': {main: 'index_system', sub: 'index_restart'}
};

function updateBreadcrumb(this_href) {
	var breadcrumb = breadcrumbMap[this_href];
	var breadcrumbText = '';
	
	if (breadcrumb) {
		// 获取主菜单文本
		var mainText = $('#' + breadcrumb.main).html() || '';
		
		if (breadcrumb.sub) {
			// 有子菜单时显示层级关系
			var subText = $('#' + breadcrumb.sub).html() || '';
			breadcrumbText = mainText + ' > ' + subText;
		} else {
			// 只有主菜单时直接显示
			breadcrumbText = mainText;
		}
	}
	
	$('#breadcrumb_text').html(breadcrumbText);
}

function main_iframe_change(this_href) {
	$("#right iframe").attr("src", this_href);
	updateBreadcrumb(this_href);
}
	

$(function () {
	// nav_item_0=$("#main_nav .nav_item:eq(0)").next("ul").height();
	// nav_item_1=$("#main_nav .nav_item:eq(1)").next("ul").height();
	nav_item_2 = $("#main_nav .nav_item:eq(2)").next("ul").height();

	$("#main_nav li .nav_item").hover(function () {
		$(this).addClass("select_nav_item");
		$(this).animate({
			paddingRight: "15px"
		}, 100);
	}, function () {
		$(this).removeClass("select_nav_item");
		$(this).animate({
			paddingRight: "15px"
		}, 100);
	});

	$("#main_nav li .nav_item").click(function () {
		var self = $(this);
		$("#main_nav li .nav_item").removeClass("select_nav_item").mouseout(function () {
			$(this).removeClass("select_nav_item");
			$(this).animate({
				paddingRight: "15px"
			}, 100);
		});
		$("#main_nav li .nav_item").not(self).animate({
			paddingRight: "15px"
		}, 100);
		$("#main_nav li .nav_item[value='have_secondary_nav']").not(self).removeClass("menu_expanded");
		if ($(this).attr("value") == "have_secondary_nav") {
			if ($(this).next("ul").attr("value") == "off") {
				$(this).next("ul").attr("style", "height:0px;").removeClass("display_off").addClass("display_on").animate({
					height: nav_item_2
				}, 100,function(){
					$(this).removeAttr("style");
				}).attr("value", "on");
				$(this).addClass("menu_expanded");
			} else {
				$(this).next("ul").animate({
					height: "0px"
				}, 100, function () {
					$(this).removeAttr("style");
					$(this).removeClass("display_on");
					$(this).addClass("display_off");
				}).attr("value", "off");
				$(this).removeClass("menu_expanded");
			}
		} else {
			$("#main_nav .main_nav_li span:eq(2)").next("ul").animate({
				height: "0px"
			}, 100, function () {
				$(this).removeAttr("style");
				$(this).removeClass("display_on");
					$(this).addClass("display_off");
			}).attr("value", "off");
			$("#main_nav li .nav_item[value='have_secondary_nav']").removeClass("menu_expanded");
			$(".secondary_nav li span").removeClass("select_secondary_nav").mouseout(function () {
				$(this).removeClass("select_secondary_nav");
				$(this).animate({
					paddingRight: "15px"
				}, 100);
			}).animate({
				paddingRight: "15px"
			}, 100);
		}
		$(this).addClass("select_nav_item");
		$(this).unbind("mouseout");
	});

	$(".secondary_nav li span").hover(function () {
		$(this).addClass("select_secondary_nav");
		$(this).animate({
			paddingRight: "15px"
		}, 100);
	}, function () {
		$(this).removeClass("select_secondary_nav");
		$(this).animate({
			paddingRight: "15px"
		}, 100);
	});

	$(".secondary_nav li span").click(function () {
		var self = $(this);
		$(".secondary_nav li span").removeClass("select_secondary_nav").mouseout(function () {
			$(this).removeClass("select_secondary_nav");
			$(this).animate({
				paddingRight: "15px"
			}, 100);
		});
		$(".secondary_nav li span").not(self).animate({
			paddingRight: "15px"
		}, 100)
		$(this).addClass("select_secondary_nav");
		$(this).unbind("mouseout");
	});
	
	$(window).resize(function(){
		iframe_adjust_height();
	});
	
	init_menu_option();
	init_language();
	init_language_select();
	setup_theme_switcher();
	setup_current_language();
	iframe_adjust_height();
	// 初始化时设置默认页面和面包屑
	var defaultPage = 'iframe/status.html';
	main_iframe_change(defaultPage);
	$("#main_nav li .nav_item:eq(0)").trigger("click");
});
