var Exercises = {

	correctAnswer: function(encodedAnswer) {
	  answer = encodedAnswer.rot13().replace('v', 'u').words().map(function(x) { return x.split('|')[0]; }).join(' ');
	  return answer;
	},

	mark: function(encodedAnswer, guess) {
	  answer = encodedAnswer.rot13().replace('v', 'u').toLowerCase().words().map(function(x) { return x.split('|'); });
	  guess = guess.replace('v', 'u').toLowerCase().words();
	  
    if (answer.length != guess.length) { return false; }
    return guess.every(function(x) { 
      return answer.some(function(y) { return y.contains(x) });
    });
  }	
};

$(function() {

	// add span.answers to each question
	
	$('ol.exercise li').each(function() {
		$(this).append('<span class="answer"><input><img></span>');
	});
	
	// blank event
	
	$('span.answer').bind('blank', function() {
		$(this).children('img')
			.attr('src', '/images/blank.png')
			.attr('title', 'No answer has been given.')
		.end()
	})
	.trigger('blank')
	
	// correct event
	
	.bind('correct', function() {
		$(this).children('img')
			.attr('src', '/images/correct.png')
			.attr('title', 'This is the correct answer.')
		.end()
	})
	
	// incorrect event
	
	.bind('incorrect', function() {
		$(this).children('img')
			.attr('src', '/images/incorrect.png')
			.attr('title', 'This answer is incorrect.')
		.end()
	})
	
	// mark event
	
	.bind('mark', function() {
		var guess = $(this).children('input').val();
		if (!guess) {
			$(this).trigger('blank');
		}
		else if (Exercises.mark($(this).closest('li').data('answer'), guess)) {
			$(this).trigger('correct');
		}
		else {
			$(this).trigger('incorrect');
		}
	})
	
	// requestAnswer event
	
	.bind('requestAnswer', function() {
		$(this).children('img')
			.attr('src', '/images/alert.png')
			.attr('title', 'The answer was given.')
		.end()
		.children('input')
		  .val(Exercises.correctAnswer($(this).closest('li').data('answer')))
			.attr('disabled', 'disabled')
		.end()
	})
	
	// make double-clicking the image trigger the requestAnswer event
	
	.children('img')
		.bind('dblclick', function() {
			$(this).parent().trigger('requestAnswer')
		})
	.end()
	
	// make changing the input trigger the mark event
	
	.children('input')
		.bind('change', function() {
			$(this).parent().trigger('mark')
		})
	.end()
});	

