/*
 * Veggie of the Month - Common Javascript
 *
 */

// init $VOM namespace 
var $VOM = window.$VOM || {};

/*
 * Veggie of the Month - Quiz
 *
 * This code lets you put up a quiz. The quiz code should be structured as follows:
 * 
 * <div class="fix question">
 * <dl>
 *	<dt id="q1">1. Where is asparagus originally from?</dt>
 *	<dd><input type="radio" name="q-q1" /> <b>A)</b>  China</dd>
 *	<dd class="correctAnswer"><input type="radio" name="q-q1" /> <b>B)</b> Eastern Europe</dd>
 * 	<dd><input type="radio" name="q-q1" /> <b>C)</b> Peru</dd>
 *	<dd><input type="radio" name="q-q1" /> <b>D)</b> Asparagus Island, UK</dd>
 * </dl>	
 * <div class="answer" id="a-q1">
 * 	<h3>The Answer is <span>B</span></h3>
 * 	<p>It still grows in the wild all over Western Russia.</p>
 * </div>
 * </div>
 *
 * The code will look for all <dt> elements inside <dl class="quiz">. It will grab the id of each
 * of those, and look for radio buttons or checkboxes with a name of 'q-ID' (e.g. 'q-q1'). It will then score
 * the quiz based on what the user has selected and which radio button has a class of 'correct'. The answer is 
 * displayed on a div with id='a-ID' (e.g. 'a-q1').
 * 
 */

// init quiz namespace
$VOM.quiz = {};

/*
 * scoreQuiz(): runs the scoring routine on a quiz
 */
$VOM.quiz.scoreQuiz = function () {

	var correctAnswerCount = 0;
	var quizQuestions = $('#quiz dt');

	// clear any existing answers
	$('#quiz dd')
	  .removeClass('correctAnswer')
  	  .removeClass('incorrectAnswer');

	// set the 'correctAnswer' or 'incorrectAnswer' on the <dd> corresponding to the answer
	for (i = 0; i < quizQuestions.size(); i++) {
		var checkedAnswer = $("input[name='q-" + quizQuestions[i].id + "']:checked");
		if (checkedAnswer.hasClass('correct')) {
			$(checkedAnswer).parent('dd')
				.removeClass('incorrectAnswer')
				.addClass('correctAnswer');
			correctAnswerCount++;
		} else {
			$(checkedAnswer).parent('dd')
				.removeClass('correctAnswer')
				.addClass('incorrectAnswer');
		}
		
		// display the answer itself. Only do this if they checked 
		// something
		// if (checkedAnswer.length > 0)
			$('#a-' + quizQuestions[i].id).fadeIn('fast');
	}
	
	$('#answerCount').html(correctAnswerCount);
	$('.score').fadeIn('fast');
}

/*
 * resetQuiz(): hide the answers and reset the score
 */
$VOM.quiz.resetQuiz = function () {

	$('#quiz dd')
	  .removeClass('correctAnswer')
  	  .removeClass('incorrectAnswer');
  	$('#quiz input').removeAttr('checked');
	$('.answer').css('display','none');
	$('.score').css('display','none');

	// we set the correct answers back to zero, but leave the box
	// because it looks better that way
	$('#answerCount').html('0');
}

/*
 * initQuiz(): initialize the quiz page
 */
$VOM.quiz.initQuiz = function() {
	
	// attach listeners to the scoring and reset buttons
	$("#scoreQuiz").click($VOM.quiz.scoreQuiz);
	$("#resetQuiz").click($VOM.quiz.resetQuiz);	

}

$(window).ready(function() {
	$VOM.quiz.initQuiz();
})