var f2fQuizQuestions = [

	{
		question : "Why do we grow our lettuce on the coast?",
		answers : [
			"So we can go swimming every day",
			"Because there is the most warmth and light",
			"So we can water the lettuce with sea water"
		],
		correctAnswer : 1,
		goTo : '/seeds/'
	},
	{
		question : "How long does it take for a lettuce to grow big enough to be moved outdoors?",
		answers : [
			"6 days",
			"34 days",
			"2 weeks"
		],
		correctAnswer : 1,
		goTo : '/planting/'
	},
	{
		question : "What is fertiliser for?",
		answers : [
			"To keep the plants warm",
			"To keep insects away",
			"To help the plants grow up to be healthy"
		],
		correctAnswer : 2,
		goTo : '/irrigation/'
	},
	{
		question : "What does the farmer do in the fields?",
		answers : [
			"Plants the lettuce",
			"Checks the lettuce is getting enough water",
			"Scares the birds away"
		],
		correctAnswer : 1,
		goTo : '/harvest/'
	},
	{
		question : "What does GPS stand for?",
		answers : [
			"Gardener's Pickled Sandwich",
			"General Purpose Saw",
			"Global Positioning System"
		],
		correctAnswer : 2,
		goTo : '/cooling/'
	},
	{
		question : "Why does the lettuce get cooled?",
		answers : [
			"To stop slugs from eating it",
			"To keep it fresh and looking good.",
			"So it grows slower"
		],
		correctAnswer : 1,
		goTo : '/delivery/'
	},
	{
		question : "Where are the Natures Way Foods factories?",
		answers : [
			"Selsey and Runcton",
			"Behind the supermarket",
			"London"
		],
		correctAnswer : 0,
		goTo : '/chopwashbag/'
	},
	{
		question : "How do we know how much salad our supermarket customers need?",
		answers : [
			"We guess",
			"We always give them the same amount",
			"They ring us every day with their orders"
		],
		correctAnswer : 2,
		goTo : '/supermarket/'
	},
	{
		question : "How do we transport our salad to supermarkets, restaurants and shops?",
		answers : [
			"On a motorbike",
			"On horseback",
			"In a lorry"
		],
		correctAnswer : 2,
		goTo : ''
	}
];

var f2fQuiz = {
	
	quizIsVisible : false,
	
	currentQuestion : -1,
	
	correctQuestions : 0,
	
	errors : 0,
	
	wrongAnswer : $('<img id="wrong_answer" src="/img/quiz_wrong_answer.png" width="238" height="226">'),
	
	chooseAnswer : $('<img id="choose_question" src="/img/quiz_choose_answer.png" width="246" height="163">'),
	
	quizBox : $('<div id="quizbox_wrapper"><div id="quizbox"><div id="quizdrag"><a href="#" class="closequiz ignore">close quiz panel</a></div><div id="quizbox_question"></div></div></div>'),
	
	startText : '<h2>Welcome to the quiz!</h2><p>Complete this short quiz about the Field to Fork Tour and we\'ll send you some seeds to plant at home, watch them grow and then eat your home-grown produce!<br>(For UK participants only)</p><p><a href="#/location/" class="quiznext">Go go go &raquo;</a></p>',
	
	initQuiz : function()
	{
		$('body').append(this.quizBox);
		this.questionElm = this.quizBox.find('#quizbox_question');
		
		this.questionElm.html(this.startText);
		
		this.quizBox.append(this.wrongAnswer);
		this.quizBox.append(this.chooseAnswer);
		
		this.hideQuiz();
		
		var _this = this;
		
		$('li.quiz a, #quizboy').live('click', function(){
			
			if ( _this.quizIsVisible ) _this.hideQuiz();
			else _this.showQuiz();
			
		});
		
		$('a.quiznext').live('click', function(){
			if ( _this.checkAnswer() )
			{
				return _this.loadNextQuestion();
			}
			else
			{
				return false;
			}
		});
		
		$('a.resetquiz').live('click', function(){
			_this.resetQuiz();
			return false;
		});
		
		$('a.closequiz').live('click', function(){
			_this.hideQuiz();
			return false;
		});
		
		this.quizBox.jqDrag('#quizdrag');
	},
	
	showQuiz : function()
	{
		this.quizBox.show();
		this.quizIsVisible = true;
	},
	
	hideQuiz : function()
	{
		this.quizBox.hide();
		this.quizIsVisible = false;
	},
	
	checkAnswer : function()
	{
		if ( this.currentQuestion !== -1 )
		{
			var selected = $('input[name=answer]:checked');
			
			if ( ! selected.size() )
			{
				// nothing selected
				this.showErrors( 'empty' );
				return false;
			}
			else if ( selected.attr('value') == f2fQuizQuestions[this.currentQuestion].correctAnswer )
			{
				// correct answer
				this.correctQuestions++;
				return true;
			}
			else
			{
				// wrong answer
				this.errors++;
				this.showErrors( 'wrong' );
				return false;
			}
		}
		else
		{
			return true;
		}
	},
	
	displayQuestion : function( questionNum )
	{
		var q 			= '<p class="quizquestion">'+f2fQuizQuestions[questionNum].question+'</p>',
			answers 	= '<ul>',
			link 		= '<p><a href="#'+f2fQuizQuestions[questionNum].goTo+'" class="quiznext">next</a></p>',
			answerArray = f2fQuizQuestions[questionNum].answers;

		for ( var i = 0; i < answerArray.length; i++ )
		{
			answers += '<li><input type="radio" name="answer" value="'+i+'" id="chbx'+i+'"> <label for="chbx'+i+'">'+answerArray[i]+'</label></li>';
		}
		
		answers += "</ul>";
		
		this.questionElm.html('');

		this.questionElm.append(q);
		this.questionElm.append(answers);
		this.questionElm.append(link);
		
		this.currentQuestion = questionNum;
	},
	
	loadNextQuestion : function()
	{
		var nextQuestion = this.currentQuestion + 1;

		if ( f2fQuizQuestions[nextQuestion] !== undefined )
		{
			// load up the next question....
			this.displayQuestion( nextQuestion );
			return true;
		}
		else
		{
			this.finishQuiz(); // quiz is over!!
			return false;
		}
	},
	
	showErrors : function( type )
	{
		var _this = this;
		switch( type )
		{
			case 'empty':
				this.chooseAnswer.stop().fadeIn('fast').animate( { 'right':'-225px' }, 'fast', function(){	
					setTimeout( function(){
						_this.chooseAnswer.animate( { 'right':'50px' }, function(){
							_this.chooseAnswer.fadeOut('fast');
						});
					}, 1500 );
				});
			break;
			case 'form':
				alert('One or more required form fields are empty.');
			break;
			default:
				this.wrongAnswer.stop().fadeIn('fast').animate( { 'right':'-200px' }, 'fast', function(){	
					setTimeout( function(){
						_this.wrongAnswer.animate( { 'right':'50px' }, function(){
							_this.wrongAnswer.fadeOut('fast');
						});
					}, 1500 );
				});
			break;
		}
	},
	
	getErrorString : function()
	{
		var errorStr = '';
		if ( this.errors == 0 )
		{
			return 'no errors at all!';
		}
		else if ( this.errors == 1 )
		{
			return 'only one error!';
		}
		else
		{
			return 'just '+this.errors+' errors along the way!';
		}
	},
	
	finishQuiz : function()
	{
		var finishString = 	'<div id="quizform">'+
							'<h2>Well done, you got all the answers correct with <em>'+this.getErrorString()+'</em></h2>'+
							'<p>Now enter your postal address so we can post you your seeds. You can enter your email address too if you have one to get more offers and things in the future.</p>'+
							'<form method="post">'+
								'<p class="label"><label for="name">Your name:*</label></p>'+
								'<p class="field"><input id="name" value="" name="name" class="text"></p>'+
								'<p class="label"><label for="age">Your age:*</label></p>'+
								'<p class="field"><input id="age" value="" name="age" class="text"></p>'+
								'<p class="label"><label for="email">Your email: </label></p>'+
								'<p class="field"><input id="email" value="" name="email" class="text"></p>'+
								'<p class="label"><label for="address">Your address:* </label></p>'+
								'<p class="field"><textarea id="address" name="address"></textarea></p>'+
								'<p class="checkbox"><input type="checkbox" name="permission" id="permission" value="YES"><label for="permission">I give permission for Natures Way Food to send me information and things.</label></p>'+
								'<p><button type="submit"><img src="/img/submit.png"></button> or &nbsp;<a href="#" class="resetquiz">re-start the quiz</a></p>'+
							'</form>'+
							'</div>';
		
		this.questionElm.html(finishString);
		
		var form = $('#quizform form');
		var _this = this;
		
		form.submit(function(){
			
			if ( form.find('[name=name]').val().replace(/\s+/,'') !== '' &&
				form.find('[name=age]').val().replace(/\s+/,'') !== '' &&
				form.find('[name=address]').val().replace(/\s+/,'') !== '' ){
					
				if ( ! ( form.find('[name=permission]:checked').size() && form.find('[name=permission]:checked').val() == 'YES' ) )
				{
					alert('You must tick the checkbox to give us permission to send you stuff before we can register your details!')
				}
				else
				{
					$.post( '/savedetails.php', form.serialize(), function(){
		
						_this.questionElm.html('<h2>Thank you!</h2><p>Your seeds are on their way...</p><p><a href="#" class="resetquiz">Re-start quiz</a></p>');
		
					});						
				}
			}
			else
			{
				_this.showErrors('form')
			}

			return false;
		});
		
	},
	
	resetQuiz : function()
	{	
		this.currentQuestion = -1;
		this.correctQuestions = 0;
		this.errors = 0;
		this.questionElm.html(this.startText);
	}
		
}

$(function(){
	f2fQuiz.initQuiz();
});