/**
 * One-off form class for PQ quiz landing pages.
 * This form requires the user to enter his/her first name and e-mail address
 * prior to displaying the Flash quiz.
 */

var PqQuizStart = Class.create(
{
	element: null,
	
	dom: {},
	
	initialize: function( element )
	{
		this.element = $( element );
		
		if( !this.element ) return;
		
		this.initDOM();
		this.initEvents();
	},
	
	initDOM: function()
	{
		this.dom.container = $( "pq-quiz-start-container" );
		this.dom.flashQuiz = $( "pq-quiz" );
		this.dom.submitButton = $( "submit-button" );
	},
	
	initEvents: function()
	{
		this.element.observe( "submit", this.handleSubmit.bind( this ) );
	},
	
	handleSubmit: function( e )
	{
		Event.stop( e );
		this.dom.submitButton.value = "Please wait...";
		
		if( !$F( "email_address" ) || !$F( "first_name" ) || !$F( "last_name" ) )
		{
			this.dom.submitButton.value = "Start taking the quiz";
			alert( "You must enter your First and Last Name and your E-mail address" );
			return true;
		}
		
		this.element.request(
		{
			onSuccess: function( transport )
			{
				var response = transport.headerJSON;
				
				if( response.success )
					this.showQuiz();
				else
					alert( "Sorry! There was an error.\nPlease refresh the page and try again. [APP]" );
				
			}.bind( this ),
			
			onFailure: function()
			{
				alert( "Sorry! There was an error.\nPlease refresh the page and try again. [HTTP]" );
			}
		});
	},
	
	showQuiz: function()
	{
		this.dom.container.hide();
		
		if( pqQuiz )
			pqQuiz.load();
		else
			alert( "I can't find the quiz" );
	}
});

document.observe( "dom:loaded", function(){ new PqQuizStart( "pq-quiz-start" ) } );
