<commit_before>// Common variables
var Q_INPUT					= '#q_input_mathquill';		// Question input-field
var S_INPUT					= '#s_input_mathquill_1';	// Default solution input-field
var A_INPUT					= '#a_input_mathquill_1';	// Default answer input-field
var C_INPUT					= '#c_input_mathquill';		// Calculation input-field
var W_INPUT					= '#w_input_mathquill_0';	// Default user-answer input-field
var M_INPUT					= '#m_input_mathquill_1';	// Default multiple-choice input-field
var F_INPUT					= '#f_fill_content_1';		//
var N_INPUT					= '#n_input_mathquill';		// Condition input-field
var T_INPUT					= '#t_input';				// Text-input in text-modal
var ACTIVE_INPUT			= '#q_input_mathquill';     // Current active input-field
var STEP					= 1;						// Number of steps in solution.
var ANSWER					= 1;						// Number of answers.
var SUB						= 1;						// Number of text-substitutions.
var TITLE_INSERTED			= false;
var MULTI_CHOICE			= 0;
var FILL_IN					= false;
var CON_IN					= false;
var SUBMITTING				= false;
var VARIABLES				= {};						// Object containing variables in use.
var MAX_VARIABLES			= 18;						// Max amount of unique variables.
var VAR_INIT				= false;
var dict_calc				= {};
var dict_calc_unchanged		= {};
var MODIFY					= false;
var SUBMIT_AS_NEW			= false;
var mod_blanks				= 0;
var mod_condition 			= 0;
var mod_multiple			= 0;
var VARIABLE_COUNT			= 0;
var edit_calc               = false;
var edit_calc_id            = 999;

$(document).ready(function() {
	// Draw math
	redraw_mathquill_elements();

	// KeyPad listeners
	$(document).on('click', '.btn_keypad', function(e){
		e.preventDefault();
		var keypad_cmd = "";
		ACTIVE_INPUT = get_input_field(this);
		if($(this).hasClass('keypad_int')){
			keypad_cmd = $(this).val();
			write_to_mathfield(ACTIVE_INPUT, keypad_cmd);
			simulate_keystroke(ACTIVE_INPUT, 'Left', 2);
		}
		else if($(this).hasClass('keypad_write')){
			keypad_cmd = $(this).val();
			write_to_mathfield(ACTIVE_INPUT, keypad_cmd);
		}
		else{
			if($(this).attr('value')){
				keypad_cmd = $(this).val();
			}
			else if($(this).hasClass('btn_var_abc') || $(this).hasClass('btn_calc')){
				keypad_cmd = $(this).text().replace(/x/g, "");
			}
			else{
				keypad_cmd = MathQuill.StaticMath($(this)[0]).latex();
			}
			cmd_to_mathfield(ACTIVE_INPUT, keypad_cmd);
		}
		refresh_char_colors(ACTIVE_INPUT);
	});

	// Custom Matrix popover
	$(document).on('click', '.btn_custom_matrix[rel=matrix-popover]', function(e){
		e.preventDefault();
		ACTIVE_INPUT = get_input_field(this);
	}).popover({
		html: true,
		selector: '[rel="matrix-popover"]',
		content: function(){
			return $('#popover_content_matrix')[0].outerHTML;
		},
		title: function(){
			return $('#popover_title_matrix').text();
		},
		container: 'body'
	});

	// Draw preview of custom matrix
	$(document).on('mouseenter', '#popover_content_matrix td', function(){
		preview_custom_matrix($(this));
		$('.popover-title').text($('#popover_title_matrix').text() + get_custom_matrix_size($(this)));
	});

	// Draw custom matrix
	$(document).on('click', '#popover_content_matrix td', function(){
		var matrix_size = get_custom_matrix_size($(this)).split('x');
		var latex = get_custom_matrix_latex(matrix_size[0], matrix_size[1]);
		write_to_mathfield(ACTIVE_INPUT, latex);
		simulate_keystroke(ACTIVE_INPUT, 'Left', parseInt(matrix_size[0]*matrix_size[1]));
		$(this).closest('.popover').popover('hide');
	});

	// Template title validation
	$('#template_title').change(function() {
		if(TITLE_INSERTED == false){
			$('#template_title').removeClass('select_error');
			TITLE_INSERTED = true;
		}
	});

	// Check if template is inserted from db to be modified.
	if($('#edit_template').text() == 'true'){
		MODIFY = true;
		TITLE_INSERTED = true;
		VAR_INIT = true;
		insert_editable_data();
	}

	// Set which input-field is active
	$(document).on('focus', '.input_mathquill', function(e){
		e.preventDefault();
		var input_id = $(this).attr('id');
		if(input_id != undefined) {
			var input_group = input_id[0];

			if (input_group == 'q') {
				ACTIVE_INPUT = '#' + input_id;
				$(Q_INPUT).removeClass('select_error');
			}
			else if (input_group == 's') {
				S_INPUT = '#' + input_id;
				ACTIVE_INPUT = '#' + input_id;
				$(S_INPUT).removeClass('select_error');
			}
			else if (input_group == 'a') {
				A_INPUT = '#' + input_id;
				ACTIVE_INPUT = '#' + input_id;
				$(A_INPUT).removeClass('select_error');
			}
			else if (input_group == 'm') {
				M_INPUT = '#' + input_id;
				ACTIVE_INPUT = '#' + input_id;
			}
			else if (input_group == 'f') {
				F_INPUT = '#' + input_id;
				ACTIVE_INPUT = '#' + input_id;
			}
		}
    });

 	// Set which input-field is active on user-side.
	$(document).on('focus', '.input_blanks', function(e){
		e.preventDefault();
		var input_id = $(this).attr('id');
		if(input_id != undefined) {
			var input_group = input_id[0];
			if (input_group == 'w') {
				W_INPUT = '#' + input_id;
				ACTIVE_INPUT = W_INPUT;
			}
		}
    });

	// TEXT-PANEL: Insert text
	$('#t_btn_ok').click(function(e){
		e.preventDefault();
		var t_input = $(T_INPUT).val();
		$(T_INPUT).val("");
		write_to_mathfield(ACTIVE_INPUT, '\\text{'+ t_input +' }');
		$('#text_modal').on('hidden.bs.modal', function () {
			$(ACTIVE_INPUT).find('textarea').focus();
		});
	});
	
	// TEXT-PANEL: Cancel text-input
	$('.btn_close_text').click(function(e){
		e.preventDefault();
		$(T_INPUT).val("");
		$('#text_modal').on('hidden.bs.modal', function () {
			$(ACTIVE_INPUT).find('textarea').focus();
		});
	});
	
	// TEXT-PANEL: Open text panel
	$('.btn_text').click(function(){
		ACTIVE_INPUT = get_input_field(this);
		$('#text_modal').on('shown.bs.modal', function () {
			$(T_INPUT).focus();
		});
	});

	// VARIABLES: Insert new variable
	$('.btn_var').click(function(e){
		e.preventDefault();
		if(Object.keys(VARIABLES).length <= MAX_VARIABLES) {
			var var_available = false;
			var q_var = "a";
			var q_var_id = 0;
			while (var_available == false) {
				if ($('#q_btn_abc_' + q_var_id).length || q_var == "r" || q_var == "x" || q_var == "y" || q_var == "z") {
					q_var = String.fromCharCode(q_var.charCodeAt(0) + 1);
					q_var_id++;
				}
				else {
					var_available = true;
				}
			}
			init_new_variable(q_var);
			redraw_mathquill_elements();
			$(Q_INPUT).find('textarea').focus();
		}
		else{
			alert('Ikke tillatt med flere variabler.');
		}
	});

    // VARIABLES: Insert custom variable.
	$(document).on('focusout', '.input_new_variable', function() {
		var variable = $(this).val();
        if (variable) {
            if (variable.match(/^[a-z]+$/g)) {
                var id = get_converted_variable(variable).replace(/R/g, "");
                if($('#q_btn_abc_' + id).length){
                    error_message('.input_new_variable', "Tegn allerede i bruk!");
                } else if(variable == "r" || variable == "x" || variable == "y" || variable == "z"){ // Ugyldige tegn!
                    error_message('.input_new_variable', "Ugyldig tegn!");
                } else {
                    init_new_variable(variable);
                }
                $(this).val("");
            } else {
                error_message('.input_new_variable', "Ugyldig tegn!");
                $(this).val("");
            }
        }
	}).on('keyup', '.input_new_variable', function(e){
		if(/(13)/.test(e.which)) { // Add tag if one of these keys are pressed.
            $(this).focusout();
		}
	});

	// VARIABLES: Remove variable a,b,c,..
	$(document).on('click', '.btn_var_del', function(e){
		var id = parseInt($(this).attr('id').match(/[\d]+$/));
		$('#q_btn_abc_' + id).remove();
		$('.btn_var_' + id).remove();
		$('#o_adv_' + id).remove();
		refresh_all_char_colors();
		refresh_variables();
		build_overview();
		e.stopPropagation();
	});

	// Erase last input
	$('.btn_delete').click(function(e){
		e.preventDefault();
		simulate_keystroke(get_input_field(this),'Backspace');
		$(ACTIVE_INPUT).find('textarea').focus();
	});
	
	// Clear input
	$(document).on('click', '.btn_clear', function(e){
		e.preventDefault();
		var btn_id = $(this).attr('id');
		btn_id = btn_id[0];
		if(btn_id == 'q'){
			MathQuill.MathField($(Q_INPUT)[0]).revert();
			MathQuill.MathField($(Q_INPUT)[0]).focus();
		}
		else if(btn_id == 'n'){
			refresh_conditions();
		}
		else if(btn_id == 's'){
			var sol_input = $(this).attr('id').replace(/s_btn_clear_/g, '');
			MathQuill.MathField($('#s_input_mathquill_' + sol_input)[0]).revert();
			MathQuill.MathField($('#s_input_mathquill_' + sol_input)[0]).focus();
		}
		else if(btn_id == 'a'){
			var ans_input = $(this).attr('id').replace(/a_btn_clear_/g, '');
			MathQuill.MathField($('#a_input_mathquill_' + ans_input)[0]).revert();
			MathQuill.MathField($('#a_input_mathquill_' + ans_input)[0]).focus();
		}
		else{
			MathQuill.MathField($(ACTIVE_INPUT)[0]).revert();
			MathQuill.MathField($(ACTIVE_INPUT)[0]).focus();
		}
	});
	
	// Keyboard-listener for input-fields
	$(document).on('keyup', '.input_mathquill', function(e){
		var id = $(this).attr('id');
		if(id != undefined) {
			var id_group = id[0];
            if (e.keyCode >= 65 && e.keyCode <= 90){
                refresh_char_colors('#' + id);
            }
			else if (e.keyCode == 13) {
				if (id_group == 't') {
					$('#t_btn_ok').click();
				}
				else if (id_group == 'c') {
					$('#c_btn_ok').click();
				}
				else if (id_group == 'n') {
					$('#n_btn_ok').click();
				}
				else if(((id_group == 'q') || (id_group == 's') || (id_group == 'a')) && (id[1] != "e")){
					$('#' + id_group + '_btn_proceed').click();
				}
			}
		}
	}).on('keyup', '.dcg-template-mathquill', function(){
		refresh_char_colors('.dcg-template-mathquill');
	});

	// Proceed to next panel
	$('.btn_proceed').click(function(e){
		e.preventDefault();
		var btn_id = $(this).attr('id');
		btn_id = btn_id[0];
		if(btn_id == 'q'){
			if(TITLE_INSERTED){
				if(MathQuill.MathField($(Q_INPUT)[0]).latex() != ''){
					$('.btn-group-q').prop('disabled', true);
					var s_panel = $('#s_panel');
					s_panel.fadeIn(function(){
						redraw_mathquill_elements();
					});
					scroll_to(s_panel);
					$(S_INPUT).find('textarea').focus();
				}
				else{
					$(Q_INPUT).addClass('select_error');
					error_message('q_input_field', 'Dette feltet kan ikke være tomt.');
				}
			}
			else{
				$('#template_title').addClass('select_error');
				error_message('template_title', 'Skriv inn tittel.');
			}
		}
		else if(btn_id == 's'){
			var solution_valid = true;
			for(var step = 1; step <= STEP; step++){
				if(MathQuill.MathField($('#s_input_mathquill_' + step)[0]).latex() == ''){
					solution_valid = false;
					$('#s_input_mathquill_' + step).addClass('select_error');
					error_message('step_' + step, 'Dette feltet kan ikke være tomt.');
				}
				if($('#s_text_' + step).val() == ""){
					solution_valid = false;
					error_message('s_text_' + step, 'Skriv forklaring.');
				}
			}
			if(solution_valid == true){
				$('.btn-group-s').prop('disabled', true);
				var a_panel = $('#a_panel');
				a_panel.fadeIn(function(){
					redraw_mathquill_elements();
				});
				scroll_to(a_panel);
				$(A_INPUT).find('textarea').focus()
			}
		}
		else if(btn_id == 'a'){
			var answer_valid = true;
			for(var ans = 1; ans <= ANSWER; ans++){
				if(MathQuill.MathField($('#a_input_mathquill_' + ans)[0]).latex() == ''){
					answer_valid = false;
					$('#a_input_mathquill_' + ans).addClass('select_error');
					error_message('answer_' + ans, 'Dette feltet kan ikke være tomt.');
				}
			}
			if(answer_valid == true){
				$('.btn-group-a').prop('disabled', true);
				var o_panel = $('#o_panel');
				o_panel.fadeIn(function(){
					redraw_mathquill_elements();
				});
				scroll_to(o_panel);
			}
		}
	});

	// SOLUTION-PANEL: Add new solution step
	$('#s_btn_next').click(function(e){
		e.preventDefault();
		$('#s_btn_del_' + STEP).hide();
		STEP++;
		$('#s_form').append(
			'<div id="step_'+STEP+'" class="step" style="display:none"><hr>' +
				'<h4>Steg '+STEP+'<a id="s_btn_del_'+STEP+'" class="glyphicon glyphicon-remove del_step" style="float:right"></a></h4>' +
				'<div class="input_field s_input_field">' +
					'<span id="s_input_mathquill_'+STEP+'" class="math-field form-control input_mathquill"></span>' +
					'<button id="s_btn_clear_'+STEP+'" class="btn btn-default btn_clear" style="margin-left:3px; border:none">' +
						'<span class="glyphicon glyphicon-trash" style="resize:vertical"></span>' +
					'</button>' +
				'</div>' +
			'</div>'
		);
		redraw_mathquill_elements();
		$('#step_' + STEP).fadeIn();
		S_INPUT = '#s_input_mathquill_' + STEP;
		scroll_to($('#step_' + STEP));
		$(S_INPUT).find('textarea').focus();
	});

	// ANSWER-PANEL: Add another answer
	$('#a_btn_next').click(function(e){
		e.preventDefault();
		$('#a_btn_del_' + ANSWER).hide();
		if(ANSWER == 1){
			$('#ans_title_1').show();
		}
		ANSWER++;
		$('#a_form').append(
			'<div id="answer_'+ANSWER+'" class="answer" style="display:none"><hr>' +
				'<h4>Svar '+ANSWER+'<a id="a_btn_del_'+ANSWER+'" class="glyphicon glyphicon-remove del_answer" style="float:right"></a></h4>' +
				'<div class="input_field a_input_field">' +
					'<span id="a_input_mathquill_'+ANSWER+'" class="math-field form-control input_mathquill"></span>' +
					'<button id="a_btn_clear_'+ANSWER+'" class="btn btn-default btn_clear" style="margin-left:3px; border:none">' +
						'<span class="glyphicon glyphicon-trash" style="resize:vertical"></span>' +
					'</button>' +
				'</div>' +
			'</div>'
		);
		redraw_mathquill_elements();
		$('#answer_' + ANSWER).fadeIn();
		A_INPUT = '#a_input_mathquill_' + ANSWER;
		scroll_to($('#answer_' + ANSWER));
		$(A_INPUT).find('textarea').focus();
	});

	// Add another text-substitution
	$('#e_btn_next').click(function(e){
		e.preventDefault();
		var e_form = $('#e_form');
		$('#e_btn_del_' +SUB).hide();
		SUB++;
		e_form.append('<div id="e_sub_'+SUB+'" style="display:none"><hr><div class="form-group"><label class="col-md-4 control-label">Bytt ut ord/setning:</label><div class="col-md-7"><input id="e_from_'+SUB+'" type="text" class="form-control" placeholder="Epler"></div><div class="col-md-1"><a id="e_btn_del_'+SUB+'" class="glyphicon glyphicon-remove del_sub" style="float:right"></a></div></div><div class="form-group"><label class="col-md-4 control-label">Med ord/setning:</label><div class="col-md-7"><textarea id="e_to_'+SUB+'" type="text" class="form-control" rows="2" placeholder="Bananer, P&#xE6;rer, Appelsiner, Druer"></textarea></div></div></div>');
		$('#e_sub_' + SUB).fadeIn();
	});

	// Delete last text-substitution
	$(document).on('click', '.del_sub', function(e){
		e.preventDefault();
		$('#e_sub_' + SUB).remove();
		SUB--;
		$('#e_btn_del_' +SUB).show();
	});

	// Delete solution step
	$(document).on('click', '.del_step', function(e){
		e.preventDefault();
		var btn_id = parseInt($(this).attr("id").match(/[\d]+$/));
		$('#step_' + btn_id).fadeOut(function(){
			$(this).remove();
		});
		STEP--;
		$('#s_btn_del_' + STEP).show();
		S_INPUT = '#s_input_mathquill_' + STEP;
		if(STEP == 1){
			scroll_to($('#s_panel'));
		}
		else{
			scroll_to($('#step_' + STEP));
		}
		$(S_INPUT).find('textarea').focus();
	});
	
	// Delete alternative answer
	$(document).on('click', '.del_answer', function(e){
		e.preventDefault();
		var btn_id = parseInt($(this).attr("id").match(/[\d]+$/));
		if(ANSWER == 2){
			$('#ans_title_1').hide();
		}
		$('#answer_' + btn_id).fadeOut(function(){
			$(this).remove();
		});
		ANSWER--;
		$('#a_btn_del_' + ANSWER).show();
		A_INPUT = '#a_input_mathquill_' + ANSWER;
		if(ANSWER == 1){
			scroll_to($('#a_panel'));
		}
		else{
			scroll_to($('#answer_' + ANSWER));
		}
		$(A_INPUT).find('textarea').focus();
	});

	// Close panel
	$('.btn_close').click(function(e){
		e.preventDefault();
		var btn_id = $(this).attr('id');
		btn_id = btn_id[0];
		close_panel(btn_id);
	});
	
	// Remove calculated reference buttons
	$(document).on('click', '.btn_calc_del', function(e){
		var id = parseInt($(this).attr('class').match(/[\d]+$/));
		$('.btn_calc_ref_' + id).popover('destroy').remove();
		delete dict_calc[id];
		delete dict_calc_unchanged[id];
		refresh_all_char_colors();
		build_overview();
		e.stopPropagation();
	});

    // Edit calculation
    $(document).on('click', '.btn_calc_edit', function(e){
        e.stopPropagation();
        var id = parseInt($(this).attr('class').match(/[\d]+$/));
        $('.calc_variable').val(String.fromCharCode(65 + id)); // Get the correct variable from the id (A=0, B=1, C=2, etc).
        $('#calc_modal').modal('show').one('shown.bs.modal', function(){
            edit_calc = true;
            edit_calc_id = id;
            var latex = dict_calc_unchanged[id];
            write_to_mathfield(C_INPUT, latex);
            redraw_mathquill_elements();
            refresh_char_colors(C_INPUT);
        });
    });

	// Show advanced domain settings
	$('#o_btn_adv_domain').click(function(e){
		e.preventDefault();
		$('#o_adv_domain').fadeToggle();
		$('#o_adv_caret').toggleClass('dropup');
	});

	// Toggle the advance domain settings for one variable between a selection in a range and a selection with a list of numbers.
	$(document).on('change', '.o_btn_adv_sequence', function(){
		var id = $(this).attr('id').replace(/o_adv_sequence_/g, "");
		if($(this).is(':checked')){
			$('#o_adv_'+id).children().nextAll().slice(0, 3).each(function(){
				$(this).fadeOut(function(){
					$('#o_adv_sequence_container_'+id).fadeIn();
				});
			});
		} else {
			$('#o_adv_sequence_container_'+id).fadeOut(function(){
				$('#o_adv_'+id).children().nextAll().slice(0, 3).each(function(){
					$(this).fadeIn();
				});
			});
		}
	});

	// Adding sequential domains.
	$(document).on('focusout', '.seq_input', function() {
		var seq = get_latex_from_mathfield(this);
		if (seq) {
			$(this).before('<span class="o_seq"><span class="math-field static-math-sm">' + seq + '</span><a class="btn btn_tag_del">x</a></span>');
			MathQuill.MathField($(this)[0]).select().write(""); // reset the mathquill-input
			redraw_mathquill_elements();
		}
	}).on('keyup', '.seq_input', function(e){
		if(/(188|13)/.test(e.which)) { // Add tag if one of these keys are pressed.
            $(this).focusout();
		}
	});

	// Domain input-insertion to advanced settings
	$('#opt_domain_from').on('input', function(){
		$('.opt_domain_from').val($('#opt_domain_from').val());
	});
	$('#opt_domain_to').on('input', function(){
		$('.opt_domain_to').val($('#opt_domain_to').val());
	});
	$('#opt_domain_dec').on('input', function(){
		$('.opt_domain_dec').val($('#opt_domain_dec').val());
	});

	// Open condition modal
	$('#opt_conditions').click(function(){<commit_msg>Update variable overview on input change<commit_after>// Common variables
var Q_INPUT					= '#q_input_mathquill';		// Question input-field
var S_INPUT					= '#s_input_mathquill_1';	// Default solution input-field
var A_INPUT					= '#a_input_mathquill_1';	// Default answer input-field
var C_INPUT					= '#c_input_mathquill';		// Calculation input-field
var W_INPUT					= '#w_input_mathquill_0';	// Default user-answer input-field
var M_INPUT					= '#m_input_mathquill_1';	// Default multiple-choice input-field
var F_INPUT					= '#f_fill_content_1';		//
var N_INPUT					= '#n_input_mathquill';		// Condition input-field
var T_INPUT					= '#t_input';				// Text-input in text-modal
var ACTIVE_INPUT			= '#q_input_mathquill';     // Current active input-field
var STEP					= 1;						// Number of steps in solution.
var ANSWER					= 1;						// Number of answers.
var SUB						= 1;						// Number of text-substitutions.
var TITLE_INSERTED			= false;
var MULTI_CHOICE			= 0;
var FILL_IN					= false;
var CON_IN					= false;
var SUBMITTING				= false;
var VARIABLES				= {};						// Object containing variables in use.
var MAX_VARIABLES			= 18;						// Max amount of unique variables.
var VAR_INIT				= false;
var dict_calc				= {};
var dict_calc_unchanged		= {};
var MODIFY					= false;
var SUBMIT_AS_NEW			= false;
var mod_blanks				= 0;
var mod_condition 			= 0;
var mod_multiple			= 0;
var VARIABLE_COUNT			= 0;
var edit_calc               = false;
var edit_calc_id            = 999;

$(document).ready(function() {
	// Draw math
	redraw_mathquill_elements();

	// KeyPad listeners
	$(document).on('click', '.btn_keypad', function(e){
		e.preventDefault();
		var keypad_cmd = "";
		ACTIVE_INPUT = get_input_field(this);
		if($(this).hasClass('keypad_int')){
			keypad_cmd = $(this).val();
			write_to_mathfield(ACTIVE_INPUT, keypad_cmd);
			simulate_keystroke(ACTIVE_INPUT, 'Left', 2);
		}
		else if($(this).hasClass('keypad_write')){
			keypad_cmd = $(this).val();
			write_to_mathfield(ACTIVE_INPUT, keypad_cmd);
		}
		else{
			if($(this).attr('value')){
				keypad_cmd = $(this).val();
			}
			else if($(this).hasClass('btn_var_abc') || $(this).hasClass('btn_calc')){
				keypad_cmd = $(this).text().replace(/x/g, "");
			}
			else{
				keypad_cmd = MathQuill.StaticMath($(this)[0]).latex();
			}
			cmd_to_mathfield(ACTIVE_INPUT, keypad_cmd);
		}
		refresh_char_colors(ACTIVE_INPUT);
	});

	// Custom Matrix popover
	$(document).on('click', '.btn_custom_matrix[rel=matrix-popover]', function(e){
		e.preventDefault();
		ACTIVE_INPUT = get_input_field(this);
	}).popover({
		html: true,
		selector: '[rel="matrix-popover"]',
		content: function(){
			return $('#popover_content_matrix')[0].outerHTML;
		},
		title: function(){
			return $('#popover_title_matrix').text();
		},
		container: 'body'
	});

	// Draw preview of custom matrix
	$(document).on('mouseenter', '#popover_content_matrix td', function(){
		preview_custom_matrix($(this));
		$('.popover-title').text($('#popover_title_matrix').text() + get_custom_matrix_size($(this)));
	});

	// Draw custom matrix
	$(document).on('click', '#popover_content_matrix td', function(){
		var matrix_size = get_custom_matrix_size($(this)).split('x');
		var latex = get_custom_matrix_latex(matrix_size[0], matrix_size[1]);
		write_to_mathfield(ACTIVE_INPUT, latex);
		simulate_keystroke(ACTIVE_INPUT, 'Left', parseInt(matrix_size[0]*matrix_size[1]));
		$(this).closest('.popover').popover('hide');
	});

	// Template title validation
	$('#template_title').change(function() {
		if(TITLE_INSERTED == false){
			$('#template_title').removeClass('select_error');
			TITLE_INSERTED = true;
		}
	});

	// Check if template is inserted from db to be modified.
	if($('#edit_template').text() == 'true'){
		MODIFY = true;
		TITLE_INSERTED = true;
		VAR_INIT = true;
		insert_editable_data();
	}

	// Set which input-field is active
	$(document).on('focus', '.input_mathquill', function(e){
		e.preventDefault();
		var input_id = $(this).attr('id');
		if(input_id != undefined) {
			var input_group = input_id[0];

			if (input_group == 'q') {
				ACTIVE_INPUT = '#' + input_id;
				$(Q_INPUT).removeClass('select_error');
			}
			else if (input_group == 's') {
				S_INPUT = '#' + input_id;
				ACTIVE_INPUT = '#' + input_id;
				$(S_INPUT).removeClass('select_error');
			}
			else if (input_group == 'a') {
				A_INPUT = '#' + input_id;
				ACTIVE_INPUT = '#' + input_id;
				$(A_INPUT).removeClass('select_error');
			}
			else if (input_group == 'm') {
				M_INPUT = '#' + input_id;
				ACTIVE_INPUT = '#' + input_id;
			}
			else if (input_group == 'f') {
				F_INPUT = '#' + input_id;
				ACTIVE_INPUT = '#' + input_id;
			}
		}
    });

 	// Set which input-field is active on user-side.
	$(document).on('focus', '.input_blanks', function(e){
		e.preventDefault();
		var input_id = $(this).attr('id');
		if(input_id != undefined) {
			var input_group = input_id[0];
			if (input_group == 'w') {
				W_INPUT = '#' + input_id;
				ACTIVE_INPUT = W_INPUT;
			}
		}
    });

	// TEXT-PANEL: Insert text
	$('#t_btn_ok').click(function(e){
		e.preventDefault();
		var t_input = $(T_INPUT).val();
		$(T_INPUT).val("");
		write_to_mathfield(ACTIVE_INPUT, '\\text{'+ t_input +' }');
		$('#text_modal').on('hidden.bs.modal', function () {
			$(ACTIVE_INPUT).find('textarea').focus();
		});
	});
	
	// TEXT-PANEL: Cancel text-input
	$('.btn_close_text').click(function(e){
		e.preventDefault();
		$(T_INPUT).val("");
		$('#text_modal').on('hidden.bs.modal', function () {
			$(ACTIVE_INPUT).find('textarea').focus();
		});
	});
	
	// TEXT-PANEL: Open text panel
	$('.btn_text').click(function(){
		ACTIVE_INPUT = get_input_field(this);
		$('#text_modal').on('shown.bs.modal', function () {
			$(T_INPUT).focus();
		});
	});

	// VARIABLES: Insert new variable
	$('.btn_var').click(function(e){
		e.preventDefault();
		if(Object.keys(VARIABLES).length <= MAX_VARIABLES) {
			var var_available = false;
			var q_var = "a";
			var q_var_id = 0;
			while (var_available == false) {
				if ($('#q_btn_abc_' + q_var_id).length || q_var == "r" || q_var == "x" || q_var == "y" || q_var == "z") {
					q_var = String.fromCharCode(q_var.charCodeAt(0) + 1);
					q_var_id++;
				}
				else {
					var_available = true;
				}
			}
			init_new_variable(q_var);
			redraw_mathquill_elements();
			$(Q_INPUT).find('textarea').focus();
		}
		else{
			alert('Ikke tillatt med flere variabler.');
		}
	});

    // VARIABLES: Insert custom variable.
	$(document).on('focusout', '.input_new_variable', function() {
		var variable = $(this).val();
        if (variable) {
            if (variable.match(/^[a-z]+$/g)) {
                var id = get_converted_variable(variable).replace(/R/g, "");
                if($('#q_btn_abc_' + id).length){
                    error_message('.input_new_variable', "Tegn allerede i bruk!");
                } else if(variable == "r" || variable == "x" || variable == "y" || variable == "z"){ // Ugyldige tegn!
                    error_message('.input_new_variable', "Ugyldig tegn!");
                } else {
                    init_new_variable(variable);
                }
                $(this).val("");
            } else {
                error_message('.input_new_variable', "Ugyldig tegn!");
                $(this).val("");
            }
        }
	}).on('keyup', '.input_new_variable', function(e){
		if(/(13)/.test(e.which)) { // Add tag if one of these keys are pressed.
            $(this).focusout();
		}
	});

	// VARIABLES: Remove variable a,b,c,..
	$(document).on('click', '.btn_var_del', function(e){
		var id = parseInt($(this).attr('id').match(/[\d]+$/));
		$('#q_btn_abc_' + id).remove();
		$('.btn_var_' + id).remove();
		$('#o_adv_' + id).remove();
		refresh_all_char_colors();
		refresh_variables();
		build_overview();
		e.stopPropagation();
	});

	// Erase last input
	$('.btn_delete').click(function(e){
		e.preventDefault();
		simulate_keystroke(get_input_field(this),'Backspace');
		$(ACTIVE_INPUT).find('textarea').focus();
	});
	
	// Clear input
	$(document).on('click', '.btn_clear', function(e){
		e.preventDefault();
		var btn_id = $(this).attr('id');
		btn_id = btn_id[0];
		if(btn_id == 'q'){
			MathQuill.MathField($(Q_INPUT)[0]).revert();
			MathQuill.MathField($(Q_INPUT)[0]).focus();
		}
		else if(btn_id == 'n'){
			refresh_conditions();
		}
		else if(btn_id == 's'){
			var sol_input = $(this).attr('id').replace(/s_btn_clear_/g, '');
			MathQuill.MathField($('#s_input_mathquill_' + sol_input)[0]).revert();
			MathQuill.MathField($('#s_input_mathquill_' + sol_input)[0]).focus();
		}
		else if(btn_id == 'a'){
			var ans_input = $(this).attr('id').replace(/a_btn_clear_/g, '');
			MathQuill.MathField($('#a_input_mathquill_' + ans_input)[0]).revert();
			MathQuill.MathField($('#a_input_mathquill_' + ans_input)[0]).focus();
		}
		else{
			MathQuill.MathField($(ACTIVE_INPUT)[0]).revert();
			MathQuill.MathField($(ACTIVE_INPUT)[0]).focus();
		}
	});
	
	// Keyboard-listener for input-fields
	$(document).on('keyup', '.input_mathquill', function(e){
		var id = $(this).attr('id');
		if(id != undefined) {
			var id_group = id[0];
            if (e.keyCode >= 65 && e.keyCode <= 90){
                refresh_char_colors('#' + id);
            }
			else if (e.keyCode == 13) {
				if (id_group == 't') {
					$('#t_btn_ok').click();
				}
				else if (id_group == 'c') {
					$('#c_btn_ok').click();
				}
				else if (id_group == 'n') {
					$('#n_btn_ok').click();
				}
				else if(((id_group == 'q') || (id_group == 's') || (id_group == 'a')) && (id[1] != "e")){
					$('#' + id_group + '_btn_proceed').click();
				}
			}
		}
	}).on('keyup', '.dcg-template-mathquill', function(){
		refresh_char_colors('.dcg-template-mathquill');
	});

	// Proceed to next panel
	$('.btn_proceed').click(function(e){
		e.preventDefault();
		var btn_id = $(this).attr('id');
		btn_id = btn_id[0];
		if(btn_id == 'q'){
			if(TITLE_INSERTED){
				if(MathQuill.MathField($(Q_INPUT)[0]).latex() != ''){
					$('.btn-group-q').prop('disabled', true);
					var s_panel = $('#s_panel');
					s_panel.fadeIn(function(){
						redraw_mathquill_elements();
					});
					scroll_to(s_panel);
					$(S_INPUT).find('textarea').focus();
				}
				else{
					$(Q_INPUT).addClass('select_error');
					error_message('q_input_field', 'Dette feltet kan ikke være tomt.');
				}
			}
			else{
				$('#template_title').addClass('select_error');
				error_message('template_title', 'Skriv inn tittel.');
			}
		}
		else if(btn_id == 's'){
			var solution_valid = true;
			for(var step = 1; step <= STEP; step++){
				if(MathQuill.MathField($('#s_input_mathquill_' + step)[0]).latex() == ''){
					solution_valid = false;
					$('#s_input_mathquill_' + step).addClass('select_error');
					error_message('step_' + step, 'Dette feltet kan ikke være tomt.');
				}
				if($('#s_text_' + step).val() == ""){
					solution_valid = false;
					error_message('s_text_' + step, 'Skriv forklaring.');
				}
			}
			if(solution_valid == true){
				$('.btn-group-s').prop('disabled', true);
				var a_panel = $('#a_panel');
				a_panel.fadeIn(function(){
					redraw_mathquill_elements();
				});
				scroll_to(a_panel);
				$(A_INPUT).find('textarea').focus()
			}
		}
		else if(btn_id == 'a'){
			var answer_valid = true;
			for(var ans = 1; ans <= ANSWER; ans++){
				if(MathQuill.MathField($('#a_input_mathquill_' + ans)[0]).latex() == ''){
					answer_valid = false;
					$('#a_input_mathquill_' + ans).addClass('select_error');
					error_message('answer_' + ans, 'Dette feltet kan ikke være tomt.');
				}
			}
			if(answer_valid == true){
				$('.btn-group-a').prop('disabled', true);
				var o_panel = $('#o_panel');
				o_panel.fadeIn(function(){
					redraw_mathquill_elements();
				});
				scroll_to(o_panel);
			}
		}
	});

	// SOLUTION-PANEL: Add new solution step
	$('#s_btn_next').click(function(e){
		e.preventDefault();
		$('#s_btn_del_' + STEP).hide();
		STEP++;
		$('#s_form').append(
			'<div id="step_'+STEP+'" class="step" style="display:none"><hr>' +
				'<h4>Steg '+STEP+'<a id="s_btn_del_'+STEP+'" class="glyphicon glyphicon-remove del_step" style="float:right"></a></h4>' +
				'<div class="input_field s_input_field">' +
					'<span id="s_input_mathquill_'+STEP+'" class="math-field form-control input_mathquill"></span>' +
					'<button id="s_btn_clear_'+STEP+'" class="btn btn-default btn_clear" style="margin-left:3px; border:none">' +
						'<span class="glyphicon glyphicon-trash" style="resize:vertical"></span>' +
					'</button>' +
				'</div>' +
			'</div>'
		);
		redraw_mathquill_elements();
		$('#step_' + STEP).fadeIn();
		S_INPUT = '#s_input_mathquill_' + STEP;
		scroll_to($('#step_' + STEP));
		$(S_INPUT).find('textarea').focus();
	});

	// ANSWER-PANEL: Add another answer
	$('#a_btn_next').click(function(e){
		e.preventDefault();
		$('#a_btn_del_' + ANSWER).hide();
		if(ANSWER == 1){
			$('#ans_title_1').show();
		}
		ANSWER++;
		$('#a_form').append(
			'<div id="answer_'+ANSWER+'" class="answer" style="display:none"><hr>' +
				'<h4>Svar '+ANSWER+'<a id="a_btn_del_'+ANSWER+'" class="glyphicon glyphicon-remove del_answer" style="float:right"></a></h4>' +
				'<div class="input_field a_input_field">' +
					'<span id="a_input_mathquill_'+ANSWER+'" class="math-field form-control input_mathquill"></span>' +
					'<button id="a_btn_clear_'+ANSWER+'" class="btn btn-default btn_clear" style="margin-left:3px; border:none">' +
						'<span class="glyphicon glyphicon-trash" style="resize:vertical"></span>' +
					'</button>' +
				'</div>' +
			'</div>'
		);
		redraw_mathquill_elements();
		$('#answer_' + ANSWER).fadeIn();
		A_INPUT = '#a_input_mathquill_' + ANSWER;
		scroll_to($('#answer_' + ANSWER));
		$(A_INPUT).find('textarea').focus();
	});

	// Add another text-substitution
	$('#e_btn_next').click(function(e){
		e.preventDefault();
		var e_form = $('#e_form');
		$('#e_btn_del_' +SUB).hide();
		SUB++;
		e_form.append('<div id="e_sub_'+SUB+'" style="display:none"><hr><div class="form-group"><label class="col-md-4 control-label">Bytt ut ord/setning:</label><div class="col-md-7"><input id="e_from_'+SUB+'" type="text" class="form-control" placeholder="Epler"></div><div class="col-md-1"><a id="e_btn_del_'+SUB+'" class="glyphicon glyphicon-remove del_sub" style="float:right"></a></div></div><div class="form-group"><label class="col-md-4 control-label">Med ord/setning:</label><div class="col-md-7"><textarea id="e_to_'+SUB+'" type="text" class="form-control" rows="2" placeholder="Bananer, P&#xE6;rer, Appelsiner, Druer"></textarea></div></div></div>');
		$('#e_sub_' + SUB).fadeIn();
	});

	// Delete last text-substitution
	$(document).on('click', '.del_sub', function(e){
		e.preventDefault();
		$('#e_sub_' + SUB).remove();
		SUB--;
		$('#e_btn_del_' +SUB).show();
	});

	// Delete solution step
	$(document).on('click', '.del_step', function(e){
		e.preventDefault();
		var btn_id = parseInt($(this).attr("id").match(/[\d]+$/));
		$('#step_' + btn_id).fadeOut(function(){
			$(this).remove();
		});
		STEP--;
		$('#s_btn_del_' + STEP).show();
		S_INPUT = '#s_input_mathquill_' + STEP;
		if(STEP == 1){
			scroll_to($('#s_panel'));
		}
		else{
			scroll_to($('#step_' + STEP));
		}
		$(S_INPUT).find('textarea').focus();
	});
	
	// Delete alternative answer
	$(document).on('click', '.del_answer', function(e){
		e.preventDefault();
		var btn_id = parseInt($(this).attr("id").match(/[\d]+$/));
		if(ANSWER == 2){
			$('#ans_title_1').hide();
		}
		$('#answer_' + btn_id).fadeOut(function(){
			$(this).remove();
		});
		ANSWER--;
		$('#a_btn_del_' + ANSWER).show();
		A_INPUT = '#a_input_mathquill_' + ANSWER;
		if(ANSWER == 1){
			scroll_to($('#a_panel'));
		}
		else{
			scroll_to($('#answer_' + ANSWER));
		}
		$(A_INPUT).find('textarea').focus();
	});

	// Close panel
	$('.btn_close').click(function(e){
		e.preventDefault();
		var btn_id = $(this).attr('id');
		btn_id = btn_id[0];
		close_panel(btn_id);
	});
	
	// Remove calculated reference buttons
	$(document).on('click', '.btn_calc_del', function(e){
		var id = parseInt($(this).attr('class').match(/[\d]+$/));
		$('.btn_calc_ref_' + id).popover('destroy').remove();
		delete dict_calc[id];
		delete dict_calc_unchanged[id];
		refresh_all_char_colors();
		build_overview();
		e.stopPropagation();
	});

    // Edit calculation
    $(document).on('click', '.btn_calc_edit', function(e){
        e.stopPropagation();
        var id = parseInt($(this).attr('class').match(/[\d]+$/));
        $('.calc_variable').val(String.fromCharCode(65 + id)); // Get the correct variable from the id (A=0, B=1, C=2, etc).
        $('#calc_modal').modal('show').one('shown.bs.modal', function(){
            edit_calc = true;
            edit_calc_id = id;
            var latex = dict_calc_unchanged[id];
            write_to_mathfield(C_INPUT, latex);
            redraw_mathquill_elements();
            refresh_char_colors(C_INPUT);
        });
    });

	// Show advanced domain settings
	$('#o_btn_adv_domain').click(function(e){
		e.preventDefault();
		$('#o_adv_domain').fadeToggle();
		$('#o_adv_caret').toggleClass('dropup');
	});

	// Toggle the advance domain settings for one variable between a selection in a range and a selection with a list of numbers.
	$(document).on('change', '.o_btn_adv_sequence', function(){
		var id = $(this).attr('id').replace(/o_adv_sequence_/g, "");
		if($(this).is(':checked')){
			$('#o_adv_'+id).children().nextAll().slice(0, 3).each(function(){
				$(this).fadeOut(function(){
					$('#o_adv_sequence_container_'+id).fadeIn();
				});
			});
		} else {
			$('#o_adv_sequence_container_'+id).fadeOut(function(){
				$('#o_adv_'+id).children().nextAll().slice(0, 3).each(function(){
					$(this).fadeIn();
				});
			});
		}
	});

	// Adding sequential domains.
	$(document).on('focusout', '.seq_input', function() {
		var seq = get_latex_from_mathfield(this);
		if (seq) {
			$(this).before('<span class="o_seq"><span class="math-field static-math-sm">' + seq + '</span><a class="btn btn_tag_del">x</a></span>');
			MathQuill.MathField($(this)[0]).select().write(""); // reset the mathquill-input
			redraw_mathquill_elements();
		}
	}).on('keyup', '.seq_input', function(e){
		if(/(188|13)/.test(e.which)) { // Add tag if one of these keys are pressed.
            $(this).focusout();
		}
	});

	// Domain input-insertion to advanced settings
	$('#opt_domain_from').on('input', function(){
		$('.opt_domain_from').val($('#opt_domain_from').val());
        build_overview();
	});
	$('#opt_domain_to').on('input', function(){
		$('.opt_domain_to').val($('#opt_domain_to').val());
        build_overview();
	});
	$('#opt_domain_dec').on('input', function(){
		//$('.opt_domain_dec').val($('#opt_domain_dec').val());
        build_overview();
	});
    $('.opt_domain_from').on('input', function(){
		//$('.opt_domain_from').val($('#opt_domain_from').val());
        build_overview();
	});
	$('.opt_domain_to').on('input', function(){
		//$('.opt_domain_to').val($('#opt_domain_to').val());
        build_overview();
	});
	$('.opt_domain_dec').on('input', function(){
		//$('.opt_domain_dec').val($('#opt_domain_dec').val());
        build_overview();
	});

	// Open condition modal
	$('#opt_conditions').click(function(){
{'fraction_non_alphanumeric': 0.21430641549203003, 'fraction_numerical': 0.004742458174153603, 'mean_word_length': 3.754008016032064, 'pattern_counts': {'":': 0, '<': 127, '<?xml version=': 0, '>': 121, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3576015', 'n_tokens_mistral': 15615, 'n_tokens_neox': 13913, 'n_words': 2255}