(function() {
	
	var exports = {};
	
	exports.update = function(data)
	{
		data = data || {};
		var templates = data.templates;
		var settingsHTML = data.settings;
		
		// Templates
		var templateContainer = document.querySelector("#template-rows");
		templateContainer.innerHTML = "";
		if (templates) {
			for (var i = 0; i < templates.length; i++) {
				this.addTemplate(templates[i]);
			}
			
			document.querySelector("#uistate-templates").className = templates.length == 0 ? "hidden" : "";
			document.querySelector("#uistate-no-templates").className = templates.length != 0 ? "hidden" : "";
		}
		else {
			document.querySelector("#uistate-templates").className = "hidden";
			document.querySelector("#uistate-no-templates").className = "hidden";
		}
		
		// Settings
		document.querySelector("#uistate-settings").className = settingsHTML ? "" : "hidden";
		document.querySelector("#template-settings").innerHTML = settingsHTML;
		var scripts = document.querySelectorAll("#template-settings script");
		for (var i = 0; i < scripts.length; i++) {
			eval(scripts[i].innerText);
		}
	};
	
	exports.addTemplate = function (data) {
		data = data || {};
		var template = document.querySelector('#template-row');
		var description = data.description || "";
		if (description.length > 0) {
			description = " — " + description;
		}
		
		var copy = document.importNode(template.content, true);
		copy.querySelector(".name").innerText = data.name || "";
		copy.querySelector(".description").innerText = description;
		copy.querySelector(".template-button").classList.add((data.choosesExisting || false) ? "existing" : "add");
		copy.querySelector("a.row").setAttribute("onclick", "window.assistant.choose('"+data.identifier+"'); return false;");
		document.querySelector("#template-rows").appendChild(copy);
	}
	
	exports.getSettings = function () {
		return window.utils.formToDictValue(document.querySelector("#template-settings"));
	}
	
	window.ui = exports;
})();
