$extend( FY, {

	initProfilePopup: function()
	{	
		var popup = FY.Profile = new Aurora.Popup({
				width: 567,
				height: 750,
				zIndex: 5000,
				transitionDelay: 4,
				transitionInSteps: 6,
				transitionOutSteps: 6,
				closeButton: false,
				noCanvas: true
			})
			.addEvent( 'ready', function() {
	
				var content = this.$content;
				
				new Request.HTML()
					.get( '/Resources/FY/Sites/FindYoga/HTML/New/Profile.html?=' + $time() )
					.addEvent( 'success', (function() {
							
						content.setStyle( 'background', 'none' );
						
						// Init the options
						FY.initProfileForm( this.response.html );
				
					}) );
			
			});
	},
	
	initProfileForm: function( formHTML )
	{
		// Insert the html		
		FY.Profile.$content.set( 'html', formHTML );
		
		$( 'button_close' ).addEvent( 'click', function() { FY.Profile.close(); });
		$( 'button_done' ).addEvent( 'click', function() { FY.Profile.close(); });
	
		// Init validation
		FY.FormTools.initValidationHint( { field: 'name', type: 'length', hintMsg: 'e.g John Smith', errorMsg: 'Please enter a name', notRequired: false } );
		FY.FormTools.initValidationHint( { field: 'emailAddress', type: 'email', hintMsg: 'eg. john@smith.com', errorMsg: 'Please enter a valid email', notRequired: false } );
		
		FY.FormTools.initValidationHint( { field: 'zipcode', type: 'length', hintMsg: '', errorMsg: 'Please enter a zip code', notRequired: false } );
		FY.FormTools.initValidationHint( { field: 'state', type: 'length', hintMsg: '', errorMsg: 'Please enter a state', notRequired: false } );
		FY.FormTools.initValidationHint( { field: 'country', type: 'length', hintMsg: '', errorMsg: 'Please enter a country', notRequired: false } );
		
		var blurFields = function()
		{
			$( 'name' ).fireEvent( 'blur' );
			$( 'emailAddress' ).fireEvent( 'blur' );
			$( 'zipcode' ).fireEvent( 'blur' );
			$( 'state' ).fireEvent( 'blur' );
			$( 'country' ).fireEvent( 'blur' );	
		};
		
		var member = Aurora.dataAPI.data.load.client;
		
		$( 'name' ).set( 'value', member.name ).setStyle( 'color', '#4D4D4D' );
		$( 'emailAddress' ).set( 'value', member.emailAddress ).setStyle( 'color', '#4D4D4D' );
		$( 'zipcode' ).set( 'value', member.homePostcode ).setStyle( 'color', '#4D4D4D' );
		$( 'state' ).set( 'value', member.homeState ).setStyle( 'color', '#4D4D4D' );
		$( 'country' ).set( 'value', member.homeCountry ).setStyle( 'color', '#4D4D4D' );
		
		$( 'newsletter' ).set( 'checked', member.subscribed_to.newsletter );
		
		blurFields();
	
		$( 'form_profile' ).addEvent( 'submit', function(e) {

			return true;
		
		});
	
		$( 'submitForm' ).addEvent( 'click', function() {
		
			if ( FY._processingProfile )
				return;
		
			// Check form
			if ( checkForm() ) {
			
				disableForm();
			
				// Check the email address availability
				checkEmail();
			}
			else
				return false;
									
		});
		
		var disableForm = function()
		{
			FY._processingProfile = true;
			$( 'submitForm' ).getElement( '.wrap2' ).set( 'text', '...' );
			$( 'submitForm' ).set( 'opacity', 0.4 );
		};
		
		var enableForm = function()
		{
			FY._processingProfile = false;
			$( 'submitForm' ).getElement( '.wrap2' ).set( 'text', 'Save Changes' );
			$( 'submitForm' ).set( 'opacity', 1 );
		};
		
		var checkForm = function()
		{
			FY.FormTools._invalidFields = [ 'name', 'emailAddress', 'zipcode', 'state', 'country' ];
		
			blurFields();
		
			var newPassword = $( 'newPassword' ).value;
			var confirmPassword = $( 'confirmPassword' ).value;
			
			if ( newPassword && confirmPassword && newPassword.length < 6 )
			{
				alert( "Please enter a password at least six characters long." );
				enableForm();
				return false;
			}
			
			if ( newPassword && confirmPassword && ( newPassword != confirmPassword ) )
			{
				alert( "Please make sure the password you entered in both fields matches." );
				enableForm();
				return false;
			}
		
			if ( FY.FormTools._invalidFields.length ) {
			
				blurFields();
				
				enableForm();
				return false;
			}
			
			return true;
		
		};
		
		var checkEmail = function()
		{
			// Check email if in use
			var email = $( 'emailAddress' ).value;
		
			if ( !email.length || email == '(required)' )
				return false;
				
			// If its the same email, skip the process
			if ( email == Aurora.dataAPI.data.load.client.emailAddress ) {
				validateForm();
				return;
			}
		
			Aurora.callAction({
				
				action: 'member.isEmailAddressInUse',
				data: { emailAddress: email },
				
				onComplete: function( rtnData ) {
					
					if ( !rtnData ) {
						enableForm();
						return false;
					}
			
					if ( !rtnData.success ) {
						alert( 'Oops! Something went wrong. Please check your email address and try again. If you continue to encounter problems, please contact us.' );
						enableForm();
						return false;
					}
					
					if ( rtnData.isInUse ) {
						alert( 'Oops! Someone is already using that email address with Find Yoga, you might already have an account with us.\n\nPlease try and sign in.\n\nOtherwise, try using another email address.' );
						enableForm();
						$log( 'Email in use.' );
						return false;
					}
					
					$log( 'Email not in use.' );
					
					// Validate one last time
					validateForm();
									
				}
			});
			
		};
		
		var validateForm = function()
		{
			// Submit the form
			$log( 'Validating form...' );
			
			if ( checkForm() )
			{
				FY.saveProfile();
				enableForm();
				$log( 'Validation successful, saving profile.' );
				
			}
			else
			{
				enableForm();
				$log( 'Validation failed, invalid or required fields.' );
				return false;
			}
		
		};
	
	},
	
	saveProfile: function()
	{
		// Data
		var data = {
			memberId: Aurora.dataAPI.data.load.client.memberId,
			name: $( 'name' ).value.trim(),
			emailAddress: $( 'emailAddress' ).value.trim(),
			homePostcode: $( 'zipcode' ).value.trim(),
            homeState: $( 'state' ).value.trim(),
            homeCountry: $( 'country' ).value.trim(),
            newsletter: $( 'newsletter' ).checked
		};
		
		if ( $( 'newPassword' ).value && $( 'confirmPassword' ).value ) {
			data.newPassword = $( 'newPassword' ).value;
            data.confirmPassword = $( 'confirmPassword' ).value;
        }

		Aurora.callAPI({
			
			key: 'update client',
			data: data,
			
			onComplete: function( rtnData ) {
			
				if ( rtnData.success )
				{
					// Extend Data
					$extend( Aurora.dataAPI.data.load.client, data );
					
					Aurora.dataAPI.data.load.client.subscribed_to.newsletter = data.newsletter;
					
					$( 'button_close' ).set( 'text', 'close' );
					
					$( 'form_profile_details' ).hide();
					$( 'form_profile_done' ).show();
				}
				else
				{
					alert( 'Oops! Something went wrong. Please check your details and try again. If you continue to encounter problems, please contact us.' );
				}
				
			}
			
			
		});	
	}

});
