        // Create a 5 minute periodic timer for kicking off the scheduled task to register the device with AAD.
            this.deviceRegistrationTaskScheduler = setInterval(
                () => {
                    this.sessionUtilities.enrollmentApis.forceRunDeviceRegistrationScheduledTaskAsync().then(
                        () => {
                            this.sessionUtilities.logInfoEvent("BootstrapStatus: Starting AAD device registration task succeeded");
                        },

                        (e) => {
                            this.sessionUtilities.logErrorEvent("BootstrapStatus: Starting AAD device registration task failed (non-fatal)", e);
                        });
                },
                this.DEVICE_REGISTRATION_INTERVAL_WAIT_TIME_IN_MILLISECONDS);

            let aadRegistrationWaitPromise = new WinJS.Promise(
                // Promise initialization handler
                (completeDispatch, errorDispatch, progressDispatch) => {
                    // Create event handler.
                    this.aadRegistrationListener = (hresult) => {
                        this.sessionUtilities.logInfoEvent(`BootstrapStatus: AAD device registration task completed with hresult ${hresult.target}`);

                        this.aadRegistered = (0 === hresult.target);
                        this.aadRegistrationHresult = hresult;
                        completeDispatch(true);
                    };

                    // Register event handler.
                    this.sessionUtilities.autopilotSubscriptionManager.addEventListener("aadjcompleted", this.aadRegistrationListener.bind(this));
                },

                // Promise cancellation event handler
                () => {
                });

            // Set a max timeout for device registration.  The reason for this timeout is AD connect happens in the
            // background approximately every 30 minutes, and once this occurs, the device registration task (forced 
            // to run every five minutes by deviceRegistrationTaskScheduler) will finally succeed, at which point
            // the device is AAD-registered.
            let aadRegistrationTimeoutPromise = WinJS.Promise.timeout(this.MAX_AAD_REGISTRATION_WAIT_TIME_IN_MILLISECONDS).then(() => {
                this.sessionUtilities.logInfoEvent("AAD registration timed out");
            });

            let aadRegistrationPromises = [
                aadRegistrationTimeoutPromise,
                aadRegistrationWaitPromise
            ];

            // Wait for either the TPM attested state or the timeout.
            return WinJS.Promise.any(aadRegistrationPromises).then(() => {
                if (this.aadRegistrationListener !== null) {
                    this.sessionUtilities.autopilotSubscriptionManager.removeEventListener("aadjcompleted", this.aadRegistrationListener.bind(this));
                }

                aadRegistrationTimeoutPromise.cancel();
                aadRegistrationTimeoutPromise = null;

                // Device is now AAD-registered or timed out trying, and so stop trying to run the background task
                // to AADJ register the device.
                clearInterval(this.deviceRegistrationTaskScheduler);
                this.deviceRegistrationTaskScheduler = null;

                if (this.aadRegistered) {
                    // Re-create the OMADM sync tasks to force user policy sync upon AADJ completing.
                    return this.sessionUtilities.enrollmentApis.recreateEnrollmentTasksAsync();
                } else {
                    if (null === this.aadRegistrationHresult) {
                        // No registration failure, but still not registered.  Default to displaying timeout error ERROR_TIMEOUT.
                        this.aadRegistrationErrorString = this.sessionUtilities.formatNumberAsHexString(this.sessionUtilities.HRESULT_TIMEOUT, 8);
                    } else {
                        this.aadRegistrationErrorString = this.sessionUtilities.formatNumberAsHexString(this.aadRegistrationHresult.target, 8);
                    }
                }

                return;
            }).then(() => {
                return {
                    actionSucceeded: this.aadRegistered,
                    statusMessage: this.aadRegistrationErrorString
                };
            });
        }

        sendResultsToMdmServerAsync() {
            this.sessionUtilities.enrollmentApis.updateServerWithResult(true, this.sessionUtilities.runningInOobe());

            return WinJS.Promise.as({
                actionSucceeded: true,
                statusMessage: null
            });
        }

        prepareMultifactorAuthAsync() {
            this.sessionUtilities.logInfoEvent("BootstrapStatus: Requesting AAD user token");

            return CloudExperienceHostAPI.UtilStaticsCore.requestAADUserTokenAsync().then((result) => {
                this.sessionUtilities.logInfoEvent("BootstrapStatus: AAD user token successfully requested");

                return WinJS.Promise.as({
                    actionSucceeded: true,
                    statusMessage: null
                });
            },
            (e) => {
                this.sessionUtilities.logErrorEvent("BootstrapStatus: AAD user token request failed", e);

                return WinJS.Promise.as({
                    actionSucceeded: false,
                    statusMessage: null
                });
            });
        }

        // Category interface methods

        getId() {
            return "AccountSetupCategory";
        }

        getTitle() {
            return this.resourceStrings["BootstrapPageAccountSetupCategoryTitle"];
        }

        getIconClass() {
            return "icon-users";
        }

        getDisposition() {
            return (!this.sessionUtilities.runningInOobe() ? this.sessionUtilities.CATEGORY_DISPOSITION_VISIBLE : this.sessionUtilities.CATEGORY_DISPOSITION_IGNORED);
        }

        runsInOobe() {
            return false;
        }

        getInitializationPromise() {
            return WinJS.Promise.as(true);
        }

        getSubcategories() {
            return [
                new bootstrapStatusSubcategoryViewModel(
                    this.resourceStrings,
                    this.sessionUtilities,
                    "AccountSetup.WaitingForAadRegistrationSubcategory",
                    this.resourceStrings["BootstrapPageAccountSetupWaitingForAadRegistrationSubcategoryTitle"],
                    false,
                    () => {
                        return this.sessionUtilities.SUBCATEGORY_DISPOSITION_VISIBLE;
                    },
                    (progressCallback) => {
                        return this.waitForAadRegistrationAsync();
                    }
                ),
                new bootstrapStatusSubcategoryViewModel(
                    this.resourceStrings,
                    this.sessionUtilities,
                    "AccountSetup.PrepareMultifactorAuth",
                    "AccountSetup.PrepareMultifactorAuth",
                    false,
                    () => {
                        return this.sessionUtilities.SUBCATEGORY_DISPOSITION_SILENT;
                    },
                    (progressCallback) => {
                        return this.prepareMultifactorAuthAsync();
                    }
                ),
                new bootstrapStatusSubcategoryViewModel(
                    this.resourceStrings,
                    this.sessionUtilities,
                    "AccountSetup.SecurityPoliciesSubcategory",
                    this.resourceStrings["BootstrapPageSecurityPoliciesSubcategoryTitle"],
                    true,
                    () => {
                        return this.sessionUtilities.SUBCATEGORY_DISPOSITION_VISIBLE;
                    },
                    (progressCallback) => {
                        return this.mdmBootstrapSessionUtilities.monitorPoliciesApplicationAsync(progressCallback);
                    }
                ),
                new bootstrapStatusSubcategoryViewModel(
                    this.resourceStrings,
                    this.sessionUtilities,
                    "AccountSetup.CertificatesSubcategory",
                    this.resourceStrings["BootstrapPageCertificatesSubcategoryTitle"],
                    true,
                    () => {
                        return this.sessionUtilities.SUBCATEGORY_DISPOSITION_VISIBLE;
                    },
                    (progressCallback) => {
                        return this.mdmBootstrapSessionUtilities.monitorCertsInstallationAsync(progressCallback);
                    }
                ),
                new bootstrapStatusSubcategoryViewModel(
                    this.resourceStrings,
                    this.sessionUtilities,
                    "AccountSetup.NetworkConnectionsSubcategory",
                    this.resourceStrings["BootstrapPageNetworkConnectionsSubcategoryTitle"],
                    true,
                    () => {
                        return this.sessionUtilities.SUBCATEGORY_DISPOSITION_VISIBLE;
                    },
                    (progressCallback) => {
                        return this.mdmBootstrapSessionUtilities.monitorNetworkProfilesConfigAsync(progressCallback);
                    }
                ),
                new bootstrapStatusSubcategoryViewModel(
                    this.resourceStrings,
                    this.sessionUtilities,
                    "AccountSetup.AppsSubcategory",
                    this.resourceStrings["BootstrapPageAppsSubcategoryTitle"],
                    true,
                    () => {
                        return this.sessionUtilities.SUBCATEGORY_DISPOSITION_VISIBLE;
                    },
                    (progressCallback) => {
                        return this.mdmBootstrapSessionUtilities.monitorAppsInstallAsync(progressCallback);
                    }
                ),
                // This subcategory needs to be parallelized with resource type subcategories which poll for resources being installed by Intune through
                // sync sessions.
                new bootstrapStatusSubcategoryViewModel(
                    this.resourceStrings,
                    this.sessionUtilities,
                    "AccountSetup.InitiateSyncSessions",
                    "AccountSetup.InitiateSyncSessions",
                    true,
                    () => {
                        return this.sessionUtilities.SUBCATEGORY_DISPOSITION_SILENT;
                    },
                    (progressCallback) => {
                        // This is a fire and forget operation because sendResultsToMdmServerAsync sets the IsSyncDone node to actually break out of this wait
                        this.mdmBootstrapSessionUtilities.initiateSyncSessionsAsync(ModernDeployment.Autopilot.Core.SyncSessionExitCondition.accountSetupComplete);

                        return WinJS.Promise.as({
                            actionSucceeded: true,
                            statusMessage: null
                        });
                    }
                ),
                new bootstrapStatusSubcategoryViewModel(
                    this.resourceStrings,
                    this.sessionUtilities,
                    "AccountSetup.SendResultsToMdmServer",
                    "AccountSetup.SendResultsToMdmServer", // Title is mandatory, even for silent subcategories.
                    false,
                    () => {
                        return this.sessionUtilities.SUBCATEGORY_DISPOSITION_SILENT;
                    },
                    (progressCallback) => {
                        return this.sendResultsToMdmServerAsync();
                    }
                )];
        }

        getClickHandler() {
            return (handlerParameters) => {
                switch (handlerParameters.clickedItemId) {
                    case this.sessionUtilities.clickableItemContinueAnywayButton:
                        return new WinJS.Promise(
                            // Promise initialization
                            (completeDispatch, errorDispatch, progressDispatch) => {
                                if (!this.securityPoliciesProvisioningSucceeded ||
                                    !this.certificatesProvisioningSucceeded ||
                                    !this.networkProfilesProvisioningSucceeded ||
                                    !this.appsProvisioningSucceeded) {
                                    try {
                                        this.sessionUtilities.logInfoEvent("One of the provisioning subcategories failed, so kicking off MDM polling tasks.");
                                        this.sessionUtilities.enrollmentApis.startPollingTask();
                                    } catch (e) {
                                        this.sessionUtilities.logErrorEvent("Error starting the MDM polling tasks.", err);
                                    }
                                }

                                // True means that this handler succeeded.
                                completeDispatch(true);
                            },

                            // Cancellation event handler
                            () => {
                            });
                    default:
                        this.sessionUtilities.logErrorEvent("Unexpected click handler item");
                }

                // True means that this handler succeeded.
                return WinJS.Promise.as(true);
            };
        }
    }

    return accountSetupCategoryViewModel;
});
