define([], function () {
	return function () {
		editor('ace/theme/solarized_light');
		symname();
	};

	var active_css_class = '';

	/**
	 * symbolic name generator
	 */
	function symname() {
		active_css_class = $("#component_symbolic").val();
		$("#component_name").on("keyup", function () {
			// replace invalid characters and trim and replace whitespace with underscores
			var str = $(this).val().trim().replace(/[\s]+/g, '-');
			str = str.replace(/[^\w\d-]/g, '').toLowerCase();

			// disallow numbers at the start
			if (str.charCodeAt(0) >= 48 && str.charCodeAt(0) <= 57) {
				$(this).val('');
				return;
			}

            str = 'tile-' + str;

			$("#component_symbolic").val(str);
			$("#css_class_symbolic_name").html(str);

			// change css class in editor to match symbolic name
			var css_editor = window.ace.edit('css_content_editable');
			var css = css_editor.getValue();
			var re =  new RegExp('(\\.)'+active_css_class+'(?!-?[_a-zA-Z]+[_a-zA-Z0-9-]*)', 'g');
			css_editor.setValue(css.replace(re, '$1'+str));

			active_css_class = str;
		});
	}

	/**
	 * load code editor (ace js)
	 */
	function editor(ace_theme) {
		var ace = window.ace;

		var html_editor = ace.edit('html_content_editable');
		html_editor.setTheme(ace_theme);
		html_editor.getSession().setMode("ace/mode/html");

		var css_editor = ace.edit('css_content_editable');
		css_editor.setTheme(ace_theme);
		css_editor.getSession().setMode("ace/mode/css");

		var js_editor = ace.edit('js_content_editable');
		js_editor.setTheme(ace_theme);
		js_editor.getSession().setMode("ace/mode/javascript");

		// load contents to editor
		html_editor.setValue($("input[name='html']").val());
		css_editor.setValue($("input[name='css']").val());
		js_editor.setValue($("input[name='js']").val());

		// submit form
		$("#js-page-submit").on('click', function () {
			$("input[name='html']").val(html_editor.getValue());
			$("input[name='css']").val(css_editor.getValue());
			$("input[name='js']").val(js_editor.getValue());
			return true;
		});
	}
});
