var PqQuizReferral = Class.create(
{
	element: null,
	
	dom: {},
	
	sent: false,
	
	initialize: function( element )
	{
		this.element = $( element );
		this.initDOM();
		
		if( !this.dom.referralButton )
			return; // quiz has not been completed, bail out!
		
		this.initEvents();
	},
	
	initDOM: function()
	{
		this.dom.referralButton = $( "recommend-to-friends" );
		this.dom.resultDialog = $( "result-dialog" );
		this.dom.navBox = $( "nav-box" );
		this.dom.submitButton = $( "referral-submit" );
		this.dom.cancelButton = $( "referral-cancel" );
	},
	
	initEvents: function()
	{
		this.element.observe( "submit", this.handleSubmit.bind( this ) );
		this.dom.referralButton.observe( "click", this.handleClickReferral.bind( this ) );
		this.dom.cancelButton.observe( "click", this.handleClickCancel.bind( this ) );
	},
	
	/**
	 * Event Handlers
	 */
	
	handleSubmit: function( e )
	{
		Event.stop( e );
		
		this.dom.submitButton.setValue( "Please wait..." );
		
		var first = this.element.select( "input" )[0];
		
		if( !$F( first ) )
		{
			this.dom.submitButton.setValue( "Send" );
			alert( "You must enter at least one e-mail address" );
			return;
		}
		
		this.element.request( 
		{
			onComplete: function()
			{
				this.dom.submitButton.setValue( "Send" );
				
			}.bind( this ),
			
			onSuccess: function( transport )
			{
				alert( "Recommendation e-mails sent!" );
				this.hide();
			
			}.bind( this ),
			
			onFailure: function()
			{
				alert( "ERROR!\nCould not sent e-mails.\n\nPlease try again." );
			}
		});
	},
	
	handleClickReferral: function( e )
	{
		Event.stop( e );
		this.show();
	},
	
	handleClickCancel: function( e )
	{
		Event.stop( e );
		this.hide();
	},
	
	/**
	 * Other methods
	 */
	
	show: function()
	{
		this.dom.resultDialog.hide();
		this.dom.navBox.hide();
		this.element.reset();
		this.element.show();
		this.element.focusFirstElement();
	},
	
	hide: function()
	{
		this.element.hide();
		this.dom.resultDialog.show();
		this.dom.navBox.show();
	}
});

document.observe( "dom:loaded", function(){ new PqQuizReferral( "pq-quiz-referral" ) } );
