var account = null;

;( function( $ ) {

	var GET_INFO_AJAX_URL          = contextRoot + '/account/ajax/get-info.do';
	var LOGIN_AJAX_URL             = contextRoot + '/account/ajax/login.do';
	var FACEBOOK_LOGIN_AJAX_URL    = contextRoot + '/account/ajax/facebook-login.do';
	var LOGOUT_AJAX_URL            = contextRoot + '/account/ajax/logout.do';
	var REGISTER_AJAX_URL          = contextRoot + '/account/ajax/register.do';
	var FACEBOOK_REGISTER_AJAX_URL = contextRoot + '/account/ajax/facebook-register.do';
	var FORGOT_PASSWORD_AJAX_URL   = contextRoot + '/account/ajax/forgot-password.do';

	var isReady = false;
	var dialogs = new Array();
	var loadingDialog;
	var messageDialog;
	var loginDialog;
	var registerDialog;
	var facebookRegisterDialog;
	var forgotPasswordDialog;
	var listeners = new Array;
	var userInfo = { loggedIn : 'false' };

	// -------------------- Initializes the account library.
	//
	function init() {

		// Construct the account library object.
		account = {
			login       : function() { if ( isReady ) showDialog( loginDialog ); },
			logout      : function() { logoutUser(); },
			register    : function() { if ( isReady ) showDialog( registerDialog ); },
			addListener : function( obj ) { listeners[ listeners.length ] = obj; },
			getUserInfo : function() { return userInfo; },
			isLoggedIn  : function() { return userInfo.loggedIn == 'true'; }
		};

		// When the DOM is ready...
		$( document ).ready( function() {

			// Initialize Facebook single sign-on.
			initFacebook();

			// Initialize the loading dialog.
			initLoadingDialog();

			// Initialize the message dialog.
			initMessageDialog();

			// Initialize the login dialog.
			initLoginDialog();

			// Initialize the register dialog.
			initRegisterDialog();

			// Initialize the Facebook user register dialog.
			initFacebookRegisterDialog();

			// Initialize the forgot password dialog.
			initForgotPasswordDialog();

			// Check if the user is already logged in.
			restoreUserInfo();

		} );

	};

	// -------------------- Initializes Facebook single sign-on.
	//
	function initFacebook() {

		if (window["FB"] != undefined) {
			
			FB.init( {
				appId  : 'c654b0a35f437199ce7171d59eae7ca8',
				status : true,
				cookie : true,
				xfbml  : true
			} );
			
			FB.Event.subscribe( 'auth.sessionChange', function( response ) {
				if ( response.session ) {
					//alert( 'facebook user logged in' );
				} else {
					//alert( 'facebook user logged out' );
				}
			});

		}

	};

	// -------------------- Initialize the loading dialog.
	//
	function initLoadingDialog() {

		// Generate the dialog HTML.
		$( 'body' ).append(
			  '<div id="loading-dialog" title="Loading">'
			+ '  <div class="dialog-content loading-dialog-content">One moment please&hellip;</div>'
			+ '</div>'
		);

		loadingDialog = $( '#loading-dialog' );
		dialogs[ dialogs.length ] = loadingDialog;

		// Create the dialog window.
		loadingDialog.dialog( {
			width         : 400,
			autoOpen      : false,
			closeOnEscape : false,
			draggable     : false,
			modal         : true,
			resizable     : false,
			open          : function( event, ui ) {

				// Hide the title bar.
				$( '.ui-dialog-titlebar', $( this ).parent() ).hide();

			}
		} );

	};

	// -------------------- Initialize the message dialog.
	//
	function initMessageDialog() {

		// Generate the dialog HTML.
		$( 'body' ).append(
			  '<div id="message-dialog">'
			+ '  <div class="dialog-content message-dialog-content">'
			+ '    <div class="message-dialog-text">-</div>'
			+ '    <div><a href="#" class="dialog-button message-dialog-close"><span>OK</span></a></div>'
			+ '  </div>'
			+ '</div>'
		);

		messageDialog = $( '#message-dialog' );
		dialogs[ dialogs.length ] = messageDialog;

		// Create the dialog window.
		messageDialog.dialog( {
			width     : 590,
			autoOpen  : false,
			draggable : false,
			modal     : true,
			resizable : false,
			open      : function( event, ui ) {

				// Hide the title bar.
				$( '.ui-dialog-titlebar', $( this ).parent() ).hide();

			}
		} );

		// Setup the close dialog link.
		$( '.message-dialog-close', messageDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( null );
		} );

	};

	// -------------------- Initialize the login dialog.
	//
	function initLoginDialog() {

		// Generate the dialog HTML.
		$( 'body' ).append(
			  '<div id="login-dialog" title="Login">'
			+ '  <div class="dialog-content login-dialog-content">'
			+ '    <div class="login-dialog-dialoghead">'
			+ '      <a href="#" class="login-dialog-close ui-state-default ui-corner-all" title="Close"><span class="ui-icon ui-icon-close">&nbsp;</span></a>'
			+ '      Login to save your color selections'
			+ '    </div>'
			+ '    <div class="login-dialog-loggedout">'
			+ '      <div class="login-dialog-column1">'
			+ '        <div class="login-dialog-column1-inside">'
			+ '          <div class="login-dialog-columnhead">Login with your Glidden<sup>&reg;</sup> account</div>'
			+ '          <form action="#">'
			+ '            <div>'
			+ '              <div class="login-dialog-question"><label for="login-dialog-username">What is your email address?</label></div>'
			+ '              <div class="login-dialog-textfield"><input type="text" id="login-dialog-username" name="username" value="" /></div>'
			+ '            </div>'
			+ '            <div>'
			+ '              <div class="login-dialog-question">Do you have a Glidden account?</div>'
			+ '              <div class="login-dialog-option"><input type="radio" id="login-dialog-hasaccount-no" name="hasAccount" value="no" checked="checked" /><label for="login-dialog-hasaccount-no">No, please let me register.</label></div>'
			+ '              <div class="login-dialog-option"><input type="radio" id="login-dialog-hasaccount-yes" name="hasAccount" value="yes" /><label for="login-dialog-hasaccount-yes">Yes, my password is:</label></div>'
			+ '              <div class="login-dialog-textfield"><input type="password" id="login-dialog-password" name="password" value="" /></div>'
			+ '              <div class="login-dialog-forgot-password"><a href="#" class="account-util-link">Forgot your password?</a></div>'
			+ '            </div>'
			+ '            <div class="login-dialog-button">'
			+ '              <a href="#" class="dialog-button login-dialog-button-login"><span>Login</span></a>'
			+ '              <a href="#" class="dialog-button login-dialog-button-register"><span>Go To The Registration Form</span></a>'
			+ '            </div>'
			+ '            <div class="login-dialog-error">-</div>'
			+ '          </form>'
			+ '        </div>'
			+ '      </div><!-- End div.login-dialog-column1. -->'
			+ '      <div class="login-dialog-column2">'
			+ '        <div class="login-dialog-column2-inside">'
			+ '          <div class="login-dialog-columnhead">Login with your Facebook account</div>'
			+ '          <div class="login-dialog-facebook"><a href="#"><span>Login with Facebook</span></a></div>'
			+ '          <div class="login-dialog-facebook-infolink"><a href="#" class="account-util-link">What is this?</a></div>'
			+ '          <div class="login-dialog-facebook-infocontent">You may use your Facebook login instead of a Glidden account to access personalized features on this&nbsp;website.</div>'
			+ '        </div>'
			+ '      </div>'
			+ '      <div class="clearPixel">&nbsp;</div>'
			+ '    </div><!-- End div.login-dialog-loggedout. -->'
			+ '    <div class="login-dialog-loggedin">'
			+ '        You are currently logged in as <span class="login-dialog-loggedin-firstname">-</span>.'
			+ '    </div>'
			+ '  </div><!-- End div.dialog-content. -->'
			+ '</div>'
		);

		loginDialog = $( '#login-dialog' );
		dialogs[ dialogs.length ] = loginDialog;

		// Create the dialog window.
		loginDialog.dialog( {
			width     : 600,
			autoOpen  : false,
			draggable : false,
			modal     : true,
			resizable : false,
			open      : function( event, ui ) {

				// Hide the title bar.
				$( '.ui-dialog-titlebar', $( this ).parent() ).hide();

				// Hide the error message.
				$( '.login-dialog-error', this ).hide();

				// Only show the login form if the user is not logged in.
				if ( userInfo.loggedIn == 'true' ) {
					$( '.login-dialog-loggedin-firstname', this ).html( userInfo.firstName );
					$( '.login-dialog-loggedin', this ).show();
					$( '.login-dialog-loggedout', this ).hide();
				} else {
					$( '.login-dialog-loggedin', this ).hide();
					$( '.login-dialog-loggedout', this ).show();
				}

			}
		} );

		// Setup the close dialog link.
		$( '.login-dialog-close', loginDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( null );
			dispatchEvent( 'onLoginCancel' ); // Notify all listeners that the user cancelled the login.
		} );

		// Setup the login form. 
		$( 'form', loginDialog ).submit( function( e ) {
			e.preventDefault();
			loginUser();
		} );

		// Setup the login link.
		$( '.login-dialog-button-login', loginDialog ).click( function( e ) {
			e.preventDefault();
			$( 'form', loginDialog ).submit();
		} );

		// Setup the radio buttons.
		var passwordField = $( '#login-dialog-password', loginDialog );
		var passwordFieldHasFocus = false;
		$( passwordField ).focus( function( e ) {
			passwordFieldHasFocus = true;
			$( '#login-dialog-hasaccount-yes', loginDialog ).click();
		} ).blur( function( e ) {
			passwordFieldHasFocus = false;
		} );
		$( '#login-dialog-hasaccount-no', loginDialog ).click( function( e ) {
			$( '.login-dialog-button-login', loginDialog ).hide();
			$( '.login-dialog-button-register', loginDialog ).show();
			$( passwordField ).css( 'opacity', '0.4' ).css( 'filter', 'alpha(opacity=40)' );
		} ).click();
		$( '#login-dialog-hasaccount-yes', loginDialog ).click( function( e ) {
			$( '.login-dialog-button-login', loginDialog ).show();
			$( '.login-dialog-button-register', loginDialog ).hide();
			if ( passwordFieldHasFocus == false ) $( passwordField ).focus();
			$( passwordField ).css( 'opacity', '1' ).css( 'filter', 'alpha(opacity=100)' );
		} );

		// Setup the register link.
		$( '.login-dialog-button-register', loginDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( registerDialog );
			$( '#register-dialog-email', registerDialog ).val( $( '#login-dialog-username', loginDialog ).val() );
		} );

		// Setup the forgot password link.
		$( '.login-dialog-forgot-password a', loginDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( forgotPasswordDialog );
		} );

		// Setup the login using Facebook link.
		$( '.login-dialog-facebook a', loginDialog ).click( function( e ) {
			e.preventDefault();
			showFacebookLoginDialog();
		} );

		// Setup the login using Facebook "What is this?" link.
		$( '.login-dialog-facebook-infocontent', loginDialog ).hide();
		$( '.login-dialog-facebook-infolink a', loginDialog ).click( function( e ) {
			e.preventDefault();
			$( '.login-dialog-facebook-infocontent', loginDialog ).toggle();
		} );

	};

	// -------------------- Initialize the register dialog.
	//
	function initRegisterDialog() {

		// Generate the dialog HTML.
		$( 'body' ).append(
			  '<div id="register-dialog" title="Register">'
			+ '  <div class="dialog-content register-dialog-content">'
			+ '    <form action="#">'
			+ '      <div class="register-dialog-dialoghead">'
			+ '        <a href="#" class="register-dialog-close ui-state-default ui-corner-all" title="Close"><span class="ui-icon ui-icon-close">&amp;nbsp;</span></a>'
			+ '        Register a new Glidden<sup>&reg;</sup> account'
			+ '      </div>'
			+ '      <div class="register-dialog-dialogintro">Register now so you can save your favorite color combos and share your new room designs with&nbsp;friends.</div>'
			+ '      <div class="register-dialog-formrow">'
			+ '        <label for="register-dialog-email" class="register-dialog-label">Email:</label>'
			+ '        <input type="text" id="register-dialog-email" name="emailAddress" value="" class="required email" />'
			+ '      </div>'
			+ '      <div class="register-dialog-formrow">'
			+ '        <label for="register-dialog-firstname" class="register-dialog-label">First Name:</label>'
			+ '        <input type="text" id="register-dialog-firstname" name="firstName" value="" class="required" />'
			+ '      </div>'
			+ '      <div class="register-dialog-formrow">'
			+ '        <label for="register-dialog-lastname" class="register-dialog-label">Last Name:</label>'
			+ '        <input type="text" id="register-dialog-lastname" name="lastName" value="" class="required" />'
			+ '      </div>'
			+ '      <div class="register-dialog-formrow">'
			+ '        <label for="register-dialog-password" class="register-dialog-label">Password:</label>'
			+ '        <input type="password" id="register-dialog-password" name="password" value="" class="required" />'
			+ '      </div>'
			+ '      <div class="register-dialog-formrow">'
			+ '        <label for="register-dialog-confirmpassword" class="register-dialog-label">Confirm Password:</label>'
			+ '        <input type="password" id="register-dialog-confirmpassword" name="password" value="" class="required" />'
			+ '      </div>'
			+ '      <div class="register-dialog-optinrow">'
			+ '        <input type="checkbox" id="register-dialog-optin" name="optIn" value="true" />'
			+ '        <label for="register-dialog-optin">Please send me emails about Glidden promotions, offers or&nbsp;products.</label>'
			+ '      </div>'
			+ '      <div class="register-dialog-forgot-password" style="margin-left: 160px;"><a href="#" class="account-util-link">Forgot your password?</a><br /><br /></div>'
			+ '      <div class="register-dialog-button"><a href="#" class="dialog-button register-dialog-submit"><span>Register</span></a></div>'
			+ '      <div class="register-dialog-error-container">'
			+ '        <div class="register-dialog-error">-</div>'
			+ '      </div>'
			+ '      <div class="register-dialog-disclaimer account-util-link">By registering, you are agreeing to the<br /><a href="' + contextRoot + '/terms/privacy-policy.do" target="_blank" class="account-util-link">Glidden Terms, Conditions and Privacy Policy</a>.</div>'
			+ '    </form>'
			+ '  </div>'
			+ '</div>'
		);

		registerDialog = $( '#register-dialog' );
		dialogs[ dialogs.length ] = registerDialog;

		// Create the dialog window.
		registerDialog.dialog( {
			width     : 410,
			autoOpen  : false,
			draggable : false,
			modal     : true,
			resizable : false,
			open      : function( event, ui ) {

				// Hide the title bar.
				$( '.ui-dialog-titlebar', $( this ).parent() ).hide();

				// Hide the error message.
				$( '.register-dialog-error', this ).hide();

			}
		} );

		// Setup the close dialog link.
		$( '.register-dialog-close', registerDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( null );
			dispatchEvent( 'onLoginCancel' ); // Notify all listeners that the user cancelled the login.
		} );

		// Setup the register form. 
		$( 'form', registerDialog ).validate( {
			submitHandler: function( form ) {
				registerUser();
			}
		} );
		
		// Setup the forgot password link.
		$( '.register-dialog-forgot-password a', registerDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( forgotPasswordDialog );
		} );		
		
		// Setup the submit button.
		$( '.register-dialog-submit', registerDialog ).click( function( e ) {
			e.preventDefault();
			$( 'form', registerDialog ).submit();
		} );
	};

	// -------------------- Initialize the Facebook user register dialog.
	//
	function initFacebookRegisterDialog() {

		// Generate the dialog HTML.
		$( 'body' ).append(
			  '<div id="facebook-register-dialog" title="Register">'
			+ '  <div class="dialog-content facebook-register-dialog-content">'
			+ '    <form action="#">'
			+ '      <input type="hidden" id="facebook-register-dialog-facebookuserid" name="facebookUserId" value="" />'
			+ '      <div class="facebook-register-dialog-dialoghead">'
			+ '        <a href="#" class="facebook-register-dialog-close ui-state-default ui-corner-all" title="Close"><span class="ui-icon ui-icon-close">&nbsp;</span></a>'
			+ '        Welcome <span class="facebook-register-dialog-welcome">&nbsp;</span>,'
			+ '      </div>'
			+ '      <div class="facebook-register-dialog-dialogintro">'
			+ '        Please take a moment to register your Facebook account with Glidden.com. Once registered, you can save your favorite color combos and share your new room designs with&nbsp;friends.'
			+ '      </div>'
			+ '      <div class="facebook-register-dialog-formrow">'
			+ '        <label for="facebook-register-dialog-firstname" class="facebook-register-dialog-label">First Name:</label>'
			+ '        <input type="text" id="facebook-register-dialog-firstname" name="firstName" value="" class="required" />'
			+ '      </div>'
			+ '      <div class="facebook-register-dialog-formrow">'
			+ '        <label for="facebook-register-dialog-lastname" class="facebook-register-dialog-label">Last Name:</label>'
			+ '        <input type="text" id="facebook-register-dialog-lastname" name="lastName" value="" class="required" />'
			+ '      </div>'
			+ '      <div class="facebook-register-dialog-formrow">'
			+ '        <label for="facebook-register-dialog-email" class="facebook-register-dialog-label">Email:</label>'
			+ '        <input type="text" id="facebook-register-dialog-email" name="emailAddress" value="" class="required email" />'
			+ '      </div>'
			+ '      <div class="facebook-register-dialog-optinrow">'
			+ '        <input type="checkbox" id="facebook-register-dialog-optin" name="optIn" value="true" />'
			+ '        <label for="facebook-register-dialog-optin">Please send me emails about Glidden promotions, offers or&nbsp;products.</label>'
			+ '      </div>'
			+ '      <div class="facebook-register-dialog-button"><a href="#" class="dialog-button facebook-register-dialog-submit"><span>Register</span></a></div>'
			+ '      <div class="facebook-register-dialog-error-container">'
			+ '        <div class="facebook-register-dialog-error">-</div>'
			+ '      </div>'
			+ '      <div class="facebook-register-dialog-disclaimer account-util-link">By registering, you are agreeing to the<br /><a href="' + contextRoot + '/terms/privacy-policy.do" target="_blank" class="account-util-link">Glidden Terms, Conditions and Privacy Policy</a>.</div>'
			+ '    </form>'
			+ '  </div>'
			+ '</div>'
		);

		facebookRegisterDialog = $( '#facebook-register-dialog' );
		dialogs[ dialogs.length ] = facebookRegisterDialog;

		// Create the dialog window.
		facebookRegisterDialog.dialog( {
			width     : 410,
			autoOpen  : false,
			draggable : false,
			modal     : true,
			resizable : false,
			open      : function( event, ui ) {

				// Hide the title bar.
				$( '.ui-dialog-titlebar', $( this ).parent() ).hide();

				// Hide the error message.
				$( '.facebook-register-dialog-error', this ).hide();

			}
		} );

		// Setup the close dialog link.
		$( '.facebook-register-dialog-close', facebookRegisterDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( null );
			dispatchEvent( 'onLoginCancel' ); // Notify all listeners that the user cancelled the login.
		} );

		// Setup the Facebook register form. 
		$( 'form', facebookRegisterDialog ).validate( {
			submitHandler: function( form ) {
				facebookRegisterUser();
			}
		} );

		// Setup the submit button.
		$( '.facebook-register-dialog-submit', facebookRegisterDialog ).click( function( e ) {
			e.preventDefault();
			$( 'form', facebookRegisterDialog ).submit();
		} );

	};

	// -------------------- Initialize the forgot password dialog.
	//
	function initForgotPasswordDialog() {

		// Generate the dialog HTML.
		$( 'body' ).append(
			  '<div id="forgot-password-dialog" title="Forgot Password">'
			+ '  <div class="dialog-content forgot-password-dialog-content">'
			+ '    <form action="#">'
			+ '      <div class="forgot-password-dialog-dialoghead">'
			+ '        <a href="#" class="forgot-password-dialog-close ui-state-default ui-corner-all" title="Close"><span class="ui-icon ui-icon-close">&nbsp;</span></a>'
			+ '        Password Retrieval'
			+ '      </div>'
			+ '      <div class="forgot-password-dialog-formrow">'
			+ '        <label for="forgot-password-dialog-username">What is the email address used for the Glidden account?</label>'
			+ '        <input type="text" id="forgot-password-dialog-username" name="username" value="" />'
			+ '      </div>'
			+ '      <div class="forgot-password-dialog-button"><a href="#" class="dialog-button forgot-password-dialog-submit"><span>Send Me My Password</span></a></div>'
			+ '      <div class="forgot-password-dialog-error"><span>-</span> <a href="#">Register&nbsp;now!</a></div>'
			+ '    </form>'
			+ '  </div>'
			+ '</div>'
		);

		forgotPasswordDialog = $( '#forgot-password-dialog' );
		dialogs[ dialogs.length ] = forgotPasswordDialog;

		// Create the dialog window.
		forgotPasswordDialog.dialog( {
			width     : 380,
			autoOpen  : false,
			draggable : false,
			modal     : true,
			resizable : false,
			open      : function( event, ui ) {

				// Hide the title bar.
				$( '.ui-dialog-titlebar', $( this ).parent() ).hide();

				// Hide the error message.
				$( '.forgot-password-dialog-error', this ).hide();

			}
		} );

		// Setup the close dialog link.
		$( '.forgot-password-dialog-close', forgotPasswordDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( loginDialog );
		} );

		// Setup the forgot password form. 
		$( 'form', forgotPasswordDialog ).submit( function( e ) {
			e.preventDefault();
			emailLoginInfoToUser();
		} );

		// Setup the submit button.
		$( '.forgot-password-dialog-submit', forgotPasswordDialog ).click( function( e ) {
			e.preventDefault();
			$( 'form', forgotPasswordDialog ).submit();
		} );

		// Setup the register link.
		$( '.forgot-password-dialog-error a', forgotPasswordDialog ).click( function( e ) {
			e.preventDefault();
			showDialog( registerDialog );
			$( '#register-dialog-email', registerDialog ).val( $( '#forgot-password-dialog-username', forgotPasswordDialog ).val() );
		} );

	};

	// -------------------- Checks if the user is already logged in.
	//
	function restoreUserInfo() {

		// Get the logged in user's information.
		$.getJSON( GET_INFO_AJAX_URL, {}, function( data ) {

			// Update the user info.
			userInfo = data;

			// The account library is now fully initialized.
			isReady = true;

			// Notify all listeners if the user is logged in.
			dispatchEvent( 'onLoginChange' );

		} );

	};

	// -------------------- Logs in the user.
	//
	function loginUser() {

		// Show the loading dialog.
		showDialog( loadingDialog );

		// Get the parameters to send to the AJAX script.
		var params = {
			username : $( '#login-dialog-username' ).val(),
			password : $( '#login-dialog-password' ).val()
		};

		// Call the login AJAX script.
		$.getJSON( LOGIN_AJAX_URL, params, function( data ) {

			// Update the user info.
			userInfo = data;

			// If the login was successful...
			if ( userInfo.loggedIn == 'true' ) {

				// Clear the login form.
				$( '#login-dialog-username' ).val( '' );
				$( '#login-dialog-password' ).val( '' );

				// Close the loading dialog.
				loadingDialog.dialog( 'close' );

				// Track the event.
				trackPath( 'gliddenLoginSuccess' );

			} else {

				// Re-show the login dialog.
				showDialog( loginDialog );

				// Show the error message.
				$( '.login-dialog-error', loginDialog )
					.show()
					.html( 'Invalid email and password. Please try again.' );

				// Track the event.
				trackPath( 'gliddenLoginFail' );

			} // End if.

			// Notify all listeners that a login operation has taken place.
			dispatchEvent( 'onLoginChange' );

		} );

	};

	// -------------------- Logs out the user.
	//
	function logoutUser() {

		// Logout the user.
		$.getJSON( LOGOUT_AJAX_URL, {}, function( data ) {

			// Update the user info.
			userInfo = data;

			// Notify all listeners that the user logged out.
			dispatchEvent( 'onLoginChange' );

			// If the user logged in using Facebook, logout from the Facebook session.
			FB.getLoginStatus( function( response ) {
				if ( response.session ) {
					FB.logout( function( response ) {} );
				}
			});

			// Track the event.
			trackPath( 'logout' );

		} );

	};

	// -------------------- Registers a new Glidden account.
	//
	function registerUser() {

		// Make sure the passwords match.
		if ( $( '#register-dialog-password' ).val() != $( '#register-dialog-confirmpassword' ).val() ) {
			$( '.register-dialog-error', registerDialog )
				.show()
				.html( 'Please make sure the passwords match.' );
			return;
		}

		// Show the loading dialog.
		showDialog( loadingDialog );

		// Get the parameters to send to the AJAX script.
		var params = {
			firstName    : $( '#register-dialog-firstname' ).val(),
			lastName     : $( '#register-dialog-lastname' ).val(),
			emailAddress : $( '#register-dialog-email' ).val(),
			password     : $( '#register-dialog-password' ).val(),
			optIn        : $( '#register-dialog-optin:checked' ).val()
		};

		if ( params.optIn != 'true' ) params.optIn = 'false';

		// Call the register AJAX script.
		$.getJSON( REGISTER_AJAX_URL, params, function( data ) {

			// Update the user info.
			userInfo = data;

			// If the registration was successful...
			if ( data.responseCode == 'ok' ) {

				// Clear the register form.
				$( '#register-dialog-firstname' ).val( '' );
				$( '#register-dialog-lastname' ).val( '' );
				$( '#register-dialog-email' ).val( '' );
				$( '#register-dialog-password' ).val( '' );
				$( '#register-dialog-confirmpassword' ).val( '' );
				$( '#register-dialog-optin' ).each( function() {
					this.checked = false;
				} );

				// Show a success message.
				showMessage( 'Thank you for creating your Glidden account. You are now logged in as ' + userInfo.firstName + '.' );

				// Track the event.
				trackPath( 'gliddenRegisterSuccess' );

			} else {

				// Re-show the register dialog.
				showDialog( registerDialog );

				// Generate the error message.
				var errorMsg;
				var trackMsg;
				if ( data.responseCode == 'exists' ) {
					errorMsg = data.responseMessage;
					trackMsg = 'gliddenRegisterFailDuplicateEmail';
				} else {
					errorMsg = 'We\'re sorry. There was an unexpected error while saving your information. Please try again. [' + data.responseMessage + ']';
					trackMsg = 'gliddenRegisterFail';
				}

				// Show the error message.
				$( '.register-dialog-error', registerDialog )
					.show()
					.html( errorMsg );

				// Track the event.
				trackPath( trackMsg );

			} // End if.

			// Notify all listeners that a login operation has taken place.
			dispatchEvent( 'onLoginChange' );

		} );

	};

	// -------------------- Registers a new Glidden account from a Facebook account.
	//
	function facebookRegisterUser() {

		// Show the loading dialog.
		showDialog( loadingDialog );

		// Get the parameters to send to the AJAX script.
		var params = {
			firstName      : $( '#facebook-register-dialog-firstname' ).val(),
			lastName       : $( '#facebook-register-dialog-lastname' ).val(),
			emailAddress   : $( '#facebook-register-dialog-email' ).val(),
			optIn          : $( '#facebook-register-dialog-optin:checked' ).val(),
			facebookUserId : $( '#facebook-register-dialog-facebookuserid' ).val()
		};

		if ( params.optIn != 'true' ) params.optIn = 'false';

		// Call the Facebook register AJAX script.
		$.getJSON( FACEBOOK_REGISTER_AJAX_URL, params, function( data ) {

			// Update the user info.
			userInfo = data;

			// If the registration was successful...
			if ( data.responseCode == 'ok' ) {

				// Clear the Facebook register form.
				$( '#facebook-register-dialog-firstname' ).val( '' );
				$( '#facebook-register-dialog-lastname' ).val( '' );
				$( '#facebook-register-dialog-email' ).val( '' );
				$( '#facebook-register-dialog-optin' ).each( function() {
					this.checked = false;
				} );
				$( '#facebook-register-dialog-facebookuserid' ).val( '' );

				// Show a success message.
				showMessage( 'Thank you. You are now logged in as ' + userInfo.firstName + '.' );

				// Track the event.
				trackPath( 'facebookRegisterSuccess' );

			} else {

				// Re-show the Facebook register dialog.
				showDialog( facebookRegisterDialog );

				// Generate the error message.
				var errorMsg = 'We\'re sorry. There was an unexpected error while saving your information. Please try again. [' + data.responseMessage + ']';

				// Show the error message.
				$( '.facebook-register-dialog-error', facebookRegisterDialog )
					.show()
					.html( errorMsg );

				// Track the event.
				trackPath( 'facebookRegisterFail' );

			} // End if.

			// Notify all listeners that a login operation has taken place.
			dispatchEvent( 'onLoginChange' );

		} );

	};

	// -------------------- Dispatches events to the listener objects.
	//
	function emailLoginInfoToUser( event ) {

		// Show the loading dialog.
		showDialog( loadingDialog );

		// Get the parameters to send to the AJAX script.
		var params = {
			username : $( '#forgot-password-dialog-username' ).val()
		};

		// Email the login information to the user.
		$.getJSON( FORGOT_PASSWORD_AJAX_URL, params, function( data ) {

			// If the information was properly sent...
			if ( data.responseCode == 'ok' ) {

				// Clear the forgot password form.
				$( '#forgot-password-dialog-username' ).val( '' );

				showMessage( 'Your login information has been emailed to ' + data.emailAddress + '.' );

				// Track the event.
				trackPath( 'forgotPasswordSuccess' );

			// Else, if there was an error...
			} else {

				// Re-show the forgot password dialog.
				showDialog( forgotPasswordDialog );

				// Show the error message.
				$( '.forgot-password-dialog-error span', forgotPasswordDialog ).html( data.responseMessage );
				$( '.forgot-password-dialog-error', forgotPasswordDialog ).show();

				// Track the event.
				trackPath( 'forgotPasswordFail' );

			} // End if.

		} );

	};

	// -------------------- Shows the Facebook single sign-on dialog.
	//
	function showFacebookLoginDialog() {

		// Hide all jQuery dialogs.
		showDialog( null );

		// Show the Facebook login dialog.
		FB.login( function( response ) {
			if ( response.session ) {
				FB.api( '/me', function( response ) {
					loginFacebookUser( response );
				} );
			} else {
				// Facebook user cancelled the login.
			}
		});

	};

	// -------------------- Performed when a user logs in using a Facebook account.
	//
	function loginFacebookUser( fbUserInfo ) {

		// Show the loading dialog.
		showDialog( loadingDialog );

		// Call the facebook login AJAX script.
		$.getJSON( FACEBOOK_LOGIN_AJAX_URL, {}, function( data ) {

			// Update the user info.
			userInfo = data;

			// If there is a Glidden account associated with the Facebook account...
			if ( userInfo.loggedIn == 'true' ) {

				// Clear the login form.
				$( '#login-dialog-username' ).val( '' );
				$( '#login-dialog-password' ).val( '' );

				// Close the loading dialog.
				loadingDialog.dialog( 'close' );

				// Track the event.
				trackPath( 'facebookLoginSuccess' );

			// Else, if this is the first time this Facebook account has been used on this site...
			} else {

				// Populate the Facebook register form.
				$( '.facebook-register-dialog-welcome' ).html( fbUserInfo.first_name );
				$( '#facebook-register-dialog-facebookuserid' ).val( fbUserInfo.id );
				$( '#facebook-register-dialog-firstname' ).val( fbUserInfo.first_name );
				$( '#facebook-register-dialog-lastname' ).val( fbUserInfo.last_name );
				$( '#facebook-register-dialog-email' ).val( '' );
				$( '#facebook-register-dialog-optin' ).each( function() {
					this.checked = false;
				} );

				// Show the Facebook register dialog.
				showDialog( facebookRegisterDialog );

				// Track the event.
				trackPath( 'facebookLoginFirstTime' );

			} // End if.

			// Notify all listeners that a login operation has taken place.
			dispatchEvent( 'onLoginChange' );

		} );

	};

	// -------------------- Hides all dialogs and shows the specified one.
	//
	function showDialog( dialogToShow ) {

		// Close all dialogs.
		for ( var i = 0; i < dialogs.length; i++ ) {
			var d = dialogs[ i ];
			d.dialog( 'close' );
		}

		// Open the specified dialog.
		if ( dialogToShow != null ) dialogToShow.dialog( 'open' );

	};

	// -------------------- Shows the message dialog.
	//
	function showMessage( msg ) {

		$( '.message-dialog-text', messageDialog ).html( msg );
		showDialog( messageDialog );

	};

	// -------------------- Dispatches events to the listener objects.
	//
	function dispatchEvent( event ) {

		for ( var i = 0; i < listeners.length; i++ ) {
			var obj = listeners[ i ]
			if ( obj != null ) {
				var func = obj[ event ];
				if ( func ) func.call();
			} // End if.
		} // End for.

	};

	// -------------------- Track using Google Analytics.
	//
	function trackPath( path ) {
		//alert("Track Pageview: "+path);
		pageTracker._trackPageview( '/account/tracking/' + path );

	};


	init();

} )( jQuery );

