var current_theme_name = "light";

$(function() {
	current_theme_name = $.cookie('theme');
	if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
		current_theme_name = "dark";
	}
	window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
		current_theme_name = e.matches ? "dark" : "light";
		setTheme(current_theme_name);
	});
	setTheme(current_theme_name);
	
	$('#themechange').click(function(e) {
		var theme = current_theme_name;
		theme = theme == 'light' ? 'dark' : 'light';
		setTheme(theme);
	});
});

function setTheme(theme='light') {
	theme = (theme != 'light' && theme != 'dark') ? 'light' : theme;
	
	$('.control img, .header img').each(function() {
		var src = $(this).attr('src').replaceAll('/light/', '/'+theme+'/').replaceAll('/dark/', '/'+theme+'/');
		$(this).attr('src', src)
	});
	
	var head = document.getElementsByTagName("head")[0]; 
	var links = head.getElementsByTagName('link');
	$(links).each(function() {
		var href = $(this).attr('href');
		if((href.indexOf("light.css") !== -1))
			head.removeChild($(this)[0]);
		if((href.indexOf("dark.css") !== -1))
			head.removeChild($(this)[0]);
	});
	var link = document.createElement("link"); 
	link.rel = "stylesheet"; 
	link.type = "text/css"; 
	link.href = 'css/' + theme + '.css';
	head.appendChild(link);
	current_theme_name = theme;

	$.cookie('theme', theme, {expires:30});
	DataTableView.setTheme(theme);
}
