var Quiz = function() {

	function updatePage(data) {

		try {
			$('#last-saved').html(data.last_saved);
			$('#last-saved').effect("highlight", {}, 2000);
		} catch (e) { alert(e); }

		if (data.has_mc_rejoinder === true) {
			$("#mc-choice-question-pair_"+data.question_family_id+"_"+data.choice_family_id).after($(data.mc_rejoinder));
		}

	}

	function adjustTextArea(textarea) {
		var textarea = $(textarea);

		var hard_lines = 1;
		var last = 0;

		// Count hard lines
		while ( true ) {
			hard_lines = hard_lines + 1;
			last = textarea.val().indexOf("\n", last+1);
			if ( last == -1 ) break;
		}

		// Count soft lines
		var soft_lines = Math.round(textarea.val().length / (textarea.attr('cols')-1));

		var rows = Math.max(hard_lines,soft_lines) + 1;
		textarea.attr("rows",rows);
	}

	function enhanceTextAreas() {
		$('textarea.editable').each(function(index,textarea){
			adjustTextArea(textarea);
			textarea.onfocus = function(){
				adjust_textarea_int = setInterval(function(){adjustTextArea(textarea);}, 500);
			}
			textarea.onblur = function(){
				clearInterval(adjust_textarea_int);
			}
		});
	}

	function handleMultipleChoice() {
		$('#quiz-form').submit();
		$(this).closest('table.choices').find('input.mc-option').attr('disabled','disabled');
	}

	return {
		init : function() {

			var options = {
				url: $('#save-quiz-button').closest('form').attr("action"),
				type: 'POST',
				dataType: 'json',
				beforeSend: function() {
					$('#saving-indicator').show();
				},
				complete: function() {
					$('#saving-indicator').hide();
				},
				success: updatePage,
				error: function(xhr,status,error) {
					$('#last-saved').text("Could not save quiz answers. Please try again or contact support.");
				}
			}

			$('#quiz-form').submit(function() {
				$(this).ajaxSubmit(options);
				return false;
			})

			// Enhance textareas
			enhanceTextAreas();

			// Automatically save MC questions
			$('input.mc-option').click(handleMultipleChoice);
		}
	}
}();

$(function(){
	Quiz.init();
});
