var clock = null;
var currentMinute = -1;

function highlightCurrentTime() {
	var now = new Date();
	var hour = now.getHours();
	var minute = now.getMinutes();
	if (minute == currentMinute) {
		return;
	}
	currentMinute = minute;
	resetItems();
	var dotMinute = minute % 5;
	var coarseMinute = minute - dotMinute;
	for (var i = 1; i <= dotMinute; i++) {
		highlight('dot' + i);
	}
	highlight('minute' + coarseMinute);
	if (coarseMinute >= 25) {
		hour++;
	}
	hour = normalizeHour(hour);
	highlight('hour'+hour);
}

function clearDisplay() {
	$('.item').removeClass('active');
}
function resetItems() {
	clearDisplay()
	highlight('es');
	highlight('isch');
}

function highlight(itemClass) {
	$('.item.' + itemClass).addClass('active');
}

function normalizeHour(hour) {
	if (hour > 12) {
		hour %= 12;
	}
	if (hour == 0) {
		return 12;
	}
	return hour;
}

function startClock() {
	if (clock == null) {
		clock = window.setInterval(highlightCurrentTime, 1000);
	}
}

function stopClock() {
	if (clock != null) {
		window.clearInterval(clock);
		clock = null;
		currentMinute = -1;
		clearDisplay();
	}
}

function updateClockState() {
	if ($('#onoffswitch').is(':checked')) {
		startClock();
	} else {
		stopClock();
	}
}
function switchTheme(element) {
	var theme = $(element).val()
	$('#theme').attr('href', 'uhr-' + theme + '.css');
}

function render(layout) {
	var container = $('#renderarea');
	for (var y = 0; y < layout.values.length; y++) {
		for (var x = 0; x < layout.values[y].length; x++) {
			var letter = layout.values[y][x];
			container.append(letter.toString());
		}
		if (y < layout.values.length - 1) {
			container.append('<br/>');
		}
	}
}

function Letter(value, style = '') {
	this.value = value;
	this.style = style;
	this.getStyle = function() {
		return "item letter " + style;
	}
	this.getValue = function() {
		return value;
	}
}
Letter.prototype.toString = function letterToString() {
	return "<span class=\"" + this.getStyle() + "\">" + this.getValue() + "</span>";
}
function l(letter, style) {
	return new Letter(letter, style);
}
function h(letter, hour) {
	return l(letter, 'hour' + hour);
}
function m(letter) {
	var style = '';
	for (var i = 1; i < arguments.length; i++) {
		style += ' minute' + arguments[i];
	}
	return l(letter, style);
}