jQuery(document).ready(function() {
	
	/* Save the content of the quiz box, so it can be restored after an ajax call */
	quiz_content = jQuery('.quiz-box-content').html();
	
	/* Showing and hiding the actual quiz popout thing */
	jQuery('.quiz-button').click(function() {
		show_quiz();
	});
	
	jQuery('.quiz-box-wrapper').click(function() {
		hide_quiz();
	});
	
	jQuery('#quiz-box-close').click(function() {
		hide_quiz();
	});
	
	function show_quiz() {
		jQuery('.quiz-box').show();
	}
	
	function hide_quiz() {
		jQuery('.quiz-box').hide();
		/* restore the riddle contents */
		jQuery('.quiz-box-content').html(quiz_content);
		jQuery('#quiz-box-close').click(function() {
			hide_quiz();
		});
	}
	
	/**
	 * The main content of the riddle popup box is replaced with the answer
	 * from the ajax below, and the hide_quiz() function above always reverts
	 * it back to the original content that was there on page load.  Terrible,
	 * but it works.  My apologies to whoever reads this.  -mp
	 */
	function change_quiz_content(content) {
		jQuery('.quiz-box-content').html(content  + '<img id="quiz-box-close" src="/wp-content/themes/moth/images/quiz-box-close.png">' );
		jQuery('#quiz-box-close').click(function() {
			hide_quiz();
		});
		show_quiz();
	}
	

	/* Quiz form */
	jQuery('#quiz-form-answer').focus(function() {
		if (jQuery(this).val() == "Type your answer here")
			jQuery(this).val('');
	});
	
	jQuery('#quiz-form-answer').blur(function() {
		if (jQuery(this).val() == "")
			jQuery(this).val('Type your answer here');
	});
	
	jQuery('#quiz-form-email').focus(function() {
		if (jQuery(this).val() == "Enter email here")
			jQuery(this).val('');
	});
	
	jQuery('#quiz-form-email').blur(function() {
		if (jQuery(this).val() == "")
			jQuery(this).val('Enter email here');
	});
	
	/* The ajax call */
	jQuery('#quiz-form-form').submit(function() {
		
		jQuery.ajax({
			url: '/wp-content/themes/moth/quiz_ajax.php',
			data: 'answer=' + jQuery('#quiz-form-answer').val() + '&email=' + jQuery('#quiz-form-email').val(),
			success: function(data) {
				change_quiz_content(data);
			},
			error: function() {
				alert('There was an error.  Sorry!');
			}
		});
		
		return false;
	});
	
	
	
	
});


