<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-23T23:14:47.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2019-03-19T03:59:35.5700000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-23T23:14:01.8200000</UpdatedUtcDate>
    <ScriptId>NEWACC</ScriptId>
    <Description>New Account</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountNew
Option Explicit On
Option Strict On

' #################################################################
' New Account HTML Widget
'
' Version: 1.27 (24/09/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.17  31/08/2021  ISS                Updated
'    1.18  31/01/2022  ISS      J028189   Replaced Obsolete Promotion functions
'          15/02/2022  ISS      J028247   Updated reference to new Promotion functions
'          17/03/2022  ISS      J028411   Improved defaulting of Promotion Financials
'          06/04/2022  ISS      J027963   Some Permission Keys removed
'          06/05/2022  ISS      J028607   Purpose, Source, Region and Policy Type fields no longer ignored if mandatory and hidden behind "Advanced"
'          25/05/2022  ISS      J028776   Support Duplicating an Account
'          30/05/2022  ISS      J028837   Supply Branch Id to Security Statement Item form
'          07/06/2022  ISS      J028452   User Defined fields not retaining indexes
'    1.19  07/07/2022  ISS      J029067   Product Type now supplied to Security Statement Item HTML Widget to limit available Security Types
'          18/07/2022  ISS      J028981   Interest Rate Increase &amp; Decreate instructions now correctly default from Floating Rate Loan Account Types
'          08/08/2022  ISS      J029029   Improvements to how UserData is written and retrieved
'          02/11/2022  ISS      J029487   Financial page; Overriding Payments and Payment Schedule have been implemented
'          04/11/2022  ISS      J029871   Improved Default Name and Default Description handling
'    1.20  17/01/2023  ISS      J030289   Support printing Quotation
'          27/01/2023  ISS      J030146   Updated Initialise Parameters for AccountIncomingPaymentDetails &amp; AccountOutgoingPaymentDetails controls
'          09/03/2023  ISS      J027336   Updating Payment Type does not clear bank account details
'          14/03/2023  ISS      J030665   Maturity Instructions, Payment Method now mandatory
'    1.21  11/04/2023  ISS      J030384   Client Id no longer duplicated if creating from a Quotation.
'          19/04/2023  ISS      J030460   HTML Widget now supports Accounts created from a Refinance.
'          01/05/2023  ISS      J030930   "Add all Selected Clients" was not adding correct Clients.
'    1.22  11/07/2023  ISS      J031511   Outgoing Payment Method is now optional for non-Deposit Product Types
'    1.23  21/11/2023  ISS      J032275   Added defaulting of the Signatory, Privacy, Mail and Security Account Client options
'    1.24  21/03/2024  ISS      J032928   Added support for Zepto PayTo (Australia)
'    1.25  07/05/2024  ISS      J032576   Changed Wording to use finBL.Settings.SecurityStmtInsuranceBrokerTerminology
'          16/05/2024  ISS      J033472   Added "Quote Ready to be Opened" and "Quote Notes"  
'          22/05/2024  ISS      J033494   Payment Method defaults are applied when selected, e.g. Default Reference.
'    1.26  14/06/2024  ISS      J033557   Changed chkQuote to respect the Account Type setting "Default status as 'Quote'?"
'    1.27  24/09/2024  ISS      J033086   Disbursement page is now validated
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountNew"

' Common Parameters
Private mAccountId As String
Private mAccountTypeId As String
Private mClientsToAdd As String
Private mDuplicateAccountId As String
Private mProductTypeId As String
Private mRefinancedAccountId As String
Private mQuoteMode As Boolean
Private mStdTransWidgetId As String

' Objects
Private mCombinedParameters As ISKeyValueList
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList

' Other
Private mHostingContext As isefinHtmlWidgetHostingContext

Public Function Main(eventId As String,
                     parametersJson As String,
                     startUpParametersJson As String,
                     hostingContext As isefinHtmlWidgetHostingContext,
                     requestInfo As finScriptRequestInfo,
                     ByRef returnValue As String) As Boolean

  ' Assume Success
  Main = True
  
  ' Initialise
  mHostingContext = hostingContext

  ' Get Parameters
  mParameters = finBL.CreateKeyValueList()
  mParameters.FromSimpleJsonString(parametersJson)
  mStartupParameters = finBL.CreateKeyValueList()
  mStartupParameters.FromSimpleJsonString(startUpParametersJson)

  ' Get Combined Parameters (Startup Parameters updated with event Parameters)
  mCombinedParameters = mStartupParameters.Clone()
  mCombinedParameters.UpdateFromKeyValueList(mParameters, True)

  ' Get Common Parameters
  With mCombinedParameters
    mAccountId = .GetString("AccountId")
    mAccountTypeId = .GetString("AccountType")
    mClientsToAdd = .GetString("ClientsToAdd")
    mDuplicateAccountId = .GetString("DuplicateAccountId")
    mProductTypeId = .GetString("ProductType")
    mRefinancedAccountId = .GetString("RefinancedAccountId")
    mQuoteMode = .GetBoolean("QuoteMode")
    mStdTransWidgetId = .GetString("StdTransWidgetId")
  End With

  ' Update Parameters
  If Len(mRefinancedAccountId) &lt;&gt; 0 Then
    mAccountId = mRefinancedAccountId
  End If
  
  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return initial HTML content (excluding html and body tags)
      returnValue = ScriptInfo.TemplateText

    Case "Calculate"
      ' Calculate
      Main = Calculate(parametersJson, returnValue)

    Case "ClientSearch"
      ' Client Search
      Main = ClientSearch(returnValue)

    Case "CreateDefaultDisbursements"
      ' Create Default Disbursements
      Main = CreateDefaultDisbursements(parametersJson, returnValue)

    Case "DeleteRefinanceAccount"
      ' Delete Refinance Account
      Main = DeleteRefinanceAccount()
      
    Case "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, requestInfo, returnValue)

    Case "GetAccountSchedule"
      ' Get Account Schedule
      Main = GetAccountSchedule(parametersJson, returnValue)

    Case "GetAccountAndProductTypes"
      ' Get Account and Product Types
      Main = GetAccountAndProductTypes(returnValue)

    Case "GetClientDetails"
      ' Get Client Details
      Main = GetClientDetails(returnValue)

    Case "GetClientPreview"
      ' Get Client Preview
      Main = GetClientPreview(returnValue)

    Case "GetDisbursementsRefreshed"
      ' Get Refreshed Disbursements
      Main = GetDisbursementsRefreshed(parametersJson, returnValue)

    Case "GetNextStatementDate"
      ' Get Next Statement Date
      Main = GetNextStatementDate(returnValue)

    Case "GetSecurityItemsRefreshed"
      ' Get Refreshed Security Items
      Main = GetSecurityItemsRefreshed(parametersJson, returnValue)

    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)

    Case "GetPromotions"
      ' Get Promotions
      Main = GetPromotions(parametersJson, returnValue)

    Case "PrintContract"
      ' Print Contract
      Main = PrintContract(returnValue)
      
    Case "PrintQuotation"
      ' Print Quotation
      Main = PrintQuotation(parametersJson, returnValue)

    Case "OverridingPaymentsHandling"
      ' Create Blank Regular Payments
      Main = OverridingPaymentsHandling(returnValue)
      
    Case "WizardRefresh"
      ' Get details required for refreshing a wizard page
      Main = WizardRefresh(parametersJson, returnValue)

    Case "WizardValidate"
      ' Validate wizard page
      Main = WizardValidate(parametersJson, returnValue)

    Case Else
      finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
      Main = False
  End Select

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Commit changes.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim CalculationFailed As Boolean
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetAccountDetails(parametersJson, AccountDetails)

  ' Create Account object (this performs a calculation)
  If Success Then
    Success = CreateAccount(AccountDetails, Account, CalculationFailed) AndAlso Not CalculationFailed
  End If

  ' Save
  If Success Then
    ' Update
    Account.AccountId = AccountDetails.NewAccountId

    ' Validate
    If AccountDetails.AccountPk &lt;&gt; 0 Then
      If AccountDetails.AccountTimestamp &lt;&gt; Account.Timestamp Then
        Success = False
        finBL.Error.ErrorBegin("This record has been updated by another User.")
      End If
    End If

    ' Save
    If Success Then
      Success = Account.Save()
    End If
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(Account.AccountId), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Calculate financials.
''' &lt;/summary&gt;
Private Function Calculate(parametersJson As String,
                           ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim AccountDetails As AccountDetails
  Dim CalculationFailed As Boolean
  Dim Html As String
  Dim OwnerClientIds As ISList
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  OwnerClientIds = New ISList()

  ' Parse Parameters
  Success = GetAccountDetails(parametersJson, AccountDetails)
  
  ' Create Account object (this performs a calculation)
  If Success Then
    Success = CreateAccount(AccountDetails, Account, CalculationFailed)
  End If

  ' Track Owner Clients
  If Success Then
    For Each AccountClient In Account.Clients
      If AccountClient.IsOwner Then OwnerClientIds.Add(AccountClient.ClientId)
    Next
  End If

  ' Get HTML Summary
  If Success
    If CalculationFailed Then
      Html = finBL.GetHtmlErrorMessage(finBL.Error.Message(True, True))
    Else
      Html = finBL.SummaryPageFunctions.AccountFinancialSummary(False, Account, -1, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
    End If
  End If

  ' Finalise
  If Success Then
    AccountDetails = New AccountDetails(finBL, Account)
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New CalculationDetails(AccountDetails, Html, OwnerClientIds.ToCsvString()), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account and Product Types.
''' &lt;/summary&gt;
Public Function GetAccountAndProductTypes(ByRef returnValue As String) As Boolean

  Dim AccountTypes As List(Of AccountTypeInfo)
  Dim BranchId As String
  Dim ProductTypes As List(Of ProductTypeInfo)
  Dim Success As Boolean
  Dim Data As Object

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    BranchId = .GetString("BranchId")
  End With

  ' Get Values
  GetAccountAndProductTypesInternal(BranchId, AccountTypes, ProductTypes)

  ' Add to Object
  Data = New With {
    .AccountTypes = AccountTypes,
    .ProductTypes = ProductTypes
  }

  ' Serialise
  Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)

  Return Success

End Function

Public Sub GetAccountAndProductTypesInternal(branchId As String,
                                       ByRef accountTypes As List(Of AccountTypeInfo),
                                       ByRef productTypes As List(Of ProductTypeInfo))

  Dim AccountType As finAccountTypeRO
  Dim AccountClassList As List(Of isefinAccountClass)
  Dim Found As Boolean
  Dim ProductType As finProductTypeRO
  Dim ProductTypeTemp As ProductTypeInfo

  ' Initialise
  accountTypes = New List(Of AccountTypeInfo)
  productTypes = New List(Of ProductTypeInfo)

  ' Product Types List
  AccountClassList = New List(Of isefinAccountClass)
  If finBL.Settings.AddOns.DepositAccount Then AccountClassList.Add(isefinAccountClass.Deposit)
  If finBL.Settings.AddOns.Disbursements AndAlso (Not mQuoteMode) Then AccountClassList.Add(isefinAccountClass.Disbursement)
  If finBL.Settings.AddOns.LoanFRAccount Then AccountClassList.Add(isefinAccountClass.LoanFR)
  If finBL.Settings.AddOns.LoanFTAccount Then AccountClassList.Add(isefinAccountClass.LoanFT)
  If finBL.Settings.AddOns.LoanRCAccount AndAlso (Not mQuoteMode) Then AccountClassList.Add(isefinAccountClass.LoanRC)

  For Each ProductType In finBL.ProductTypes
    If Len(mProductTypeId) = 0 OrElse StrComp(ProductType.ProductTypeId, mProductTypeId, CompareMethod.Text) = 0 Then
      If finBL.AccountTypes.GetAvailableAccountTypes(ProductType.ProductTypeId, True, AccountClassList, branchId).Count = 0 Then
        ' No Account Types
      Else
        productTypes.Add(New ProductTypeInfo(finBL, ProductType, mQuoteMode))
      End If
    End If
  Next

  ' Account Type
  ' NOTE: Ensure that only Account Types linked to the above Product Types are included
  For Each AccountType In finBL.AccountTypes
    If AccountType.Active Then
      Found = False
      For Each ProductTypeTemp In productTypes
        If ProductTypeTemp.ProductTypeId = AccountType.ProductTypeId Then
          Found = True
          Exit For
        End If
      Next

      If Found Then
        If mQuoteMode AndAlso (AccountType.AccountClass = isefinAccountClass.Disbursement OrElse AccountType.AccountClass = isefinAccountClass.LoanRC) Then
          ' Do not include Disbursement or Revolving Credit Accounts in 'Quote' mode
        ElseIf finBL.AccountTypeFunctions.IsAccountTypeAvailable(AccountType.AccountTypeId, branchId, True) Then
          accountTypes.Add(New AccountTypeInfo(finBL, AccountType))
        End If
      End If
    End If
  Next

End Sub

''' &lt;summary&gt;
'''  Get Account Details.
''' &lt;/summary&gt;
Private Function GetAccountDetails(parametersJson As String,
                                   ByRef accountDetails As AccountDetails) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  accountDetails = Nothing

  ' Parse Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(AccountDetails), obj) Then
    accountDetails = DirectCast(obj, AccountDetails)
  Else
    Success = False
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account Schedule.
''' &lt;/summary&gt;
Public Function GetAccountSchedule(parametersJson As String,
                                   ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim CalculationFailed As Boolean
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetAccountDetails(parametersJson, AccountDetails)

  ' Create Account object (this performs a calculation)
  If Success Then
    Success = CreateAccount(AccountDetails, Account, CalculationFailed) AndAlso Not CalculationFailed
  End If

  ' Get Schedule
  If Success Then
    response = Account.Calculation.Schedule.ToHtmlWidgetJsonString("Date,ScheduleType,ElementId,Reference,Value,Balance,Notes")
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create Default Disbursements.
''' &lt;/summary&gt;
Public Function CreateDefaultDisbursements(parametersJson As String,
                                          ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim CalculationFailed As Boolean
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetAccountDetails(parametersJson, AccountDetails)

  ' Create Account object
  If Success Then
    Success = CreateAccount(AccountDetails, Account, CalculationFailed)
  End If

  ' Create Default Disbursements
  If Success Then
    Success = Account.Disbursements.CreateDefaultDisbursements()
  End If

  ' Finalise
  If Success Then
    AccountDetails = New AccountDetails(finBL, Account)
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(AccountDetails.Disbursements, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Delete Refinance Account.
''' &lt;/summary&gt;
Private Function DeleteRefinanceAccount() As Boolean
  
  Dim Account As finAccount
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  Account = finBL.CreateAccount()
  
  ' Load &amp; Delete
  If Account.Load(mAccountId) Then
    Success = Account.Delete()
  Else 
    Success = False
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get Refreshed Disbursements (to update Descriptions etc after edit).
''' &lt;/summary&gt;
Public Function GetDisbursementsRefreshed(parametersJson As String,
                                          ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim AccountDisbursement As finAccountDisbursement
  Dim CalculationFailed As Boolean
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetAccountDetails(parametersJson, AccountDetails)

  ' Create Account object (this updates Disbursements)
  If Success Then
    Success = CreateAccount(AccountDetails, Account, CalculationFailed)
  End If

  ' Update Disbursements?
  If Success Then
    If AccountDetails.MatchDisbursementDateToOpening Then
      For Each AccountDisbursement In Account.Disbursements
        If AccountDisbursement.Date &lt; Account.DateOpened Then
          AccountDisbursement.Date = Account.DateOpened
        End If
      Next 
    End If
  End If
  
  ' Finalise
  If Success Then
    AccountDetails = New AccountDetails(finBL, Account)
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(AccountDetails.Disbursements, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Refreshed Security Items (to update Descriptions etc after edit).
''' &lt;/summary&gt;
Public Function GetSecurityItemsRefreshed(parametersJson As String,
                                          ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim CalculationFailed As Boolean
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetAccountDetails(parametersJson, AccountDetails)

  ' Create Account object (this updates Security Items)
  If Success Then
    Success = CreateAccount(AccountDetails, Account, CalculationFailed)
  End If

  ' Finalise
  If Success Then
    AccountDetails = New AccountDetails(finBL, Account)
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(AccountDetails.SecurityItems, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Client Search.
''' &lt;/summary&gt;
Private Function ClientSearch(ByRef returnValue As String) As Boolean

  Dim Query As String
  Dim QuickSearch As finQuickSearch
  Dim QuickSearchResult As finQuickSearchResult
  Dim SearchResults As List(Of ClientSearchResult)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    Query = .GetString("Query")
  End With

  ' Validate
  If Len(Query) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("No search query specified.")
  End If

  ' Search
  If Success Then
    QuickSearch = finBL.CreateQuickSearch()
    With QuickSearch
      .ClearAllIncludes()
      .IncludeClients = True
      .IncludeInactive = False
      .QueryText = Query

      ' Search
      Success = .ExecuteSearch()
    End With
  End If

    ' Finalise
  If Success Then
    SearchResults = New List(Of ClientSearchResult)
    For Each QuickSearchResult In QuickSearch.SearchResults
      SearchResults.Add(New ClientSearchResult(finBL, QuickSearchResult))
    Next

    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(SearchResults, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create a finAccount object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccount(accountDetails As AccountDetails,
                               ByRef account As finAccount,
                               ByRef calculationFailed As Boolean) As Boolean

  Dim AccountClient As finAccountClient
  Dim AccountClients As List (Of Object)
  Dim AccountClientDetails As AccountClientDetails
  Dim AccountDisbursement As finAccountDisbursement
  Dim DisbursementDetails As DisbursementDetails
  Dim Disbursements As List(Of Object)
  Dim i As Integer
  Dim InterestInstructionDownText As String
  Dim InterestInstructionUpText As String
  Dim SecurityItem As finSecurityStmtItemBase
  Dim SecurityItems As List(Of Object)
  Dim SecurityItemDetails As SecurityItemDetails
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  account = finBL.CreateAccount()
  calculationFailed = False

  ' Load Existing Account?
  If Len(mAccountId) &lt;&gt; 0 Then
    If account.Load(mAccountId) Then
      If account.Status &lt;&gt; isefinAccountStatus.Quote Then
        Success = False
        finBL.Error.ErrorBeginFormat("Existing Account '{0}' is not a 'Quote'.", account.AccountId)
      End If
    Else
      Success = False
    End If
  ElseIf Len(mDuplicateAccountId) &lt;&gt; 0 Then
    If account.Load(mDuplicateAccountId) Then
      Success = account.Duplicate()
    Else
      Success = False
    End If
  End If

  ' Update Account from supplied Account Details
  If Success AndAlso accountDetails IsNot Nothing Then
    With account
      ' General
      .AccountManagerUserId = accountDetails.AccountManagerUserId
      .AccountTypeId = accountDetails.AccountTypeId
      .AccountTypePromotionId = accountDetails.AccountTypePromotionId
      .BranchId = accountDetails.BranchId
      If .BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Incoming) Then
        account.BankingDetails(isefinAccountBankingDetailsType.Incoming).BankingDetails.FromHtmlWidgetJsonString(accountDetails.BankingDetailsIncomingJson)
      End If
      If .BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Outgoing) Then
        account.BankingDetails(isefinAccountBankingDetailsType.Outgoing).BankingDetails.FromHtmlWidgetJsonString(accountDetails.BankingDetailsOutgoingJson)
      End If
      If .BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Maturity) Then
        account.BankingDetails(isefinAccountBankingDetailsType.Maturity).BankingDetails.FromHtmlWidgetJsonString(accountDetails.BankingDetailsMaturityJson)
      End If
      .BrokerExternalPartyId = accountDetails.BrokerId
      .BrokerExternalPartyEmployeeClientEmploymentId = accountDetails.BrokerEmployeeId
      .DateAccepted = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(accountDetails.DateAccepted)
      .DateQuoted = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(accountDetails.DateQuoted)
      .DateReview = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(accountDetails.DateReview)
      .DateSigned = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(accountDetails.DateSigned)
      .DealerExternalPartyId = accountDetails.DealerId
      .DealerExternalPartyEmployeeClientEmploymentId = accountDetails.DealerEmployeeId
      .DepartmentId = accountDetails.DepartmentId
      .Description = accountDetails.Description
      .ExternalId = accountDetails.ExternalId
      .InsuranceInsurerExternalPartyId = accountDetails.InsurerId
      .InsurancePolicyNumber = accountDetails.InsurancePolicyNumber
      .InsurancePolicyType = accountDetails.InsurancePolicyType
      .InterestTransferToAccountId = accountDetails.InterestTransferToAccountId
      .MaturityInstructionText = accountDetails.MaturityInstructionText
      .MaturityValue = accountDetails.MaturityValue
      .MaturityAccountTypeId = accountDetails.MaturityAccountTypeId
      .MaturityAccountId = accountDetails.MaturityAccountId
      .MaturityPaymentTypeText = accountDetails.MaturityPaymentTypeText
      .MaturityTransferToAccountId = accountDetails.MaturityTransferToAccountId
      .Name = accountDetails.Name
      .Notes = accountDetails.Notes
      .PoolId = accountDetails.PoolId
      .Purpose = accountDetails.Purpose
      .QuoteNote = accountDetails.QuoteNotes
      If accountDetails.QuoteReady Then
        .DateQuoteReady = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()
      Else
        .DateQuoteReady = Nothing
      End If
      .Region = accountDetails.Region
      .Source = accountDetails.Source

      ' User Defined
      If .AccountType IsNot Nothing AndAlso .AccountType.UserDefinedShowInNewAccountWizard AndAlso .AccountType.UserDefinedParameterSetPk &lt;&gt; 0 Then
        If Left(accountDetails.UserDataJson, 1) = "[" Then
          .UserData.FromHtmlWidgetParametersJsonString(accountDetails.UserDataJson)
        Else
          .UserData.FromSimpleJsonString(accountDetails.UserDataJson)
        End If
      End If

      ' Clients (retain existing items by matching Pk)
      AccountClients = New List (Of Object)
      For Each AccountClientDetails In accountDetails.Clients
        With AccountClientDetails
          ' Locate Account Client/ Create new Account Client
          If .Pk = 0 Then
            AccountClient = account.Clients.CreateAccountClient()
          Else
            AccountClient = account.Clients.ItemByPk(.Pk)
          End If

          If AccountClient IsNot Nothing Then
            ' Update Account Client details
            If AccountClient.IsNew Then
              ' New record
              AccountClient.AccountRoleIdSet(.AccountRoleId)
              AccountClient.ClientIdSet(.ClientId)
              account.Clients.Add(AccountClient)
            Else
              ' Existing record
              AccountClient.AccountRoleId = .AccountRoleId
            End If

            ' Tweak Account Role (e.g., if switching between Loans and Deposits, Account Role may be invalid)
            If account.ProductType IsNot Nothing AndAlso Not account.ProductType.IsAccountRoleValid(AccountClient.AccountRoleId) Then
              If account.ProductType.DefaultAccountRolePk = 0 Then
                ' Nothing we can do
              Else
                ' Update Account Role
                AccountClient.AccountRoleId = account.ProductType.DefaultAccountRoleId
              End If
            End If

            AccountClient.RoleJoint = .RoleJoint
            AccountClient.AccountSignatory = .AccountSignatory
            AccountClient.PrivacyConsent = .PrivacyConsent
            AccountClient.SendDocuments = .SendDocuments
            AccountClient.SecurityParty = .SecurityParty
            
            ' Add to List
            AccountClients.Add(AccountClient)
          End If
        End With
      Next

      ' Remove deleted
      For i = account.Clients.Count - 1 To 0 Step -1
        AccountClient = account.Clients(i)
        If Not AccountClients.Contains(AccountClient) Then
          account.Clients.RemoveAt(i)
        End If
      Next

      ' Order correctly
      account.Clients.Rearrange(AccountClients)
      
      ' Quotation may simply supply a Client Id
      If mQuoteMode AndAlso Len(accountDetails.QuoteClientId) &lt;&gt; 0 AndAlso Not ClientExists(accountDetails.QuoteClientId, account.Clients) Then
        AccountClient = Account.Clients.CreateAccountClient()
        'AccountClient.AccountRoleIdSet(.AccountRoleId)
        AccountClient.ClientIdSet(accountDetails.QuoteClientId)
        account.Clients.Add(AccountClient)
      End If

      ' Disbursements (retain existing items by matching Pk)
      If finBL.Settings.AddOns.Disbursements AndAlso .AccountClass &lt;&gt; isefinAccountClass.Disbursement AndAlso account.AccountType.DisbursementsShowInNewAccountWizard AndAlso finBL.CurrentUser.Permissions.Allow("Account.FormNew.Page.Disbursements") Then
        Disbursements = New List(Of Object)
        For Each DisbursementDetails In accountDetails.Disbursements
          With DisbursementDetails
            ' Locate Disbursement/ Create new Disbursement
            If .Pk = 0 Then
              ' Create Disbursement
              AccountDisbursement = account.Disbursements.CreateAccountDisbursement()
              account.Disbursements.Add(AccountDisbursement)
            Else
              AccountDisbursement = account.Disbursements.ItemByPk(.Pk)
            End If

            ' Update details
            AccountDisbursement.FromHtmlWidgetJsonString(.Json)

            ' Add to List
            Disbursements.Add(AccountDisbursement)
          End With
        Next

        ' Remove deleted
        For i = account.Disbursements.Count - 1 To 0 Step -1
          AccountDisbursement = account.Disbursements(i)
          If Not Disbursements.Contains(AccountDisbursement) Then
            account.Disbursements.RemoveAt(i)
          End If
        Next

        ' Order correctly
        account.Disbursements.Rearrange(Disbursements)
      End If

      ' Security Items (retain existing items by matching Pk)
      If finBL.Settings.AddOns.SecurityRegister Then
        SecurityItems = New List(Of Object)
        For Each SecurityItemDetails In accountDetails.SecurityItems
          With SecurityItemDetails
            ' Locate Security Item/ Create new Security Item
            SecurityItem = account.SecurityStmt.SecurityItems.CreateSecurityStmtItem(finBL.SecurityTypes.ItemByIndex(0).SecurityTypeId)
            SecurityItem.FromHtmlWidgetJsonString(.Json)

            If .Pk = 0 Then
              ' Create the correct object type
              SecurityItem = account.SecurityStmt.SecurityItems.CreateSecurityStmtItem(SecurityItem.SecurityTypeId)
              account.SecurityStmt.SecurityItems.Add(SecurityItem)
            Else
              SecurityItem = account.SecurityStmt.SecurityItems.ItemByPk(.Pk)
            End If

            ' Update details
            SecurityItem.FromHtmlWidgetJsonString(.Json)

            ' Set Descripiton
            ' NOTE: This is set when saving the Security Statement Item but we want to set it for new items so it appears in the grid
            If .Pk = 0 OrElse Len(.Description) = 0 Then
              SecurityItem.Description = SecurityItem.CreateDescription()
            End If

            ' Add to List
            SecurityItems.Add(SecurityItem)
          End With
        Next

        ' Remove deleted
        For i = account.SecurityStmt.SecurityItems.Count - 1 To 0 Step -1
          SecurityItem = account.SecurityStmt.SecurityItems(i)
          If Not SecurityItems.Contains(SecurityItem) Then
            account.SecurityStmt.SecurityItems.RemoveAt(i)
          End If
        Next

        ' Order correctly
        account.SecurityStmt.SecurityItems.Rearrange(SecurityItems)
      End If

      ' Calculation
      If Success Then
        ' Deserialise
        .Calculation.FromHtmlWidgetJsonString(accountDetails.AccountCalcJson)

        ' Account Type hasn't changed but the calculation above may have reset certain details so restore them (J024493)
        If accountDetails.AccountTypeId = accountDetails.AccountTypeIdOriginal Then
          .MaturityInstructionText = accountDetails.MaturityInstructionText
          .MaturityAccountTypeId = accountDetails.MaturityAccountTypeId

          With .Calculation
            InterestInstructionDownText = .InterestInstructionDownText
            InterestInstructionUpText = .InterestInstructionUpText
          End With
        End If

        ' Action
        Select Case accountDetails.Action
          Case "Reset"
            ' Reset All
            If account.Calculation.ResetToDefaults() Then
              InterestInstructionDownText = ""
              InterestInstructionUpText = ""
            End If
            account.Calculation.Payments.Clear()

          Case "StdTransReset"
            ' Reset Transactions to Defaults
            account.Calculation.LoadAccountTypeStdTransactions()
        End Select

        ' Calculate
        If account.AccountClass = isefinAccountClass.Disbursement Then
          ' Disbursement Accounts do not support Calculating
        Else
          If .Calculation.PaymentRegularOverride = 0 Then
            If Not .Calculation.Calculate() Then
              ' Ignore errors
              calculationFailed = True
            End If
          Else
            If Not .Calculation.CalculateTerm(.Calculation.PaymentRegularOverride) Then
              ' Ignore errors
              calculationFailed = True
            End If
          End If

          ' Restore properties that may have been reset during the Calculation
          With .Calculation
            If Len(InterestInstructionDownText) &lt;&gt; 0 Then .InterestInstructionDownText = InterestInstructionDownText
            If Len(InterestInstructionUpText) &lt;&gt; 0 Then .InterestInstructionUpText = InterestInstructionUpText
          End With
          If .AccountType.OptionAllowLedger Then
            .Ledger = accountDetails.Ledger
          End If
        End If
      End If
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Indicates if a Client already exists on the Account.
''' &lt;/summary&gt;
Private Function ClientExists(clientId As String,
                              accountClients As finAccountClients) As Boolean
  
  Dim AccountClient As finAccountClient
  
  ' Find Client
  If Len(clientId) &lt;&gt; 0 Then
    For Each AccountClient In accountClients
      If StrComp(AccountClient.ClientId, clientId, CompareMethod.Text) = 0 Then
        Return True
      End If
    Next 
  End If
  
  Return False
                              
End Function

''' &lt;summary&gt;
'''  Get Initialisation Information required for this wizard.
''' &lt;/summary&gt;
Public Function GetInitialisationInfo(ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim AccountClientDetails As AccountClientDetails
  Dim AccountRole As finAccountRoleRO
  Dim CalculationFailed As Boolean
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim List As ISList
  Dim s As String
  Dim strTemp As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If Len(mStdTransWidgetId) &lt;&gt; 0 AndAlso Not finBL.Scripts.Exists(mStdTransWidgetId) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Edit Standard Transaction HTML Widget '{0}' not found.", mStdTransWidgetId)
  ElseIf Len(mStdTransWidgetId) &lt;&gt; 0 AndAlso finBL.Scripts(mStdTransWidgetId).ScriptType &lt;&gt; isefinScriptType.HtmlWidget Then
    Success = False
    finBL.Error.ErrorBeginFormat("Edit Standard Transaction Script '{0}' must be of Type 'HTML Widget'.", mStdTransWidgetId)
  ElseIf Len(mProductTypeId) &lt;&gt; 0 AndAlso Not finBL.ProductTypes.Exists(mProductTypeId) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Product Type '{0}' not found.", mProductTypeId)
  ElseIf Len(mAccountTypeId) &lt;&gt; 0 AndAlso Not finBL.AccountTypes.Exists(mAccountTypeId) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Account Type '{0}' not found.", mAccountTypeId)
  End If

  ' Create Account object
  If Success Then
    Success = CreateAccount(Nothing, Account, CalculationFailed)
  End If
  
  ' Add Clients specified at startup
  If Success Then
    If Len(mClientsToAdd) &lt;&gt; 0 Then
      List = New ISList(mClientsToAdd)
      For Each s In List
        If Not Account.Clients.ExistsClientId(s) Then
          AccountClient = Account.Clients.CreateAccountClient()
          With AccountClient
            .ClientIdSet(s)
          End With
          Account.Clients.Add(AccountClient)
        End If
      Next
    End If
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Quotation Client
      If mQuoteMode AndAlso Account.Clients.Count &lt;&gt; 0 Then
        .QuotationClientId = Account.Clients(0).ClientId
      End If
      
      ' Account
      ' NOTE: Must build Product Types List above first, just in case mProductTypeId gets defaulted
      .Account = New AccountDetails(finBL, Account)

      ' Refinance?
      .Refinance = (Account.CreationMethod = isefinAccountCreationMethod.Refinanced)
      If .Refinance Then
        .RefinanceCreatedFromAccountId = Account.CreatedFromAccountId
        
        If Not Account.SecurityStmt.IsNew Then
          .SecurityStmtMessage = String.Format("Changes will be made to existing Security Statement '{0}'", Account.SecurityStmt.SecurityStmtId)
        End If
      End If
      
      ' Get Account and Product Types
      GetAccountAndProductTypesInternal(Account.BranchId, .AccountTypes, .ProductTypes)

      ' Default Product Type if unspecified
      If Not Account.IsNew OrElse Len(mDuplicateAccountId) &lt;&gt; 0 Then
        ' Existing Account
        mProductTypeId = Account.ProductTypeId
      ElseIf Len(mProductTypeId) = 0 AndAlso Len(mAccountTypeId) = 0 Then
        If .ProductTypes.Count = 1 Then
          ' Default Product Type since there is only one
          .Account.ProductTypeId = .ProductTypes(0).ProductTypeId
        Else
          ' From User Preferences
          .Account.ProductTypeId = finBL.SettingsUser.DefaultAccountProductTypeId
        End If

        ' Default Account Type
        If Len(.Account.ProductTypeId) &lt;&gt; 0 Then
          .Account.AccountTypeId = finBL.ProductTypes(.Account.ProductTypeId).DefaultAccountTypeId
        End If
      Else
        ' From Supplied details
        .Account.ProductTypeId = mProductTypeId
        .Account.AccountTypeId = mAccountTypeId
        If Len(mProductTypeId) = 0 AndAlso finBL.AccountTypes.Exists(mAccountTypeId) Then
          .Account.ProductTypeId = finBL.AccountTypes(mAccountTypeId).ProductTypeId
        End If
      End If

      ' Lists
      '.CountriesList = finBL.Addressing.GetCountriesList().ToCsvString()

      ' Information Lists
      .PolicyTypeAllowBlank = True
      .PolicyTypeInformationListId = "InsurancePolicyTypes"
      .RegionAllowBlank = True
      .RegionInformationListId = "AccountRegion"

      If finBL.InformationLists.Exists(.PolicyTypeInformationListId) Then
        .PolicyTypeAllowBlank = (Not finBL.InformationLists(.PolicyTypeInformationListId).Mandatory)
      End If
      If finBL.InformationLists.Exists(.RegionInformationListId) Then
        .RegionAllowBlank = (Not finBL.InformationLists(.RegionInformationListId).Mandatory)
      End If

      ' Ensure default Account Type is still valid
      If Not .AccountTypeExists(.Account.AccountTypeId) Then
        If .AccountTypes.Count = 0 Then
          .Account.AccountTypeId = ""
        Else
          .Account.AccountTypeId = .AccountTypes(0).AccountTypeId
        End If
      End If

      ' Set Account Role for Clients specified at startup
      If Success Then
        If Len(mClientsToAdd) &lt;&gt; 0 AndAlso Len(.Account.AccountTypeId) &lt;&gt; 0 Then
          For Each AccountClientDetails In .Account.Clients
            AccountClientDetails.AccountRoleId = finBL.AccountTypes(.Account.AccountTypeId).ProductType.DefaultAccountRoleId
          Next
        End If
      End If

      ' Global Collections
      For Each AccountRole In finBL.AccountRoles
        If AccountRole.Active Then
          .AccountRoles.Add(New AccountRoleInfo(finBL, AccountRole))
        End If
      Next

      ' Permissions
      If Account.IsNew Then
        .CanUpdateAccountId = finBL.CurrentUser.Permissions.Allow("Account.AllowNonAutoSequenceCode")
      Else
        .CanUpdateAccountId = finBL.CurrentUser.Permissions.Allow("Account.UpdateCode")
      End If
      .CanUpdateStatusQuoteToOpen = Account.CanUpdateStatusQuoteToOpen() AndAlso Not finBL.Settings.AddOns.IsLimitedFunctionality()

      ' Advanced Sections
      .ShowBranch = mCombinedParameters.GetString("ShowBranch"): If Len(.ShowBranch) = 0 Then .ShowBranch = "Advanced"
      If Not finBL.Settings.AddOns.Branch Then
        .ShowBranch = "False"
      ElseIf Len(Account.BranchId) = 0 Then
         .ShowBranch = "True"
      End If
      .ShowDealer = mCombinedParameters.GetString("ShowDealer"): If Len(.ShowDealer) = 0 Then .ShowDealer = "Advanced"
      If Not finBL.Settings.AddOns.ExternalPartyDealers Then
        .ShowDealer = "False"
      ElseIf Len(Account.DealerExternalPartyId) = 0 Then
         .ShowDealer = "True"
      End If
      .ShowBroker = mCombinedParameters.GetString("ShowBroker"): If Len(.ShowBroker) = 0 Then .ShowBroker = "Advanced"
      If Not finBL.Settings.AddOns.ExternalPartyBrokers Then
        .ShowBroker = "False"
      End If
      .ShowAccountManager = mCombinedParameters.GetString("ShowAccountManager"): If Len(.ShowAccountManager) = 0 Then .ShowAccountManager = "Advanced"
      If Len(Account.AccountManagerUserId) = 0 Then
         .ShowAccountManager = "True"
      End If
      .ShowPool = mCombinedParameters.GetString("ShowPool"): If Len(.ShowBroker) = 0 Then .ShowPool = "Advanced"
      If Not finBL.Settings.AddOns.Pool Then
        .ShowPool = "False"
      End If
      .PageGeneralHasAdvanced = (.ShowBranch = "Advanced" OrElse .ShowDealer = "Advanced" OrElse .ShowBroker = "Advanced" OrElse .ShowAccountManager = "Advanced" OrElse .ShowPool = "Advanced")

      .ShowClientAdditional = mCombinedParameters.GetString("ShowClientAdditional"): If Len(.ShowClientAdditional) = 0 Then .ShowClientAdditional = "Advanced"
      .PageClientsHasAdvanced = (.ShowClientAdditional = "Advanced")

      .ShowPurposeSourceRegion = mCombinedParameters.GetString("ShowPurposeSourceRegion"): If Len(.ShowPurposeSourceRegion) = 0 Then .ShowPurposeSourceRegion = "Advanced"
      .ShowInsurance = mCombinedParameters.GetString("ShowInsurance"): If Len(.ShowInsurance) = 0 Then .ShowInsurance = "Advanced"
      .PageNameHasAdvanced = (.ShowPurposeSourceRegion = "Advanced" OrElse .ShowInsurance = "Advanced")

      ' Configuration
      .AddOnsBranch = finBL.Settings.AddOns.Branch
      .AddOnsDisbursements = finBL.Settings.AddOns.Disbursements
      .AddOnsExternalPartyBrokers = finBL.Settings.AddOns.ExternalPartyBrokers
      .AddOnsExternalPartyDealers = finBL.Settings.AddOns.ExternalPartyDealers
      .AddOnsExternalPartyInsurers = finBL.Settings.AddOns.ExternalPartyInsurers
      .AddOnsPool = finBL.Settings.AddOns.Pool
      .AddOnsPromotions = finBL.Settings.AddOns.Promotions
      .AddOnsSecurityRegister = finBL.Settings.AddOns.SecurityRegister
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .ShowExternalId = finBL.SettingsUser.AccountShowExternalId
      .StdTransWidgetId = mStdTransWidgetId
      .WidgetClientNewIndividual = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientNew_Individual, mCombinedParameters.GetBoolean("UseBuiltInClientIndividualWidget"), strTemp)
      .WidgetClientNewIndividual_StartupParametersJson = strTemp
      .WidgetClientNewOrganisation = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientNew_Organisation, mCombinedParameters.GetBoolean("UseBuiltInClientOrganisationWidget"), strTemp)
      .WidgetClientNewOrganisation_StartupParametersJson = strTemp
      .WidgetDisbursement = finBL.CloudConnectFunctions.GetAccountHtmlWidgetId(isefinCloudConnectAccountScriptType.HtmlWidgetAccountDisbursement, mCombinedParameters.GetBoolean("UseBuiltInDisbursementItemWidget")) ', strTemp)
      .WidgetDisbursement_StartupParametersJson = strTemp
      .WidgetSecurityStmtItem = finBL.CloudConnectFunctions.GetSecurityStmtHtmlWidgetId(isefinCloudConnectSecurityStmtScriptType.HtmlWidgetSecurityStmtItem, mCombinedParameters.GetBoolean("UseBuiltInSecurityStatementItemWidget")) ', strTemp)
      .WidgetSecurityStmtItem_StartupParametersJson = strTemp
      
      ' Terminology
      .Terminology_SecurityStmtInsuranceBroker = finBL.Settings.SecurityStmtInsuranceBrokerTerminology

      ' Get Account Client defaults
      AccountClient = Account.Clients.CreateAccountClient()
      .DefaultClientAccountSignatory = AccountClient.AccountSignatory
      .DefaultClientPrivacyConsent = AccountClient.PrivacyConsent
      .DefaultClientSendDocuments = AccountClient.SendDocuments
      .DefaultClientSecurityParty = AccountClient.SecurityParty
      
      ' Special
      .QuoteMode = mQuoteMode
    End With
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Retrieve the Next Statement Date.
''' &lt;/summary&gt;
Private Function GetNextStatementDate(ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim AccountJson As String
  Dim Data As Object
  Dim StatementCycle As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    AccountJson = .GetString("Account")
    StatementCycle = .GetString("StatementCycle")
  End With

  ' Get Account Details
  Success = GetAccountDetails(AccountJson, AccountDetails)

  ' Get Account Statement Change object
  If Success Then
    Success = CreateAccount(AccountDetails, Account, False)
  End If

  ' Create Response
  If Success Then
    Data = New With {
      .StatementDateNext = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(Account.Calculation.AccountType.StatementDateNextResolved(Account.DateOpened, StatementCycle))
    }
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Client Details (for when only Client Id is available, e.g., when returned from a New Client wizard).
''' &lt;/summary&gt;
Public Function GetClientDetails(ByRef response As String) As Boolean

  Dim Client As finClient
  Dim ClientId As String
  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    ClientId = .GetString("ClientId")
  End With

  ' Load Client
  ' NOTE: We are only retrieving very basic details so do not need to check whether the Client is filtered out
  If Success Then
    Client = finBL.CreateClient()
    Success = Client.Load(ClientId)
  End If

  ' Get Client Details
  If Success Then
    obj = New With {
      .ClientId = Client.ClientId,
      .Name = Client.Name,
      .Status = If(Client.Status = isefinClientStatus.None, "", Client.Status.ToString())
    }
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Client Preview.
''' &lt;/summary&gt;
Public Function GetClientPreview(ByRef response As String) As Boolean

  Dim Client As finClient
  Dim ClientId As String
  Dim Html As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    ClientId = .GetString("ClientId")
  End With

  ' Load Client
  If Success Then
    Client = finBL.CreateClient()
    Success = Client.Load(ClientId)
  End If

  ' Get Summary
  If Success Then
    Html = finBL.SummaryPageFunctions.ClientSummary(False, Client, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
  End If

  ' Response
  If Success Then
    response = Html
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Promotions.
''' &lt;/summary&gt;
Public Function GetPromotions(parametersJson As String,
                              ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim Promotion As finAccountTypePromotionRO
  Dim Promotions As ISCodeDescriptionList
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetAccountDetails(parametersJson, AccountDetails)

  ' Create Account object
  If Success Then
    Success = CreateAccount(AccountDetails, Account, False)
  End If

  ' Validate
  If Success Then
    If Not finBL.AccountTypes.Exists(Account.AccountTypeId) Then
      Success = False
      finBL.Error.ErrorBegin("Account Type not found.")
    End If
  End If

  ' Get Promotions
  If Success Then
    Promotions = finBL.Runtime.CreateCodeDescriptionList()

    If Account.AccountType.PromotionBasis = isefinAccountTypePromotionBasis.DoesNotUsePromotions Then
      ' Account Type does not use Promotions
    Else
      For Each Promotion In Account.AccountType.Promotions.GetAvailablePromotions(Account.BranchId, Account.BrokerExternalPartyId, Account.DealerExternalPartyId, Account.Clients.GetClientTypeIds(), True)
        Promotions.Add(Promotion.PromotionId, Promotion.Description)
      Next
    End If
  End If

  ' Response
  If Success Then
    response = Promotions.ToJsonString()
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Print Contract.
''' &lt;/summary&gt;
Public Function PrintContract(ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountId As String
  Dim AccountLog As finAccountLog
  Dim Document As finDocumentRO
  Dim DocumentPk As Integer
  Dim FileInfo As finFileDownloadInfo
  Dim Subject As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    AccountId = .GetString("AccountId")
  End With

  ' Load Account
  Account = finBL.CreateAccount()
  Success = Account.Load(AccountId)

  ' Get Contract Document
  If Success Then
    Select Case Account.AccountClass
      Case isefinAccountClass.Deposit
        Subject = "Deposit Certificate"
        DocumentPk = Account.AccountType.InvestmentCertificateDocumentPk

      Case Else
        Subject = "Contract"
        DocumentPk = Account.AccountType.ContractDocumentPk
    End Select
  End If

  ' Validate
  If Success Then
    If DocumentPk = 0 Then
      Success = False
      finBL.Error.ErrorBegin("No Document is defined for this Account Type.")
    Else
      Document = finBL.Documents.ItemByPk(DocumentPk)
    End If
  End If

  ' Create Log
  If Success Then
    AccountLog = finBL.CreateAccountLog()
    With AccountLog
      ' Set Type and Source
      .LogType = isefinLogType.Document
      .SourceSet(isefinLogSource.WebInterface)

      ' Other Properties
      .DocumentPk = DocumentPk
      .PublishStatus = Document.DefaultPublishStatus
      .AccountId = Account.AccountId
      .Subject = Subject

      ' Fee
      .Fee = Document.Fee
      .FeeElementPk = Document.FeeElementPk
      .FeeReference = Document.FeeReference
      .FeeNotes = Document.FeeNotes

      ' Document Parameters
      Success = finBL.DocumentFunctions.SetDocumentLogParameters(AccountLog, Account, Document.DocumentId, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))

      ' External Party
      .ExternalPartyId = Account.DealerExternalPartyId

      ' Set Account Balance etc
      If Success Then Success = .AccountDataSet(, Account)

      ' Save
      If Success Then Success = .Save()
    End With

    If Not Success Then
      finBL.Error.ErrorExtend("No Document Log could be created. You can try again by loading the Account and selecing 'Create Document' from the Account Form's Actions button.")
    End If
  End If

  ' Validate Can Publish
  If Success Then
    If Not Document.SupportsUnattendedPublish Then
      Success = False
      finBL.Error.ErrorBegin("A Document Log was created but cannot be published from this interface.")
    End If
  End If

  ' Publish
  If Success Then
    If AccountLog.Publish(isefinLogPublishType.Publish, True) Then
      If mHostingContext = isefinHtmlWidgetHostingContext.WebInternal Then
        ' Refresh Account Log so Document File Name is available (ignore errors)
        AccountLog.Refresh()

        ' Get File to Download
        FileInfo = finBL.CreateFileDownloadInfo()
        If FileInfo.LoadDocumentManagerFile(isefinDocumentManagerSourceType.Account, Account.AccountId, "", AccountLog.DocumentFileName, "") Then
          response = FileInfo.ToXmlString()
        Else
          Success = False
        End If
      Else
        ' Publishing the Account Log within finPOWER Connect desktop also opens the file automatically
      End If
    Else
      Success = False
    End If
  End If

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to publish Contract Document.")
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Print a Quotation.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function PrintQuotation(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim CalculationFailed As Boolean
  Dim Document As finDocumentRO
  Dim FileData As Byte()
  Dim FileInfo As finFileDownloadInfo
  Dim ReturnValue2 As Boolean
  Dim ReturnValues As ISKeyValueList 
  Dim ParametersKvl As ISKeyValueList 
  Dim Success As Boolean
  Dim WordDocument As ISWordDocument
      
  ' Assume Success
  Success = True
  
  ' Initialise
  FileInfo = finBL.CreateFileDownloadInfo()

  ' Parse Parameters
  Success = GetAccountDetails(parametersJson, AccountDetails)

  ' Create Account object (this performs a calculation)
  If Success Then
    Success = CreateAccount(AccountDetails, Account, CalculationFailed) AndAlso Not CalculationFailed
  End If

  ' Get Quotation Document
  If Success Then
    Document = finBL.Documents(Account.AccountType.QuoteDocumentId)
  End If
  
  ' Validate Document
  If Success Then
    If Not Document.HasPermissionToExecute Then
      Success = False
      finBL.Error.ErrorBeginFormat("You do not have permission to execute Document '{0}'.", Document.DocumentId)
    ElseIf Document.FileType &lt;&gt; iseDocumentFileType.WordDocument Then
      Success = False
      finBL.Error.ErrorBeginFormat("Document '{0}' is not a 'Word Document' and cannot be used from this interface.", Document.DocumentId)
    End If
  End If
  
  ' Publish Document
  If Success Then
    ' Set a few extra properties for the Document
    If Account.IsNew Then
      If Account.Clients.Count &lt;&gt; 0 Then
        Account.Name = Account.Clients(0).ClientName
      End If
    End If
    
    ' Create Parameters
    ParametersKvl = finBL.CreateKeyValueList()
    With ParametersKvl
      .SetObject("Account", Account)      
      .SetString("DocumentId", Document.DocumentId)
    End With
    
    ' Execute Document
    Success = Document.ExecuteEvent(ReturnValue2, Nothing, "Publish", Nothing, False, ParametersKvl, ReturnValues, "") AndAlso ReturnValue2
  End If
  
  ' Get Word Document
  If Success Then
    If ReturnValues.Exists("WordDocument") AndAlso TypeOf ReturnValues.GetObject("WordDocument") Is ISWordDocument Then
      WordDocument = DirectCast(ReturnValues.GetObject("WordDocument"), ISWordDocument)          
      
      ' Create PDF from Word Document
      If WordDocument.SavePdfToByteArray(FileData) Then
        Success = FileInfo.LoadByteArray(FileData, "Quotation.pdf")
      Else
        Success = False
      End If
    Else
      Success = False
      finBL.Error.ErrorBeginFormat("Document '{0}' has not returned a 'WordDocument' property of type ISWordDocument.", Document.DocumentId)        
    End If
  End If
  
  ' Error
  ' NOTE: widget.DownloadDocument does not handle callbacks hence any errors should be returned as HTML to display to the User    
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to print Quotation Document.")
    FileInfo.LoadPlainText(finBL.HtmlEncode(finBL.Error.Message(True), True, True), "error.htm")
  End If
  
  ' Return file to download
  returnValue = FileInfo.ToXmlString()

  ' Always return True
  Return True

End Function

''' &lt;summary&gt;
'''  Get details required for refreshing a wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to refresh the wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object.
''' &lt;/param&gt;
Private Function WizardRefresh(parametersJson As String,
                               ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim AccountType As finAccountTypeRO
  Dim CalculationFailed As Boolean
  Dim ClientPkCsvList As String
  Dim MaturityAccountTypeFilter As String
  Dim obj As Object
  Dim PageId As String
  Dim ShowPaymentDetailsIncoming As Boolean
  Dim ShowPaymentDetailsMaturity As Boolean
  Dim ShowPaymentDetailsOutgoing As Boolean
  Dim ShowPaymentDetailsOutgoing_PaymentTypeCategoryFilter As String
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean
  Dim swb As ISSqlWhereBuilder

  ' Assume Success
  Success = True

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    PageId = .GetString("PageId")
  End With

  ' Validate Page
  Select Case PageId
    Case "Clients"
      ' =======
      ' Clients
      ' =======
      ' Parse Parameters
      Success = GetAccountDetails(mCombinedParameters.GetString("AccountDetails"), AccountDetails)

      ' Create Account object to (potentially) tweak Account Roles
      If Success Then
        If CreateAccount(AccountDetails, Account, CalculationFailed) Then
          obj = New AccountDetails(finBL, Account).Clients
        Else
          Success = False
        End If
      End If

    Case "Name"
      ' ====
      ' Name
      ' ====
      ' Parse Parameters
      Success = GetAccountDetails(mCombinedParameters.GetString("AccountDetails"), AccountDetails)

      ' Create Account object and get details
      If Success Then
        If CreateAccount(AccountDetails, Account, CalculationFailed) Then
          obj = New With {
            .AccountTypeId = Account.AccountTypeId,
            .DefaultName = Account.GetStandardName(),
            .DefaultDescription = Account.CreateDescription(),
            .DefaultLedger = Account.AccountType.DefaultLedger,
            .OptionAllowLedger = Account.AccountType.OptionAllowLedger,
            .OptionDefaultPrintContractDocument = Account.AccountType.OptionDefaultPrintContractDocument
          }
        Else
          Success = False
        End If
      End If

    Case "Other"
      ' =====
      ' Other
      ' =====
      ' Parse Parameters
      Success = GetAccountDetails(mCombinedParameters.GetString("AccountDetails"), AccountDetails)

      If Success Then
        ' Create Account object
        If CreateAccount(AccountDetails, Account, CalculationFailed) Then
          AccountType = Account.AccountType

          ' Payment Details to show
          ShowPaymentDetailsIncoming = Account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Incoming)
          If Account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Outgoing) Then
            Select Case Account.Calculation.InterestPaymentType
              Case isefinAccountInterestPaymentType.Capitalise, isefinAccountInterestPaymentType.Compound, isefinAccountInterestPaymentType.Transfer
                If AccountType.AccountClass = isefinAccountClass.Disbursement Then
                  ShowPaymentDetailsOutgoing = True
                Else
                  ShowPaymentDetailsOutgoing = False
                End If

              Case Else
                ShowPaymentDetailsOutgoing = True
                ShowPaymentDetailsOutgoing_PaymentTypeCategoryFilter = Account.Calculation.InterestPaymentType.ToString()
            End Select
          Else
            ShowPaymentDetailsOutgoing = False
          End If
          ShowPaymentDetailsMaturity = Account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Maturity)

          ' Maturity Account Types
          If Len(Account.Calculation.AccountType.MaturityAccountTypesNew) = 0 Then
            MaturityAccountTypeFilter = finBL.AccountTypes.GetDataViewFilter(False, 0, True, New List(Of isefinAccountClass) From {isefinAccountClass.Deposit})
          Else
            MaturityAccountTypeFilter = finBL.AccountTypes.GetDataViewFilter(False, 0, True, New List(Of isefinAccountClass) From {isefinAccountClass.Deposit}, True, Account.Calculation.AccountType.MaturityAccountTypesNew)
          End If

          ' Maturity Reinvestment Accounts
          If Account.Calculation.AccountType.MaturityReinvestmentCommonClient Then
            sqb = Account.Clients.GetCommonClientsSQL(False, ClientPkCsvList)
          End If
          swb = finBL.Database.CreateSqlWhereBuilder()
          If Account.Pk &lt;&gt; 0 Then swb.AppendComparisonInteger("Account.Pk", "&lt;&gt;", Account.Pk)
          swb.AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Open))
          If Account.Calculation.AccountType.MaturityReinvestmentCommonClient AndAlso sqb IsNot Nothing Then
            swb.AppendExists(sqb)
          End If

          ' Get Details
          obj = New With {
            .MaturityAccountFilter = finBL.HtmlWidgetUtilities.EncryptSql(swb.SqlWhere),
            .MaturityAccountTypeFilter = finBL.HtmlWidgetUtilities.EncryptSql(MaturityAccountTypeFilter),
            .MaturityAvailableInstructionsList = finBL.Enums.isefinAccountMaturityInstruction_ToCodeDescriptionList(AccountType.MaturityAvailableInstructions).ToJsonObject(),
            .MaturityPaymentAvailableTypesList = finBL.Enums.isefinAccountMaturityPaymentType_ToCodeDescriptionList(AccountType.MaturityPaymentAvailableTypes).ToJsonObject(),
            .MaturityInstructionText = Account.MaturityInstructionText,
            .MaturityPaymentTypeText = Account.MaturityPaymentTypeText,
            .OptionAllowReviewDate = AccountType.OptionAllowReviewDate,
            .OptionAllowMaturityInstruction = AccountType.OptionAllowMaturityInstruction,
            .ShowPaymentDetailsIncoming = ShowPaymentDetailsIncoming,
            .ShowPaymentDetailsOutgoing = ShowPaymentDetailsOutgoing,
            .ShowPaymentDetailsOutgoing_PaymentTypeCategoryFilter = ShowPaymentDetailsOutgoing_PaymentTypeCategoryFilter,
            .ShowPaymentDetailsMaturity = ShowPaymentDetailsMaturity,
            .StatementUse = AccountType.StatementUse,
            .StatementCycleList = If(Account.AccountClass = isefinAccountClass.LoanRC, "Weekly,Fortnightly,Monthly,End of Month,Quarterly,6 Monthly,Yearly", "None,On Demand,Weekly,Fortnightly,Monthly,End of Month,Quarterly,6 Monthly,Yearly")
          }
        Else
          Success = False
        End If
      End If
  End Select

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object; "true" if validation passed, otherwise, information as to why validation failed.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim AccountTypeId As String
  Dim AccountTypePromotionId As String
  Dim BranchId As String
  Dim BrokerId As String
  Dim CalculationFailed As Boolean
  Dim Data As Object
  Dim DealerId As String
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim Found As Boolean
  Dim PageId As String
  Dim Promotion As finAccountTypePromotionRO
  Dim Promotions As ISReadOnlyList(Of finAccountTypePromotionRO)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    PageId = .GetString("PageId")
  End With

  ' Validate Page
  Select Case PageId
    Case "General"
      ' Get Parameters
      With mCombinedParameters
        AccountTypeId = .GetString("AccountTypeId")
        AccountTypePromotionId = .GetString("AccountTypePromotionId")
        BranchId = .GetString("BranchId")
        BrokerId = .GetString("BrokerId")
        DealerId = .GetString("DealerId")
      End With

      ' Validate Account Type
      If finBL.AccountTypes.Exists(AccountTypeId) Then
        ' Validate Promotion
        If finBL.Settings.AddOns.Promotions Then
          With finBL.AccountTypes(AccountTypeId)
            If .PromotionBasis = isefinAccountTypePromotionBasis.DoesNotUsePromotions AndAlso Len(AccountTypePromotionId) &lt;&gt; 0 Then
              FailedMessage = "The Account Type does not use Promotions."
              FailedControlId = "cboAccountType"
            ElseIf .PromotionBasis = isefinAccountTypePromotionBasis.MustUsePromotion AndAlso Len(AccountTypePromotionId) = 0 Then
              FailedMessage = "You must specify a Promotion for this Account Type."
              FailedControlId = "cboAccountTypePromotion"
            Else
              If Len(AccountTypePromotionId) &lt;&gt; 0 Then
                Promotions = .Promotions.GetAvailablePromotions(BranchId, BrokerId, DealerId, New ISList(), True)
                For Each Promotion In Promotions
                  If strComp(Promotion.PromotionId, AccountTypePromotionId, CompareMethod.Text) = 0 Then
                    Found = True
                    Exit For
                  End If
                Next

                If Not Found Then
                  FailedMessage = String.Format("Promotion '{0}' does not relate to this Account Type.", AccountTypePromotionId)
                  FailedControlId = "cboAccountTypePromotion"
                End If
              End If
            End If
          End With
        End If
      Else
        FailedMessage = "Invalid Account Type."
        FailedControlId = "cboAccountType"
      End If

    Case "Clients", "Security", "Financial"
      ' Clients/ Security/ Financial
      Success = GetAccountDetails(mCombinedParameters.GetString("AccountDetails"), AccountDetails)
      If Success Then
        If CreateAccount(AccountDetails, Account, CalculationFailed) Then
          Select Case PageId
            Case "Clients"
              If Not Account.Clients.Validate(Account.ProductTypeId) Then
                FailedMessage = finBL.Error.Message(True)
                FailedControlId = "gridClients"
              ElseIf Not Account.Clients.ValidatePromotion() Then
                FailedMessage = finBL.Error.Message(True)
                FailedControlId = "gridClients"
              End If

            Case "Security"
              If Not Account.SecurityStmt.SecurityItems.Validate() Then
                FailedMessage = finBL.Error.Message(True)
                FailedControlId = "gridSecurity"
              End If

            Case "Financial"
              If CalculationFailed Then
                FailedMessage = finBL.Error.Message(True)
                FailedControlId = "afFinancial"
              End If
          End Select
        Else
          Success = False
        End If
      End If

    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unhandled page '{0}' in WizardValidate.", PageId)
  End Select

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardValidateResponse(Data, FailedMessage, FailedControlId), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Overriding Payments Handling.
''' &lt;/summary&gt;
Private Function OverridingPaymentsHandling(ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountDetails As AccountDetails
  Dim AccountJson As String
  Dim Action As String
  Dim OverridingPaymentsJson As String
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Get Parameters
  With mCombinedParameters
    Action = .GetString("Action")
    AccountJson = .GetString("AccountJson")
    OverridingPaymentsJson = .GetString("OverridingPaymentsJson")
  End With
  
  ' Parse Parameters
  Success = GetAccountDetails(AccountJson, AccountDetails)
  
  ' Create Account object and update payments
  If Success Then
    If CreateAccount(AccountDetails, Account, False) Then
      Success = Account.Calculation.Payments.FromHtmlWidgetJsonString(OverridingPaymentsJson)
    Else 
      Success = False
    End If
  End If  
  
  ' Handle Action
  If Success Then
    Select Case Action
      Case "PaymentsCleanup"
        With Account.Calculation.Payments
          Success = (.RemoveIgnored() AndAlso .RemoveBlankRegularPayments())
        End With
        
      Case "RegularPaymentsCreate"
        Success = Account.Calculation.Payments.CreateBlankRegularPayments()
        
      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Overriding Payments Action '{0}' is unhandled.", Action)
    End Select   
  End If
  
  ' Return
  If Success Then
    returnValue = Account.Calculation.Payments.ToHtmlWidgetJsonString()
  End If
  
  Return Success
                                       
End Function



''' &lt;summary&gt;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

  ' Account
  Public Account As AccountDetails
  Public Refinance As Boolean
  Public RefinanceCreatedFromAccountId As String
  
  ' Quotation Mode
  Public QuotationClientId As String

  ' Lists
  Public AccountTypes As New List(Of AccountTypeInfo)
  Public ProductTypes As New List(Of ProductTypeInfo)

  ' Information Lists
  Public PolicyTypeAllowBlank As Boolean
  Public PolicyTypeInformationListId As String
  Public PurposeAllowBlank As Boolean
  Public PurposeInformationListId As String
  Public RegionAllowBlank As Boolean
  Public RegionInformationListId As String
  Public SourceAllowBlank As Boolean
  Public SourceInformationListId As String

  ' Permissions
  Public CanUpdateAccountId As Boolean
  Public CanUpdateStatusQuoteToOpen As Boolean

  ' Advanced Sections
  Public ShowBranch As String
  Public ShowDealer As String
  Public ShowBroker As String
  Public ShowAccountManager As String
  Public ShowPool As String
  Public PageGeneralHasAdvanced As Boolean

  Public ShowClientAdditional As String
  Public PageClientsHasAdvanced As Boolean

  Public ShowPurposeSourceRegion As String
  Public ShowInsurance As String
  Public PageNameHasAdvanced As Boolean

  ' Global Collections
  Public AccountRoles As New List(Of AccountRoleInfo)

  ' Configuration
  Public AddOnsBranch As Boolean
  Public AddOnsDisbursements As Boolean
  Public AddOnsExternalPartyBrokers As Boolean
  Public AddOnsExternalPartyDealers As Boolean
  Public AddOnsExternalPartyInsurers As Boolean
  Public AddOnsPool As Boolean
  Public AddOnsPromotions As Boolean
  Public AddOnsSecurityRegister As Boolean  
  Public DefaultClientAccountSignatory As Boolean
  Public DefaultClientPrivacyConsent As Boolean
  Public DefaultClientSendDocuments As Boolean
  Public DefaultClientSecurityParty As Boolean  
  Public PromptOnSave As Boolean
  Public ShowExternalId As Boolean
  Public StdTransWidgetId As String
  Public WidgetClientNewIndividual As String
  Public WidgetClientNewIndividual_StartupParametersJson As String
  Public WidgetClientNewOrganisation As String
  Public WidgetClientNewOrganisation_StartupParametersJson As String
  Public WidgetDisbursement As String
  Public WidgetDisbursement_StartupParametersJson As String
  Public WidgetSecurityStmtItem As String
  Public WidgetSecurityStmtItem_StartupParametersJson As String
  
  ' Terminology
  Public Terminology_SecurityStmtInsuranceBroker As Boolean

  ' Special
  Public QuoteMode As Boolean
  Public SecurityStmtMessage As String

  ' Identify if an Account Type exists in the collection
  Public Function AccountTypeExists(accountTypeId As String) As Boolean

    Dim AccountTypeInfo As AccountTypeInfo

    For Each AccountTypeInfo In Me.AccountTypes
      If StrComp(AccountTypeInfo.AccountTypeId, accountTypeId, CompareMethod.Text) = 0 Then Return True
    Next

    Return False

  End Function

End Class

''' &lt;summary&gt;
'''  Validation details.
''' &lt;/summary&gt;
Public Class WizardValidateResponse

  Public Data As Object
  Public FailedControlId As String
  Public FailedMessage As String

  Public Sub New(data As Object,
                 failedMessage As String,
                 failedControlId As String)

    Me.Data = data
    Me.FailedMessage = failedMessage
    Me.FailedControlId = failedControlId

  End Sub

End Class

''' &lt;summary&gt;
'''  Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters
  ' Not applicable
End Class

''' &lt;summary&gt;
'''  Finish details.
''' &lt;/summary&gt;
Public Class WizardFinishDetails

  Public AccountId As String

  Public Sub New(accountId As String)

    Me.AccountId = accountId

  End Sub

End Class


''' &lt;summary&gt;
'''  Calculation details.
''' &lt;/summary&gt;
Public Class CalculationDetails

  Public Account As AccountDetails
  Public AccountSummaryHtml As String
  Public OwnerClientIds As String ' To pass to the Account Standard Transaction form for filtering Transfers if required

  Public Sub New(account As AccountDetails,
                 accountSummaryHtml As String,
                 ownerClientIds As String)

    Me.Account = account
    Me.AccountSummaryHtml = accountSummaryHtml
    Me.OwnerClientIds = ownerClientIds

  End Sub

End Class


''' &lt;summary&gt;
'''  Account Details.
''' &lt;/summary&gt;
Public Class AccountDetails

  ' Editing a 'Quote' Account
  Public AccountId As String
  Public AccountPk As Integer
  Public AccountTimestamp As Integer

  ' General
  Public AccountManagerUserId As String
  Public AccountTypeId As String
  Public AccountTypeIdOriginal As String ' Tracks changes of Account Type
  Public AccountTypePromotionId As String
  Public BankingDetailsIncomingJson As String
  Public BankingDetailsOutgoingJson As String
  Public BankingDetailsMaturityJson As String
  Public BranchId As String
  Public BrokerId As String
  Public BrokerEmployeeId As String
  Public DateAccepted As Date?
  Public DateQuoted As Date?
  Public DateReview As Date?
  Public DateSigned As Date?
  Public DealerId As String
  Public DealerEmployeeId As String
  Public DepartmentId As String
  Public Description As String
  Public ExternalId As String
  Public InsurerId As String
  Public InsurancePolicyNumber As String
  Public InsurancePolicyType As String
  Public InterestTransferToAccountId As String
  Public Ledger As String
  Public MaturityInstructionText As String
  Public MaturityValue As Decimal
  Public MaturityAccountTypeId As String
  Public MaturityAccountId As String
  Public MaturityPaymentTypeText As String
  Public MaturityTransferToAccountId As String
  Public Name As String
  Public NewAccountId As String
  Public Notes As String
  Public PoolId As String
  Public ProductTypeId As String
  Public Purpose As String
  Public QuoteNotes As String
  Public QuoteReady As Boolean
  Public Region As String
  Public Source As String
  Public StatementCycle As String
  Public StatementDateFirst As Date?
  Public UserDataJson As String
  
  ' Quote Mode-specific
  Public QuoteClientId As String
  
  ' Internal Use only
  Public Action As String
  Public MatchDisbursementDateToOpening As Boolean

  ' Objects
  Public AccountCalcJson As String
  Public Clients As New List(Of AccountClientDetails)
  Public Disbursements As New List(Of DisbursementDetails)
  Public SecurityItems As New List(Of SecurityItemDetails)

  Public Sub New()
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 account As finAccount)

    Dim AccountClient As finAccountClient
    Dim AccountDisbursement As finAccountDisbursement
    Dim SecurityStmtItem As finSecurityStmtItemBase

    With account
      ' Existing Account
      Me.AccountId = .AccountId
      Me.AccountPk = .Pk
      Me.AccountTimestamp = .Timestamp

      ' General
      Me.AccountManagerUserId = .AccountManagerUserId
      Me.AccountTypeId = .AccountTypeId
      Me.AccountTypeIdOriginal = .AccountTypeId
      Me.AccountTypePromotionId = .AccountTypePromotionId
      If account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Incoming) Then
        Me.BankingDetailsIncomingJson = account.BankingDetails(isefinAccountBankingDetailsType.Incoming).BankingDetails.ToHtmlWidgetJsonString()
      End If
      If account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Outgoing) Then
        Me.BankingDetailsIncomingJson = account.BankingDetails(isefinAccountBankingDetailsType.Outgoing).BankingDetails.ToHtmlWidgetJsonString()
      End If
      If account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Maturity) Then
        Me.BankingDetailsIncomingJson = account.BankingDetails(isefinAccountBankingDetailsType.Maturity).BankingDetails.ToHtmlWidgetJsonString()
      End If
      Me.BranchId = .BranchId
      Me.BrokerId = .BrokerExternalPartyId
      Me.BrokerEmployeeId = .BrokerExternalPartyEmployeeClientEmploymentId
      Me.DateQuoted = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateQuoted)
      Me.DateAccepted = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateAccepted)
      Me.DateReview = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateReview)
      Me.DateSigned = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateSigned)
      Me.DealerId = .DealerExternalPartyId
      Me.DealerEmployeeId = .DealerExternalPartyEmployeeClientEmploymentId
      Me.DepartmentId = .DepartmentId
      Me.Description = .Description
      Me.ExternalId = .ExternalId
      Me.InsurerId = .InsuranceInsurerExternalPartyId
      Me.InsurancePolicyNumber = .InsurancePolicyNumber
      Me.InsurancePolicyType = .InsurancePolicyType
      Me.InterestTransferToAccountId = .InterestTransferToAccountId
      Me.Ledger = .Ledger
      Me.MaturityInstructionText = .MaturityInstructionText
      Me.MaturityValue = .MaturityValue
      Me.MaturityAccountTypeId = .MaturityAccountTypeId
      Me.MaturityAccountId = .MaturityAccountId
      Me.MaturityPaymentTypeText = .MaturityPaymentTypeText
      Me.MaturityTransferToAccountId = .MaturityTransferToAccountId
      Me.Name = .Name
      Me.Notes = .Notes
      Me.PoolId = .PoolId
      Me.ProductTypeId = .ProductTypeId
      Me.Purpose = .Purpose
      Me.QuoteNotes = .QuoteNote
      Me.QuoteReady = (.DateQuoteReady &lt;&gt; Nothing)
      Me.Region = .Region
      Me.Source = .Source
      Select Case UCase(.Calculation.StatementCycle)
        Case "NONE", "ON DEMAND"
          Me.StatementCycle = .Calculation.StatementCycle
        Case Else
          Me.StatementCycle = finBL.Utilities.DateCycleGetMnemonicFriendly(True, .Calculation.StatementCycle)
      End Select
      Me.StatementDateFirst = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.Calculation.StatementDateNext)

      ' Clients
      For Each AccountClient In account.Clients
        Me.Clients.Add(New AccountClientDetails(finBL, AccountClient))
      Next

      ' Disbursements
      If finBL.Settings.AddOns.Disbursements Then
        For Each AccountDisbursement In account.Disbursements
          Me.Disbursements.Add(New DisbursementDetails(finBL, AccountDisbursement))
        Next
      End If

      ' Security Items
      If finBL.Settings.AddOns.SecurityRegister AndAlso account.SecurityStmt IsNot Nothing Then
        For Each SecurityStmtItem In account.SecurityStmt.SecurityItems
          Me.SecurityItems.Add(New SecurityItemDetails(finBL, SecurityStmtItem))
        Next
      End If
      
      ' Calculation
      ' NOTE: Include configuration details but not schedule
      Me.AccountCalcJson = .Calculation.ToHtmlWidgetJsonString(True, False, True, Nothing)
      
      ' User Defined
      Me.UserDataJson = .UserData.ToSimpleJsonString()
    End With
  End Sub

End Class


''' &lt;summary&gt;
'''  Account Client details.
''' &lt;/summary&gt;
Public Class AccountClientDetails

  Public Pk As Integer
  Public AccountRoleId As String
  Public AccountRoleDescription As String
  Public ClientId As String
  Public ClientName As String
  Public ClientStatus As String
  Public RoleJoint As Boolean
  Public AccountSignatory As Boolean
  Public PrivacyConsent As Boolean
  Public SendDocuments As Boolean
  Public SecurityParty As Boolean

  Public Sub New()
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 accountClient As finAccountClient)

    With accountClient
      Me.Pk = .Pk
      Me.AccountRoleId = .AccountRoleId
      If .AccountRole Is Nothing Then
        Me.AccountRoleDescription = ""
      Else
        Me.AccountRoleDescription = .AccountRole.DescriptionShortResolved
      End If
      Me.ClientId = .ClientId
      Me.ClientName = .ClientName
      If .ClientStatus &lt;&gt; isefinClientStatus.None Then Me.ClientStatus = .ClientStatus.ToString()
      Me.RoleJoint = .RoleJoint
      Me.AccountSignatory = .AccountSignatory
      Me.PrivacyConsent = .PrivacyConsent
      Me.SendDocuments = .SendDocuments
      Me.SecurityParty = .SecurityParty
    End With

  End Sub

End Class


''' &lt;summary&gt;
'''  Security Item details.
''' &lt;/summary&gt;
Public Class SecurityItemDetails

  Public Pk As Integer
  Public Description As String
  Public Json As String
  Public SecurityTypeDescription As String
  Public SecurityTypeIcon As String
  Public SecurityTypeId As String
  Public SecurityValue As Decimal
  Public TradeIn As Boolean
  Public Value As Decimal

  Public Sub New()
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 securityStmtItem As finSecurityStmtItemBase)

    With securityStmtItem
      Me.Pk = .Pk
      Me.Description = .CreateDescription() ' Ensure automatically generated descriptions are update after refresh
      Me.Json = .ToHtmlWidgetJsonString(True) ' Ensure we pass back User Indexes and data-types since this is an in-memory Security Statement and they may get lost otherwise
      Me.SecurityTypeDescription = .SecurityType.DescriptionShortResolved
      Me.SecurityTypeIcon = .SecurityType.IconResolved
      Me.SecurityTypeId = .SecurityTypeId
      Me.TradeIn = .TradeIn
      Me.Value = .Value
      Me.SecurityValue = .SecurityValue
    End With

  End Sub

End Class


''' &lt;summary&gt;
'''  Simple information about a Product Type.
''' &lt;/summary&gt;
Public Class ProductTypeInfo

  Public AccountPurposeAllowBlank As Boolean
  Public AccountPurposeInformationListId As String
  Public AccountRolesList As Object
  Public AccountSourceAllowBlank As Boolean
  Public AccountSourceInformationListId As String
  Public AccountTypesList As New List(Of String)
  Public Caption As String
  Public DefaultAccountRoleId As String
  Public DefaultAccountTypeId As String
  Public Icon As String
  Public ProductTypeId As String

  Public Sub New(finBL As ISfinSupport,
                 productType As finProductTypeRO,
                 quoteMode As Boolean)

    Dim AccountRole As finAccountRoleRO
    Dim AccountType As finAccountTypeRO
    Dim AccountRoles As ISCodeDescriptionList

    With productType
      Me.Caption = .Description
      If Len(.Icon) = 0 Then
        Me.Icon = "ProductType"
      Else
        Me.Icon = "AccountType_" &amp; .Icon
      End If
      Me.ProductTypeId = .ProductTypeId
      Me.AccountPurposeInformationListId = .AccountPurposeInformationListIdResolved
      Me.AccountSourceInformationListId = .AccountSourceInformationListIdResolved
      Me.DefaultAccountRoleId = .DefaultAccountRoleId
      Me.DefaultAccountTypeId = .DefaultAccountTypeId
    End With

    ' Information Lists
    Me.AccountPurposeAllowBlank = True
    Me.AccountSourceAllowBlank = True
    If Len(Me.AccountPurposeInformationListId) &lt;&gt; 0 AndAlso finBL.InformationLists.Exists(Me.AccountPurposeInformationListId) Then
      Me.AccountPurposeAllowBlank = (Not finBL.InformationLists(Me.AccountPurposeInformationListId).Mandatory)
    End If
    If Len(Me.AccountSourceInformationListId) &lt;&gt; 0 AndAlso finBL.InformationLists.Exists(Me.AccountSourceInformationListId) Then
      Me.AccountSourceAllowBlank = (Not finBL.InformationLists(Me.AccountSourceInformationListId).Mandatory)
    End If

    ' Available Account Types
    For Each AccountType In finBL.AccountTypes.GetAvailableAccountTypes(productType.ProductTypeId, False, Nothing, "")
      If AccountType.Active Then
          If quoteMode AndAlso (AccountType.AccountClass = isefinAccountClass.Disbursement OrElse AccountType.AccountClass = isefinAccountClass.LoanRC) Then
            ' Do not include Disbursement or Revolving Credit Accounts in 'Quote' mode
          Else
            Me.AccountTypesList.Add(AccountType.AccountTypeId)
          End If
      End If
    Next

    ' Available Account Roles
    AccountRoles = finBL.Runtime.CreateCodeDescriptionList()
    For Each AccountRole In productType.GetAccountRolesList()
      If AccountRole.Active Then
        AccountRoles.Add(AccountRole.AccountRoleId, AccountRole.Description)
      End If
    Next
    Me.AccountRolesList = AccountRoles.ToJsonObject

  End Sub

End Class


''' &lt;summary&gt;
'''  Simple information about an Account Role.
''' &lt;/summary&gt;
Public Class AccountRoleInfo

  Public AccountHidden As Boolean
  Public AccountRoleId As String
  Public AccountSignatory As Boolean
  Public IncludeInSecurityStatement As Boolean
  Public SendDocuments As Boolean
  Public UsePrivacyConsent As Boolean

  Public Sub New(finBL As ISfinSupport,
                 accountRole As finAccountRoleRO)

    With accountRole
      Me.AccountHidden = .AccountHidden
      Me.AccountRoleId = .AccountRoleId      
      Me.AccountSignatory = .AccountSignatory
      Me.IncludeInSecurityStatement = .IncludeInSecurityStatement
      Me.SendDocuments = .SendDocuments
      Me.UsePrivacyConsent = .UsePrivacyConsent
    End With

  End Sub

End Class


''' &lt;summary&gt;
'''  Simple information about an Account Type.
''' &lt;/summary&gt;
Public Class AccountTypeInfo

  Public AccountClass As String
  Public AccountTypeId As String
  Public Caption As String
  Public DefaultStatusAsQuote As Boolean
  Public HasPromotions As Boolean
  Public IncludeAccountLevelInsurance As Boolean
  Public Icon As String
  Public PromotionMandatory As Boolean
  Public ShowDisbursementsPage As Boolean
  Public ShowFinancialPagePrintQuotation As Boolean
  Public ShowSecurityPage As Boolean
  Public ShowUserDefinedPage As Boolean
  Public UserDefinedParameters As ISWsParameters

  Public Sub New(finBL As ISfinSupport,
                 accountType As finAccountTypeRO)

    Dim BrokerId As String
    Dim DealerId As String

    ' External User details
    Select Case finBL.CurrentUserInformation.ExternalPartyType
      Case isefinExternalPartyType.Broker
        BrokerId = finBL.CurrentUserInformation.ExternalPartyId
      Case isefinExternalPartyType.Dealer
        DealerId = finBL.CurrentUserInformation.ExternalPartyId
    End Select

    With accountType
      Me.AccountClass = .AccountClass.ToString()
      Me.AccountTypeId = .AccountTypeId
      Me.Caption = .Description
      If Len(.Icon) = 0 Then
        Me.Icon = "AccountType"
      Else
        Me.Icon = "AccountType_" &amp; .Icon
      End If
      Me.DefaultStatusAsQuote = .OptionDefaultQuoteStatus
      
      ' Promotion Information
      ' NOTE: HasPromotions must be set to True at this point if the Account Type has ANY active Promotions (unless this is an External User in which case they will never change)
      If finBL.Settings.AddOns.Promotions AndAlso .PromotionBasis &lt;&gt; isefinAccountTypePromotionBasis.DoesNotUsePromotions Then
        If Len(BrokerId) &lt;&gt; 0 OrElse Len(DealerId) &lt;&gt; 0 Then
          ' External User
          Me.HasPromotions = .Promotions.GetAvailablePromotions("", BrokerId, DealerId, New ISList(), True).Count &lt;&gt; 0
        Else
          ' Other (Dealer and/ or Broker can be changed at any point - GetPromotions handles this)
          Me.HasPromotions = .Promotions.CountNotClosed &lt;&gt; 0
        End If
      Else
        Me.HasPromotions = False
      End If

      Me.PromotionMandatory = (.PromotionBasis = isefinAccountTypePromotionBasis.MustUsePromotion)

      ' Configuration
      Me.IncludeAccountLevelInsurance = .IncludeAccountLevelInsurance
      Me.ShowDisbursementsPage = finBL.Settings.AddOns.Disbursements AndAlso .AccountClass &lt;&gt; isefinAccountClass.Disbursement AndAlso .DisbursementsShowInNewAccountWizard AndAlso finBL.CurrentUser.Permissions.Allow("Account.FormNew.Page.Disbursements")
      Me.ShowFinancialPagePrintQuotation = .OptionShowFinancialPagePrintQuotation AndAlso finBL.Documents.Exists(.QuoteDocumentId)
      Me.ShowSecurityPage = finBL.Settings.AddOns.SecurityRegister AndAlso .ProductType.UseSecurityStmts
      Me.ShowUserDefinedPage = .UserDefinedShowInNewAccountWizard AndAlso .UserDefinedParameterSetPk &lt;&gt; 0
      If Me.ShowUserDefinedPage Then
        Me.UserDefinedParameters = finBL.CreateWsParameters(finBL.AccountFunctions.CreateUserDefinedParameters(.UserDefinedParameterSetPk))
      End If
    End With

  End Sub

End Class

''' &lt;summary&gt;
'''  Client Search Result.
''' &lt;/summary&gt;
Public Class ClientSearchResult

  Public ClientId As String
  Public ClientStatus As String
  Public DateOfBirth As Date?
  Public Name As String

  Public Sub New(finBL As ISfinSupport,
                 quickSearchResult As finQuickSearchResult)

    Dim Client As finClient

    Client = DirectCast(quickSearchResult.SourceObject, finClient)

    With quickSearchResult
      Me.ClientId = .Id
      If Client.Status &lt;&gt; isefinClientStatus.None Then Me.ClientStatus = Client.Status.ToString()
      Me.DateOfBirth = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Client.DateOfBirth)
      Me.Name = .Name
    End With

  End Sub

End Class

Public Class DisbursementDetails

  ' Properties
  Public Pk As Integer
  Public [Date] As Date
  Public DateDue As Date?
  Public ElementDescription As String
  Public ElementId As String
  Public Json As String
  Public PayeeName As String
  Public PayeeTypeText As String
  Public Status As isefinDisbursementStatus
  Public StatusText As String
  Public [Type] As isefinDisbursementType
  Public TypeText As String
  Public Value As Decimal

  ' Permissions
  Public CanApprove As Boolean
  Public CanCancel As Boolean
  Public CanDelete As Boolean
  Public CanHold As Boolean
  Public CanPending As Boolean
  Public CanReverse As Boolean

  ' Constructors
  Public Sub New()
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 accountDisbursement As finAccountDisbursement)

    With accountDisbursement
      Me.Pk = .Pk
      Me.Date = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.Date)
      Me.DateDue = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateDue)
      Me.ElementDescription = .ElementDescription
      Me.ElementId = .ElementId
      Me.Json = .ToHtmlWidgetJsonString("")
      Select Case accountDisbursement.PayeeType
        Case isefinDisbursementPayeeType.Account
          Me.PayeeName = .PayeeName
        Case isefinDisbursementPayeeType.None
          Me.PayeeName = ""
        Case Else
          If Len(.ExternalPartyId) &lt;&gt; 0 Then
            Me.PayeeName = finBL.ExternalParties(.ExternalPartyId).Name
          End If
      End Select
      Me.PayeeTypeText = .PayeeTypeText
      Me.Status = .Status
      Me.StatusText = .StatusText
      Me.Type = .Type
      Me.TypeText = .TypeText
      Me.Value = .Value

      ' Permissions
      Me.CanApprove = False
      Me.CanCancel = False
      Me.CanDelete = .CanDelete()
      Me.CanReverse = .CanReverse()
      Me.CanHold = (.Status = isefinDisbursementStatus.Pending)
      Me.CanPending = (.Status = isefinDisbursementStatus.Hold)
    End With

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "AccountNew".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
/* Finacial page (used in conjunction with widget.css) */
#pageFinancial &gt; div {
  display:flex;
  flex-direction:column;
  overflow:hidden;

  &gt; div:first-child {
    position:relative;
    overflow:auto;
    height:50%;
    flex-grow:1;
    flex-shrink:0;
  }

  &gt; div:last-child {
    position:relative;
    overflow:auto;
    height:50%;
    flex-grow:1;
    flex-shrink:0;
  }
}

/* Small device portrait */
@media screen and (max-width:640px) {
#pageFinancial &gt; div {
  &gt; div:first-child {
    height:60%;
    overflow:hidden;
  }

  &gt; div:last-child {
    height:40%;
  }
}
}
&lt;/style&gt;


&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;New Account&lt;/div&gt;
    &lt;div class="summary"&gt;Enter Account details.&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Select an Account Type."&gt;Account Type&lt;/li&gt;
        &lt;li tabId="Clients" tooltipText="Specify Clients for this Account."&gt;Clients&lt;/li&gt;
        &lt;li tabId="Security" tooltipText="Enter details of any items the Account is being secured over"&gt;Security&lt;/li&gt;
        &lt;li tabId="Name" tooltipText="Enter the Name and other details for this Account."&gt;Name &amp;amp; Details&lt;/li&gt;
        &lt;li tabId="Financial" tooltipText="Specify Financial details for this Account."&gt;Financial&lt;/li&gt;
        &lt;li tabId="Other" tooltipText="Enter other Account details."&gt;Other Details&lt;/li&gt;
        &lt;li tabId="Disbursements" tooltipText="Enter Disbursements."&gt;Disbursements&lt;/li&gt;
        &lt;li tabId="UserDefined" tooltipText="Enter User Defined details."&gt;User Defined&lt;/li&gt;
        &lt;li tabId="Finalise" tooltipText="Review the details on this page before finalising this new Account."&gt;Finalise&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- General --&gt;
    &lt;div id="pageGeneral" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tbody class="tbProductType"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblProductType"&gt;Select a Product&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;div id="blProductTypes"&gt;&lt;/div&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="tbGeneral"&gt;
          &lt;tr id="trBranch" &gt;
            &lt;th colspan="2"&gt;&lt;label id="lblBranch"&gt;Specify Branch and Department&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="Branch"&gt;
            &lt;th&gt;&lt;label for="cboBranch"&gt;Branch:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboBranch"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr id="trBranchDepartment"&gt;
            &lt;th&gt;&lt;label for="cboDepartment"&gt;Department:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDepartment"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblQuoteClient"&gt;Optionally, specify a Client for this Quotation&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboQuoteClient"&gt;Client:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboQuoteClient"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr advancedId="Dealer"&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblDealer"&gt;Specify the Dealer and Employee&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="Dealer"&gt;
            &lt;th&gt;&lt;label for="cboDealer"&gt;Dealer:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDealer"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="Dealer"&gt;
            &lt;th&gt;&lt;label for="`"&gt;Employee:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDealerEmployee"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr advancedId="Broker"&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblBroker"&gt;Specify the Broker and Employee&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="Broker"&gt;
            &lt;th&gt;&lt;label for="cboBroker"&gt;Broker:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboBroker"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="Broker"&gt;
            &lt;th&gt;&lt;label for="`"&gt;Employee:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboBrokerEmployee"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAccountType"&gt;Select an Account Type&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboAccountType"&gt;Account Type:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboAccountType"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboAccountTypePromotion"&gt;Promotion:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboAccountTypePromotion"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr advancedId="AccountManager"&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAccountManager"&gt;Account Manager&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="AccountManager"&gt;
            &lt;th&gt;&lt;label for="cboAccountManagerUser"&gt;Manager:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboAccountManagerUser"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr advancedId="Pool"&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblPool"&gt;Pool&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="Pool"&gt;
            &lt;th&gt;&lt;label for="cboPool"&gt;Pool:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboPool"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Clients --&gt;
    &lt;div id="pageClients" class="is-tab-page" style="display:flex; flex-direction:column"&gt;
      &lt;!-- Top Panel --&gt;
      &lt;div&gt;
        &lt;table class="is-form"&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label id="lblClientSearch"&gt;Search for an existing Client or add a new Client&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;button id="cmdNewClientIndividual" class="is-button" icon="Applicant|Add"&gt;New Individual&lt;/button&gt;&lt;button id="cmdNewClientOrganisation" class="is-button" icon="UserGroup|Add"&gt;New Organisation&lt;/button&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;input id="txtClientSearch"&gt;&lt;/th&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th&gt;&lt;label id="lblClients"&gt;Account Clients&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;!-- Bottom Panel --&gt;
      &lt;div style="flex-grow:2; display:flex; flex-direction:row; position:relative"&gt;
        &lt;!-- Grid --&gt;
        &lt;div style="flex-grow:1; position:relative"&gt;
          &lt;div id="gridClients" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;

          &lt;!-- Search Results Panel (fake modal form) --&gt;
        &lt;div id="divSearchResults" style="position:absolute; max-width:480px; width:100%; right:0; top:0; bottom:0; margin-top:-32px"&gt;
          &lt;div id="gridSearchResults" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Security --&gt;
    &lt;div id="pageSecurity" class="is-tab-page" style="display:flex; flex-direction:column"&gt;
      &lt;!-- Top Panel --&gt;
      &lt;div&gt;        
        &lt;div id="gridSecurityItems" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;

      &lt;!-- Bottom Panel --&gt;
      &lt;div style="flex-grow:2"&gt;
         &lt;h1&gt;Not Implemented&lt;/h1&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Name --&gt;
    &lt;div id="pageName" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblName"&gt;Enter the Name to appear on the Account Contract&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDescription"&gt;Enter the Account Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtDescription"&gt;Description:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDescription"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr advancedId="PurposeSourceRegion"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPurpose"&gt;Enter the Purpose, Source and Region for this Account&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="PurposeSourceRegion"&gt;
          &lt;th&gt;&lt;label for="cboPurpose"&gt;Purpose:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboPurpose"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="PurposeSourceRegion"&gt;
          &lt;th&gt;&lt;label for="cboSource"&gt;Source:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboSource"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="PurposeSourceRegion"&gt;
          &lt;th&gt;&lt;label for="cboRegion"&gt;Region:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRegion"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr advancedId="Ledger"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblLedger"&gt;Ledger&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Ledger"&gt;
          &lt;th&gt;&lt;label for="cboLedger"&gt;Ledger:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboLedger"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr advancedId="Insurance"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblInsurance"&gt;Account Related Insurance details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Insurance"&gt;
          &lt;th&gt;&lt;label for="cboInsurer"&gt;Insurer:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInsurer"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Insurance"&gt;
          &lt;th&gt;&lt;label for="cboInsurancePolicyType"&gt;Policy Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInsurancePolicyType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Insurance"&gt;
          &lt;th&gt;&lt;label for="txtInsurancePolicyNumber"&gt;Policy No.:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtInsurancePolicyNumber"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblNotes"&gt;Notes&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="txtNotes"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Financial --&gt;
    &lt;div id="pageFinancial" class="is-tab-page"&gt;
      &lt;div class="is-dock-fill"&gt;
        &lt;div&gt;
          &lt;table class="is-form"&gt;
            &lt;tbody id="afFinancial"&gt;&lt;/tbody&gt;
          &lt;/table&gt;
        &lt;/div&gt;

        &lt;div id="wbAccountSummary"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Other --&gt;
    &lt;div id="pageOther" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblReviewDate"&gt;Enter the Review Date&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateReview"&gt;Review&amp;nbsp;Date:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateReview"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblStatement"&gt;Statements&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboStatementCycle"&gt;Frequency:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboStatementCycle"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateStatementFirst"&gt;First&amp;nbsp;Date:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateStatementFirst"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPaymentDetailsIncoming"&gt;Incoming Payment details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tbody id="apdPaymentDetailsIncoming"&gt;&lt;/tbody&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPaymentDetailsOutgoing"&gt;Outgoing Payment details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tbody id="apdPaymentDetailsOutgoing"&gt;&lt;/tbody&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblInterestTransferTo"&gt;Select the Account to Transfer Interest to&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboInterestTransferToAccount"&gt;Transfer To:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInterestTransferToAccount"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblMaturityInstructions"&gt;Maturity Instructions&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboMaturityInstruction"&gt;Instruction:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboMaturityInstruction"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblMaturityReinvestment"&gt;Reinvestment details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numMaturityValue"&gt;Reinvest:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numMaturityValue"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboMaturityAccountType"&gt;To Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboMaturityAccountType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboMaturityAccount"&gt;Or Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboMaturityAccount"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPaymentDetailsMaturity"&gt;Repayment details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboMaturityPaymentType"&gt;Pay Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboMaturityPaymentType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboMaturityTransferToAccount"&gt;Maturity Transfer To:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboMaturityTransferToAccount"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tbody id="apdPaymentDetailsMaturity"&gt;&lt;/tbody&gt;

      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Disbursements --&gt;
    &lt;div id="pageDisbursements" class="is-tab-page" style="display:flex; flex-direction:column"&gt;
      &lt;!-- Top Panel --&gt;
      &lt;div&gt;
        &lt;div id="gridDisbursements" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;

      &lt;!-- Bottom Panel --&gt;
      &lt;div style="flex-grow:2"&gt;
         &lt;h1&gt;Not Implemented&lt;/h1&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- User Defined --&gt;
    &lt;div id="pageUserDefined"&gt;
      &lt;div id="phUserDefined" class="is-dock-fill"&gt;&lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Finalise --&gt;
    &lt;div id="pageFinalise" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDates"&gt;Enter dates the Account was Quoted, Accepted and Signed&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateQuoted"&gt;Quoted:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateQuoted"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateAccepted"&gt;Accepted:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateAccepted"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateSigned"&gt;Signed:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateSigned"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCode"&gt;Enter the Account's code or leave blank to automatically assign a code&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAccountId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAccountId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtExternalId"&gt;External Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtExternalId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPrintContract"&gt;?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkPrintContract" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblQuote"&gt;Hold as a 'Quote' or begin the acceptance process?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkQuote" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkQuoteReady" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="cboQuoteNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboQuoteNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;
    &lt;button id="cmdPrint" class="is-button" icon="DocumentType_PDF" style="float:left" title="Print Quotation"&gt;Print&lt;/button&gt;
    &lt;button id="cmdOpen" class="is-button" icon="Account|Add" style="float:left" title="Open in the New Account wizard"&gt;Create Account&lt;/button&gt;

    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;&amp;lt; Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next &amp;gt;&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Finish&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;

&lt;script&gt;
// Record
var mRecord;
var mRecord_Account;
var mRecord_Clients;
var mRecord_Disbursements;
var mRecord_SecurityItems;
var mRecord_Page_Other;
var mRecord_Page_Name;

var mPreservedAccountTypePromotionId = "";

// Global Collections
var mAccountRoles;

// Controls
var C = {
  // General
  lblProductType: null,
  blProductTypes: null,

  tbProductType: null,
  tbGeneral: null,

  lblAccountType: null,
  cboAccountType: null,
  cboAccountTypePromotion: null,

  lblQuoteClient: null,
  cboQuoteClient: null,

  lblBranch: null,
  cboBranch: null,
  cboDepartment: null,

  lblDealer: null,
  cboDealer: null,
  cboDealerEmployee: null,

  lblBroker: null,
  cboBroker: null,
  cboBrokerEmployee: null,

  lblAccountManager: null,
  cboAccountManagerUser: null,

  lblPool: null,
  cboPool: null,

  // Clients
  lblClientSearch: null,
  cmdNewClientIndividual: null,
  cmdNewClientOrganisation: null,
  txtClientSearch: null,
  divSearchResults: null,
  gridClientSearch: null,

  lblClients: null,
  gridClients: null,

  // Security
  gridSecurityItems: null,

  // Financial
  afFinancial: null,
  wbAccountSummary: null,

  // Name
  lblName: null,
  txtName: null,

  lblDescription: null,
  txtDescription: null,

  lblPurpose: null,
  cboPurpose: null,
  cboSource: null,
  cboRegion: null,

  lblLedger: null,
  cboLedger: null,

  lblInsurance: null,
  cboInsurer: null,
  cboInsurancePolicyType: null,
  txtInsurancePolicyNumber: null,

  lblNotes: null,
  txtNotes: null,

  // Other
  lblReviewDate: null,
  dateReview: null,

  lblStatement: null,
  cboStatementCycle: null,
  dateStatementFirst: null,

  lblPaymentDetailsOutgoing: null,
  apdPaymentDetailsOutgoing: null,

  lblInterestTransferTo: null,
  cboInterestTransferToAccount: null,

  lblMaturityInstructions: null,
  cboMaturityInstruction: null,

  lblMaturityReinvestment: null,
  numMaturityValue: null,
  cboMaturityAccountType: null,
  cboMaturityAccount: null,

  lblPaymentDetailsIncoming: null,
  apdPaymentDetailsIncoming: null,

  lblPaymentDetailsMaturity: null,
  cboMaturityPaymentType: null,
  cboMaturityTransferToAccount: null,
  apdPaymentDetailsMaturity: null,

  // Disbursements
  gridDisbursements: null,

  //   User Defined
  phUserDefined: null,

  // Finalise
  lblDates: null,
  dateQuoted: null,
  dateAccepted: null,
  dateSigned: null,

  lblCode: null,
  txtAccountId: null,
  txtExternalId: null,

  lblPrintContract: null,
  chkPrintContract: null,

  lblQuote: null,
  chkQuote: null,
  chkQuoteReady: null,
  cboQuoteNotes: null,
}

// Form
var frmMain;
var tabWizard;

// Wizard Buttons
var cmdCancel;
var cmdBack;
var cmdNext;
var cmdFinish;

var cmdAdvanced;
var cmdPrint;
var cmdOpen;

// Other
var mAdvancedVisible = false;
var mAccountType;
var mAccountTypePromotionChanged = false;
var mCalculationTimer;
var mClientSearchText;
var mClientSearchResults;
var mEditDisbursementIndex;
var mEditSecurityItemIndex;
var mFinancialInitialise = true;
var mInitialLoad = false;
var mInitialisedOk = false;
var mLastDefaultName;
var mLastDefaultDescription;
var mProductType;
var mPromotions;
var mQuoteMode;

// ==========
// Initialise
// ==========
$(function () {
  // Mobile optimisations
  $(window).resize(Form_Resize);

  // --------
  // Controls
  // --------
  //   General
  C.lblProductType = widget.UI.Label("lblProductType", {});
  C.blProductTypes = widget.UI.ButtonList("blProductTypes", {
    allowBlank: false,

    onChange: blProductTypes_Change
  });

  C.tbProductType = $("#tbProductType");
  C.tbGeneral = $("#tbGeneral");

  C.lblAccountType = widget.UI.Label("lblAccountType", {});
  C.cboAccountType = widget.UI.DBCombo("cboAccountType", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboAccountType_Change,
  });
  C.cboAccountTypePromotion = widget.UI.DBCombo("cboAccountTypePromotion", {
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboAccountTypePromotion_Change,
  });

  C.lblQuoteClient = widget.UI.Label("lblQuoteClient", {});
  C.cboQuoteClient = widget.UI.DBCombo("cboQuoteClient", {
    allowBlank: true,
    limitToList: true,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblBranch = widget.UI.Label("lblBranch", {});
  C.cboBranch = widget.UI.DBCombo("cboBranch", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboBranch_Change,
  });
  C.cboDepartment = widget.UI.DBCombo("cboDepartment", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblDealer = widget.UI.Label("lblDealer", {});
  C.cboDealer = widget.UI.DBCombo("cboDealer", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboDealer_Change,
  });
  C.cboDealerEmployee = widget.UI.DBCombo("cboDealerEmployee", {
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

  C.lblBroker = widget.UI.Label("lblBroker", {});
  C.cboBroker = widget.UI.DBCombo("cboBroker", {
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboBroker_Change,
  });
  C.cboBrokerEmployee = widget.UI.DBCombo("cboBrokerEmployee", {
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

  C.lblAccountManager = widget.UI.Label("lblAccountManager", {});
  C.cboAccountManagerUser = widget.UI.DBCombo("cboAccountManagerUser", {
    allowBlank: false,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

  C.lblPool = widget.UI.Label("lblPool", {});
  C.cboPool = widget.UI.DBCombo("cboPool", {
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  //   Clients
  C.lblClientSearch = widget.UI.Label("lblClientSearch", {
    tooltipText: "Clicking in the search field will show existing search results if a search has already been performed.",
  });
  C.cmdNewClientIndividual = $("#cmdNewClientIndividual");
  C.cmdNewClientIndividual.click(NewClientIndividual);
  C.cmdNewClientOrganisation = $("#cmdNewClientOrganisation");
  C.cmdNewClientOrganisation.click(NewClientOrganisation);
  C.txtClientSearch = widget.UI.TextBox("txtClientSearch", {
    blankTip: "Search ID, name, date of birth, phone number, email, account ID",
    changeWhileTyping: true,
    maxLength:200,
    specialType: "search",
    width:"100%",

    onChange: txtClientSearch_Change,
    onEnterKey: ClientSearch,
    onFocus: txtClientSearch_Focus,
  });
  C.divSearchResults = $("#divSearchResults");
  widget.UI.StyleAsModal(C.divSearchResults, { title: "Search Results", tool: true, showClose: true });

  C.lblClients = widget.UI.Label("lblClients", {
    tooltipText: "You can add Clients directly to the grid, use the buttons above to add new Clients or Search for Clients and click the '+' button or 'Add all Selected Clients' button in the search results grid.\n\nClients can be deleted from the Account or repositioned using the buttons below the grid.\n\nUse the dropdown in the 'Role' column to change a Client's Account Role.",
  });

  //   Financial
  C.afFinancial = widget.UI.AccountFinancial("afFinancial", {
    visible: false, // Hide until first calculated
    onAction: afFinancial_Action,
    onChange: afFinancial_Change,
  });
  C.wbAccountSummary = widget.UI.PreviewPane("wbAccountSummary", {});

  //   Name
  C.lblName = widget.UI.Label("lblName", {});
  C.txtName = widget.UI.TextBox("txtName", {
    allowBlank: false,
    maxLength: 100,
        
    onButtonClick: txtName_ButtonClick,
    onChange: txtName_Change,
  });
  C.txtName.ButtonsDefine([{id: "Reset", icon: "Reset", tooltipText: "Reset to default Name"}]);

  C.lblDescription = widget.UI.Label("lblDescription", {});
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 255,
    multiLine: true,
    rows: 4,
        
    onButtonClick: txtDescription_ButtonClick,
    onChange: txtDescription_Change,
  });
  C.txtDescription.ButtonsDefine([{id: "Reset", icon: "Reset", tooltipText: "Reset to default Description"}]);

  C.lblPurpose = widget.UI.Label("lblPurpose", {});
  C.cboPurpose = widget.UI.InformationListComboBox("cboPurpose", {
    maxLength: 50,
  });
  C.cboSource = widget.UI.InformationListComboBox("cboSource", {
    maxLength: 50,
  });
  C.cboRegion = widget.UI.InformationListComboBox("cboRegion", {
    maxLength: 50,
  });

  C.lblLedger = widget.UI.Label("lblLedger", {});
  C.cboLedger = widget.UI.InformationListComboBox("cboLedger", {
    maxLength: 20,
  });

  C.lblInsurance = widget.UI.Label("lblInsurance", {});
  C.cboInsurer = widget.UI.DBCombo("cboInsurer", {
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.cboInsurancePolicyType = widget.UI.InformationListComboBox("cboInsurancePolicyType", {
    maxLength: 50,
  });
  C.txtInsurancePolicyNumber = widget.UI.TextBox("txtInsurancePolicyNumber", {
    maxLength: 20,
  });

  C.lblNotes = widget.UI.Label("lblNotes", {});
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    maxLength: 32767,
    multiLine: true,
    rows:8,
  });

  //   Other
  C.lblReviewDate = widget.UI.Label("lblReviewDate", {});
  C.dateReview = widget.UI.DateBox("dateReview", {});

  C.lblStatement = widget.UI.Label("lblStatement", {});
  C.cboStatementCycle = widget.UI.DateCycleComboBox("cboStatementCycle", {
    allowBlank: false,
    isFrequency: true,
    listOther: "None,On Demand", // Prevents fetching description for non-frequency values

    onChange: cboStatementCycle_Change,
  });
  C.dateStatementFirst = widget.UI.DateBox("dateStatementFirst", {
    allowBlank: false,
  });

  C.lblPaymentDetailsOutgoing = widget.UI.Label("lblPaymentDetailsOutgoing", {});
  C.apdPaymentDetailsOutgoing = widget.UI.AccountOutgoingPaymentDetails("apdPaymentDetailsOutgoing", {
    allowBlank: false,
  });

  C.lblInterestTransferTo = widget.UI.Label("lblInterestTransferTo", {});
  C.cboInterestTransferToAccount = widget.UI.DBCombo("cboInterestTransferToAccount", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblMaturityInstructions = widget.UI.Label("lblMaturityInstructions", {});
  C.cboMaturityInstruction = widget.UI.ComboBox("cboMaturityInstruction", {
    allowBlank: false,
    limitToList: true,

    onChange: cboMaturityInstruction_Change,
  });

  C.lblMaturityReinvestment = widget.UI.Label("lblMaturityReinvestment", {
    tooltipText: "If specified, the Account selected will take precendence over the Account Type.",
  });
  C.numMaturityValue = widget.UI.NumberBox("numMaturityValue", {
    allowBlank: false,
  });
  C.cboMaturityAccountType = widget.UI.DBCombo("cboMaturityAccountType", {
    allowBlank: true,
    maxLength: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.cboMaturityAccount = widget.UI.DBCombo("cboMaturityAccount", {
    allowBlank: true,
    maxLength: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblPaymentDetailsIncoming = widget.UI.Label("lblPaymentDetailsIncoming", {});
  C.apdPaymentDetailsIncoming = widget.UI.AccountIncomingPaymentDetails("apdPaymentDetailsIncoming", {
    allowBlank: true,
  });

  C.lblPaymentDetailsMaturity = widget.UI.Label("lblPaymentDetailsMaturity", {});
  C.cboMaturityPaymentType = widget.UI.ComboBox("cboMaturityPaymentType", {
    allowBlank: false,
    limitToList: true,

    onChange: cboMaturityPaymentType_Change,
  });
  C.cboMaturityTransferToAccount = widget.UI.DBCombo("cboMaturityTransferToAccount", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.apdPaymentDetailsMaturity = widget.UI.AccountOutgoingPaymentDetails("apdPaymentDetailsMaturity", {
    allowBlank: false,
    
    onPaymentMethodChange: apdPaymentDetailsMaturity_PaymentMethodChange,
  });

  //   User Defined
  C.phUserDefined = widget.UI.ParametersHost("phUserDefined", {});

  //   Finalise
  C.lblDates = widget.UI.Label("lblDates", {});
  C.dateQuoted = widget.UI.DateBox("dateQuoted", {
    allowBlank: false,
  });
  C.dateAccepted = widget.UI.DateBox("dateAccepted", {});
  C.dateSigned = widget.UI.DateBox("dateSigned", {});

  C.lblPrintContract = widget.UI.Label("lblPrintContract", {
    tooltipText: "This document can be printed at any time by viewing the new Account record.",
  });
  C.chkPrintContract = widget.UI.CheckBox("chkPrintContract", {
    caption: "Generate a Contract document?",
  });

  C.lblCode = widget.UI.Label("lblCode", {});
  C.txtAccountId = widget.UI.TextBox("txtAccountId", {
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.txtExternalId = widget.UI.TextBox("txtExternalId", {
    maxLength: 40,
  });

  C.lblQuote = widget.UI.Label("lblQuote", {
    tooltipText: "If you choose not to hold this Account as a 'Quote', the acceptance process will begin upon clicking the 'Finish' button.",
  });
  C.chkQuote = widget.UI.CheckBox("chkQuote", {
    caption: "Hold as a Quote?",
    
    onChange: chkQuote_Change,    
  });
  C.chkQuoteReady = widget.UI.CheckBox("chkQuoteReady", {
    caption: "Is Quote Ready to be Opened?",
  });
  C.cboQuoteNotes = widget.UI.InformationListComboBox("cboQuoteNotes", {
    maxLength: 50,
  });

  // Grids
  C.gridClients = widget.UI.Grid("gridClients", {
    allowAddRows: true,
    maxNewRows: 10,
    stickyHeader: true,
    showContextMenu: false,

    onBeforeCellUpdate: gridClients_BeforeCellUpdate,
    onInitialiseRow: gridClients_InitialiseRow,
    onAfterRowActivate: gridClients_AfterRowActivate,
    onAction: gridClients_Action,
    onRowAdd: gridClients_RowAdd,
  });
  $("#gridClients").mousedown(function () {
    // Close Client Search
    C.divSearchResults.hide();
  });

  C.gridSecurityItems = widget.UI.Grid("gridSecurityItems", {
    stickyHeader: true,

    onInitialiseRow: gridSecurityItems_InitialiseRow,
    onAfterRowActivate: gridSecurityItems_AfterRowActivate,
    onAction: gridSecurityItems_Action,
    onRowDrilldown: gridSecurityItems_RowDrilldown,
  });

  C.gridDisbursements = widget.UI.Grid("gridDisbursements", {
    stickyHeader: true,
    showRowSelectors: true,
    rowNumbering: true,
    allowMultiRowSelect: true,

    onInitialiseRow: gridDisbursements_InitialiseRow,
    onAfterRowActivate: gridDisbursements_AfterRowActivate,
    onAction: gridDisbursements_Action,
    onRowDrilldown: gridDisbursements_RowDrilldown,
  });

  // Create Widget form
  frmMain = new widget.UI.Form("frmMain", { visible:false });

  // Create Tabs
  tabWizard = new widget.UI.Tabs("tabWizard", {style: "wizard"});

  // Handle resize
  $(window).resize(Form_Resize);

  // Disable Close Button (this causes the 'FormClose' notification action to be invoked instead)
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler)

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdBack = $("#cmdBack");
  cmdNext = $("#cmdNext");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(function() { Form_ExecuteAction("Cancel"); });
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(AdvancedToggle);

  cmdPrint = $("#cmdPrint");
  cmdPrint.click(PrintQuotation);

  cmdOpen = $("#cmdOpen");
  cmdOpen.click(function () {
    // Add Client
    if (C.cboQuoteClient.Text()) AddClient(C.cboQuoteClient.Text());

    // Clear Quote Mode
    mQuoteMode = false;

    // Reset back to first page
    Fields_Update();
    tabWizard_Refresh(0);
  });

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults

  // Other
  C.phUserDefined.Tag = null;

  // Set Tab
  tabWizard.SelectedTabId("General");

  // Resize
  Form_Resize();

  // Load Record (i.e., initialise wizard)
  Record_Load();
}

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mAccountTypePromotionChanged = false;
  mClientSearchResults = null;
  mRecord = null;
  mRecord_Account = null;
  mRecord_Clients = null;
  mRecord_Disbursements = null;
  mRecord_SecurityItems = null;
  mRecord_Page_Name = null;
  mRecord_Page_Other = null;
  mQuoteMode = false;
  mInitialLoad = false;

  // Hide content
  frmMain.Visible(false);

  // Block UI
  widget.UI.Block("Initialising, please wait...");

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);
      mRecord_Account = mRecord.Account;
      mRecord_Clients = mRecord_Account.Clients;
      mRecord_Disbursements = mRecord_Account.Disbursements;
      mRecord_SecurityItems = mRecord_Account.SecurityItems;
      mQuoteMode = mRecord.QuoteMode;
      
      // Global Collections
      mAccountRoles = mRecord.AccountRoles;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mAccountRoles, "AccountRoleId");
      widget.ArrayAllowLookupById(mRecord.AccountTypes, "AccountTypeId");

      // Do not re-initialise Financial details for existing Accounts, i.e., Fields_Load will populate these details
      if (mRecord_Account.AccountId) mFinancialInitialise = false;

      // Load Fields
      Fields_Load();
      
      // Initialised Ok
      mInitialisedOk = true;
    },

    // Fail
    function (message) {
      widget.UI.MsgBoxAlert("fail: " + message);
      Fields_Load();
    }
  );
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  // Initial Load
  mInitialLoad = true;

  if (mRecord) {
    // General
    blProductTypes_Refresh();
    C.blProductTypes.SelectedItemId(mRecord_Account.ProductTypeId);
    C.cboAccountType.Text(mRecord_Account.AccountTypeId);
    mPreservedAccountTypePromotionId = mRecord_Account.AccountTypePromotionId; // Prevent Promotion being cleared when list is asynchronously refreshed

    C.cboBranch.Text(mRecord_Account.BranchId);
    C.cboDepartment.Text(mRecord_Account.DepartmentId);
    
    C.cboQuoteClient.Text(mRecord.QuotationClientId);

    C.cboDealer.Text(mRecord_Account.DealerId);
    C.cboDealerEmployee.Text(mRecord_Account.DealerEmployeeId);

    C.cboBroker.Text(mRecord_Account.BrokerId);
    C.cboBrokerEmployee.Text(mRecord_Account.BrokerEmployeeId);

    C.cboAccountManagerUser.Text(mRecord_Account.AccountManagerUserId);

    C.cboPool.Text(mRecord_Account.PoolId);
    
    // Financial
    if (mFinancialInitialise) {
      // Not initialised yet
    }
    else {
      C.afFinancial.FromAccountCalcJson(mRecord_Account.AccountCalcJson);
      if (mRecord_Account.AccountId) C.afFinancial.SetAccountId(mRecord_Account.AccountId);
      C.afFinancial.Visible(true);
    }

    // Name
    C.txtName.Text(mRecord_Account.Name);
    C.txtDescription.Text(mRecord_Account.Description);

    C.cboLedger.Text(mRecord_Account.Ledger);
    C.cboPurpose.Text(mRecord_Account.Purpose);
    C.cboSource.Text(mRecord_Account.Source);
    C.cboRegion.Text(mRecord_Account.Region);

    C.cboInsurer.Text(mRecord_Account.InsurerId);
    C.cboInsurancePolicyType.Text(mRecord_Account.InsurancePolicyType);
    C.txtInsurancePolicyNumber.Text(mRecord_Account.InsurancePolicyNumber);

    C.txtNotes.Text(mRecord_Account.Notes);

    // Other
    C.dateReview.Value(mRecord_Account.DateReview);

    C.cboStatementCycle.Text(mRecord_Account.StatementCycle);
    C.dateStatementFirst.Value(mRecord_Account.StatementDateFirst);

    C.cboInterestTransferToAccount.Text(mRecord_Account.InterestTransferToAccountId);

    C.cboMaturityInstruction.Text(mRecord_Account.MaturityInstructionText);
    C.numMaturityValue.Value(mRecord_Account.MaturityValue);
    C.cboMaturityAccountType.Text(mRecord_Account.MaturityAccountTypeId);
    C.cboMaturityAccount.Text(mRecord_Account.MaturityAccountId);
    C.cboMaturityPaymentType.Text(mRecord_Account.MaturityPaymentTypeText);
    C.cboMaturityTransferToAccount.Text(mRecord_Account.MaturityTransferToAccountId);

    // Payment Details
    // NOTE: These will be overidden later when the Options page is refreshed, but this ensures that Fields_Save saves the current data correctly.
    C.apdPaymentDetailsIncoming.FromBankingDetailsJson(mRecord_Account.BankingDetailsIncomingJson);
    C.apdPaymentDetailsOutgoing.FromBankingDetailsJson(mRecord_Account.BankingDetailsOutgoingJson);
    C.apdPaymentDetailsMaturity.FromBankingDetailsJson(mRecord_Account.BankingDetailsMaturityJson);

    // Finalise
    C.dateQuoted.Value(mRecord_Account.DateQuoted);
    C.dateAccepted.Value(mRecord_Account.DateAccepted);
    C.dateSigned.Value(mRecord_Account.DateSigned);
    
    C.chkQuoteReady.Value(mRecord_Account.QuoteReady);
    C.cboQuoteNotes.Text(mRecord_Account.QuoteNotes);

    C.txtAccountId.Text(mRecord_Account.AccountId);

    C.txtExternalId.Text(mRecord_Account.ExternalId);
  }

  // Initial Load
  mInitialLoad = false;

  // Unblock UI
  widget.UI.Unblock();

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

// ===========
// Save Fields
// ===========
function Fields_Save(fieldUpdated) {
  // General
  mRecord_Account.ProductTypeId = C.blProductTypes.SelectedItemId();
  mRecord_Account.AccountTypeId = C.cboAccountType.Text();
  mRecord_Account.AccountTypePromotionId = C.cboAccountTypePromotion.Text();

  mRecord_Account.BranchId = C.cboBranch.Text();
  mRecord_Account.DepartmentId = C.cboDepartment.Text();

  mRecord_Account.DealerId = C.cboDealer.Text();
  mRecord_Account.DealerEmployeeId = C.cboDealerEmployee.Text();

  mRecord_Account.BrokerId = C.cboBroker.Text();
  mRecord_Account.BrokerEmployeeId = C.cboBrokerEmployee.Text();

  mRecord_Account.AccountManagerUserId = C.cboAccountManagerUser.Text();

  mRecord_Account.PoolId = C.cboPool.Text();

  // Financial
  if (mFinancialInitialise) {
    // Financials not yet initialised
  }
  else {
    // Get Account Calc
    var accountCalc = C.afFinancial.ToAccountCalc();

    // Update properties not in the AccountFinancial control
    accountCalc.AccountTypePromotionId = C.cboAccountTypePromotion.Text();
    accountCalc.StatementCycle = C.cboStatementCycle.Text();
    accountCalc.StatementDateNext = C.dateStatementFirst.Value();

    // Set Field Updated (allows calculation to do special stuff like keep dates in sync)
    accountCalc.FieldUpdated = fieldUpdated;

    // Convert to JSON
    mRecord_Account.AccountCalcJson = JSON.stringify(accountCalc);
  }

  // Name
  mRecord_Account.Name = C.txtName.Text();
  mRecord_Account.Description = C.txtDescription.Text();

  mRecord_Account.Ledger = C.cboLedger.Text();
  mRecord_Account.Purpose = C.cboPurpose.Text();
  mRecord_Account.Source = C.cboSource.Text();
  mRecord_Account.Region = C.cboRegion.Text();

  mRecord_Account.InsurerId = C.cboInsurer.Text();
  mRecord_Account.InsurancePolicyType = C.cboInsurancePolicyType.Text();
  mRecord_Account.InsurancePolicyNumber = C.txtInsurancePolicyNumber.Text();

  mRecord_Account.Notes = C.txtNotes.Text();

  // Other
  mRecord_Account.DateReview = C.dateReview.Value();

  mRecord_Account.StatementCycle = C.cboStatementCycle.Text();
  mRecord_Account.StatementDateFirst = C.dateStatementFirst.Value();

  mRecord_Account.InterestTransferToAccountId = C.cboInterestTransferToAccount.Text();

  mRecord_Account.MaturityInstructionText = C.cboMaturityInstruction.Text();
  mRecord_Account.MaturityValue = C.numMaturityValue.Value();
  mRecord_Account.MaturityAccountTypeId = C.cboMaturityAccountType.Text();
  mRecord_Account.MaturityAccountId = C.cboMaturityAccount.Text();
  mRecord_Account.MaturityPaymentTypeText = C.cboMaturityPaymentType.Text();
  mRecord_Account.MaturityTransferToAccountId = C.cboMaturityTransferToAccount.Text();

  mRecord_Account.BankingDetailsIncomingJson = C.apdPaymentDetailsIncoming.ToBankingDetailsJson();
  mRecord_Account.BankingDetailsOutgoingJson = C.apdPaymentDetailsOutgoing.ToBankingDetailsJson();
  mRecord_Account.BankingDetailsMaturityJson = C.apdPaymentDetailsMaturity.ToBankingDetailsJson();

  // User Defined
  if (mAccountType.ShowUserDefinedPage &amp;&amp; C.phUserDefined.Tag) {
    mRecord_Account.UserDataJson = JSON.stringify(C.phUserDefined.GetParameterValuesWithTypes());
  }

  // Finalise
  mRecord_Account.DateQuoted = C.dateQuoted.Value();
  mRecord_Account.DateAccepted = C.dateAccepted.Value();
  mRecord_Account.DateSigned = C.dateSigned.Value();
  
  mRecord_Account.QuoteNotes = C.cboQuoteNotes.Text();
  mRecord_Account.QuoteReady = C.chkQuoteReady.Value();

  mRecord_Account.NewAccountId = C.txtAccountId.Text();
  mRecord_Account.ExternalId = C.txtExternalId.Text();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord.Refinance) {
    widget.SetHeading("Refinance of Account '" + mRecord.RefinanceCreatedFromAccountId + "' to Account '" + mRecord_Account.AccountId + "'");
  }
  else if (mQuoteMode) {
    widget.SetHeading("Account Quotation");
  }
  else if (mRecord_Account &amp;&amp; mRecord_Account.AccountId) {
    widget.SetHeading("Edit Quote Account '" + mRecord_Account.AccountId + "'");
  }
  else {
    widget.SetHeading("New Account");
  }

  // Information Lists
  if (mRecord) {
    C.cboInsurancePolicyType.SetComboFromInformationList(mRecord.PolicyTypeInformationListId, true);
    C.cboLedger.SetComboFromInformationList("AccountLedger", true);
    C.cboRegion.SetComboFromInformationList(mRecord.RegionInformationListId, true);
    C.cboQuoteNotes.SetComboFromInformationList("AccountQuoteNote", true);
  }

  // Lists
  if (mRecord) {
    C.cboQuoteClient.RefreshFromStandardRange("Clients");
    if (mRecord.AddOnsBranch) C.cboBranch.RefreshFromStandardRange("Branches");
    C.cboDepartment.RefreshFromStandardRange("Departments");
    if (mRecord.AddOnsExternalPartyDealers) C.cboDealer.RefreshFromStandardRange("ExternalPartiesDealers");
    if (mRecord.AddOnsExternalPartyBrokers) C.cboBroker.RefreshFromStandardRange("ExternalPartiesBrokers");
    C.cboAccountManagerUser.RefreshFromStandardRange("AccountManagers");
    if (mRecord.AddOnsPool) C.cboPool.RefreshFromStandardRange("Pools");

    if (mRecord.AddOnsExternalPartyInsurers) C.cboInsurer.RefreshFromStandardRange("ExternalPartiesInsurers");
    if (mRecord.AddOnsPromotions) cboAccountTypePromotions_Refresh();
  }

  // Controls
  if (mRecord) {
    blProductTypes_Change();

    C.lblQuoteClient.VisibleRow(mQuoteMode);
    C.cboQuoteClient.VisibleRow(mQuoteMode);

    if (mRecord.AddOnsExternalPartyDealers) {
      cboDealer_Change();
    }

    if (mRecord.AddOnsExternalPartyBrokers) {
      cboBroker_Change();
    }

    C.txtExternalId.VisibleRow(mRecord.ShowExternalId);

    C.afFinancial.StdTransWidgetId(mRecord.StdTransWidgetId);    
    if (mRecord.Refinance) C.afFinancial.SetRefinance(true);
    
    C.txtAccountId.ReadOnly(!mRecord.CanUpdateAccountId);

    if (mRecord.CanUpdateStatusQuoteToOpen) {
      C.chkQuote.ReadOnly(false);
    }
    else {
      C.chkQuote.ReadOnly(true);
    }
    
    chkQuote_Change();

    // Initialise Advanced
    AdvancedInitialise();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

  // Show content
  frmMain.Visible(mRecord != null);

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Mobile optimisations
  if (window.innerWidth &lt; 500) {
    C.wbAccountSummary.Element().css("min-height", "320px");
  }
  else {
    C.wbAccountSummary.Element().css("min-height", "unspecified");
  }

  // General

  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (!mInitialisedOk) {
    // Cancel immediately
    tabWizard_Cancel_Finalise();
  }
  else if (mRecord.Refinance) {
    var messageHtml = "Do you want to cancel the Refinance of Account '" + mRecord.RefinanceCreatedFromAccountId + "' to Account '" + mRecord_Account.AccountId + "'?";    
    var List = [];
    List.push({ key: "DELETE", caption: "Delete '" + mRecord_Account.AccountId + "'", details: "Delete Account '" + mRecord_Account.AccountId + "' and reopen Account '" + mRecord.RefinanceCreatedFromAccountId + "'.", icon: "Trash" });
    List.push({ key: "LEAVE", caption: "Leave '" + mRecord_Account.AccountId + "'", details: "Leave '" + mRecord_Account.AccountId + "' as a Quote (any changes made to the newly refinanced Account will be lost).", icon: "AccountStatus_Quote" });
    List.push({ key: "NOTHING", caption: "Do Nothing", details: "Take me back to editing '" + mRecord_Account.AccountId + "'.", icon: "Undo" });
    
    widget.UI.MsgBoxList(messageHtml, List, {}, tabWizard_Cancel_Refinance);
  }
  else if (tabWizard.SelectedTabIndex() != 0 &amp;&amp; !mQuoteMode) {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form without saving your changes?", {}, tabWizard_Cancel_Finalise);
  }
  else {
    // Cancel immediately
    tabWizard_Cancel_Finalise();
  }
}

function tabWizard_Cancel_Refinance(key) {
  switch(key) {
    case "DELETE":
      // Block UI
      widget.UI.Block("Deleting Account, please wait...");
      
      // Delete Account
      widget.GetString("DeleteRefinanceAccount", {}, 
        function() {
          // Refresh Forms
          widget.RefreshParent();
          widget.ActionNotificationSend("AccountRefresh", { accountId: mRecord.RefinanceCreatedFromAccountId }, null, true);
          
          // Close
          tabWizard_Cancel_Finalise();
        },
         
        function(errorMessage) {
          // Unblock UI
          widget.UI.Unblock();
          
          // Error Message
          widget.UI.MsgBoxAlert(errorMessage);
        }
      );
      break;
      
    case "LEAVE":
      tabWizard_Cancel_Finalise();
      break;
      
    default:
      // Ignore
      break;
  }
}

function tabWizard_Cancel_Finalise() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

function tabWizard_UpdateButtons() {
// Back, Next, Finish Buttons Valid?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 0);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
  cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

  // Exceptions
  if (mRecord) {
    // Only show Advanced button on relevant pages
    cmdAdvanced.hide()
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (mRecord.PageGeneralHasAdvanced) cmdAdvanced.show();
        break;

      case "Clients":
        if (mRecord.PageClientsHasAdvanced) cmdAdvanced.show();
        break;

      case "Name":
        if (mRecord.PageNameHasAdvanced) cmdAdvanced.show();
        break;
    }
  }
  else {
    cmdAdvanced.hide();
  }

  // Quote Mode?
  if (mQuoteMode &amp;&amp; tabWizard.SelectedTabId() == "Financial") {
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
    cmdOpen.show();
  }
  else {
    cmdOpen.hide();
  }
  
  // Allow Print Quotation?
  if (tabWizard.SelectedTabId() == "Financial" &amp;&amp; mAccountType &amp;&amp; mAccountType.ShowFinancialPagePrintQuotation) {
    cmdPrint.show();
  }
  else {
    cmdPrint.hide();
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.cboAccountType.WidthResizeFromParent();
      C.cboAccountTypePromotion.WidthResizeFromParent();
      C.cboBranch.WidthResizeFromParent();
      C.cboDepartment.WidthResizeFromParent();
      C.cboDealer.WidthResizeFromParent();
      C.cboDealerEmployee.WidthResizeFromParent();
      C.cboBroker.WidthResizeFromParent();
      C.cboBrokerEmployee.WidthResizeFromParent();
      C.cboAccountManagerUser.WidthResizeFromParent();
      C.cboPool.WidthResizeFromParent();
      break;

    case "Clients":
      C.txtClientSearch.WidthResizeFromParent();

    case "Name":
      C.txtName.WidthResizeFromParent();
      C.txtDescription.WidthResizeFromParent();

      C.cboLedger.WidthResizeFromParent();
      C.cboPurpose.WidthResizeFromParent();
      C.cboSource.WidthResizeFromParent();
      C.cboRegion.WidthResizeFromParent();
      break;

    case "Other":
      C.apdPaymentDetailsIncoming.WidthResizeFromParent();
      C.apdPaymentDetailsOutgoing.WidthResizeFromParent();
      C.apdPaymentDetailsMaturity.WidthResizeFromParent();
      break;

    case "Finalise":
      C.txtExternalId.WidthResizeFromParent();
      C.cboQuoteNotes.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

// ===========
// Wizard Move
// ===========
function tabWizard_Move(direction) {
  var Ok;

  // Validate
  if (direction &gt; 0) {
    tabWizard_Validate(function () { tabWizard_MovePost(direction); });
  }
  else {
    // Can always move backwards
    tabWizard_MovePost(direction);
  }
}

function tabWizard_MovePost(direction) {
  var Ok = true;

  // Find Next Tab to Move To
  if (Ok) {
    var found = false;
    var newTab = tabWizard.SelectedTabIndex();

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "Clients":
          if (!mQuoteMode) found = true;
          break;

        case "Security":
          if (!mQuoteMode &amp;&amp; mAccountType.ShowSecurityPage) found = true;
          break;

        case "Name":
          if (!mQuoteMode) found = true;
          break;

        case "Disbursements":
          if (!mQuoteMode &amp;&amp; mAccountType.ShowDisbursementsPage) found = true;
          break;

        case "Other":
          if (!mQuoteMode) found = true;
          break;

        case "UserDefined":
          if (!mQuoteMode &amp;&amp; mAccountType.ShowUserDefinedPage) found = true;
          break;

        default:
          found = true;
          break;
      }

      // Found?
      if (found) {
        break;
      }
      else if (newTab == tabWizard.TabCount() - 1) {
        // Just in case!
        widget.UI.MsgBoxAlert("tabWizard_MovePost: Tab not handled!");
        break;
      }
    }
    while (true);

    // Refresh the New Tab
    tabWizard_Refresh(newTab);
  }
}

// ===========
// Refresh Tab
// ===========
function tabWizard_Refresh(newTab) {
  // Clear search results so moving to and from the Clients page does not automatically show the results pane
  mClientSearchResults = null;
  C.divSearchResults.hide();

  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "General":
        pageGeneral_Refresh();
        break;

      case "Clients":
        tabWizard_FetchDetails("Clients");
        break;

      case "Security":
        gridSecurityItems_Refresh();
        break;

      case "Financial":
        // Handled below
        break;

      case "Name":
        tabWizard_FetchDetails("Name");
        break;

      case "Other":
        tabWizard_FetchDetails("Other");
        break;

      case "Disbursements":
        gridDisbursements_Refresh();
        break;

      case "UserDefined":
        if (C.phUserDefined.Tag != mAccountType.AccountTypeId) {
          C.phUserDefined.Initialise(mAccountType.UserDefinedParameters);
          C.phUserDefined.UpdateParameterValues(JSON.parse(mRecord_Account.UserDataJson));
          C.phUserDefined.Tag = mAccountType.AccountTypeId;
        }
        break;

      case "Finalise":
        pageFinalise_Refresh();
        break;

      default:
        break;
    }
  }

  // Make Tab it
  tabWizard.SelectedTabIndex(newTab);

  // Tweak fields
  switch(tabWizard.SelectedTabId()) {
    case "Financial":
      // Reload when moving forward or backward since Summary shows fields such as Maturity Instructions
      pageFinancial_Refresh(true);
      break;
  }

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Security":
      var securityStmtMessage = "";
      if (mRecord.SecurityStmtMessage) {
        securityStmtMessage = " (" + mRecord.SecurityStmtMessage + ")";        
      }
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()) + securityStmtMessage + ".");
      break;
  
    default:    
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

  // Back, Next command buttons valid?
  tabWizard_UpdateButtons();

  // Resize Wizard
  tabWizard_Resize();

  // Focus
  switch (tabWizard.SelectedTabId()) {
    default:
      tabWizard.FocusFirst();
      break;
  }
}

// ===============
// Validate Wizard
// ===============
function tabWizard_Validate(validCallback) {
  // Validate
  var Ok = tabWizard.Validate(true);

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (C.blProductTypes.SelectedItemIndex() == -1) {
          C.blProductTypes.Focus();
          Ok = false;
        }
        else if(!mAdvancedVisible) {
          // Mandatory but hidden because advanced
          if(!C.cboBranch.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboBranch.Focus();
          }
          else if(!C.cboDepartment.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboDepartment.Focus();
          }
          else if(!C.cboDealer.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboDealer.Focus();
          }
          else if(!C.cboAccountManagerUser.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboAccountManagerUser.Focus();
          }
        }
        break;

      case "Clients":
        if (mRecord_Clients.length == 0) {
          widget.UI.MsgBoxAlert("You must specify at least one Client for this Account", {}, function () { C.txtClientSearch.Focus(); });
          Ok = false;
        }
        break;

      case "Security":
        // Server-side validation
        break;

      case "Name":
        if (!mAdvancedVisible) {
          // Mandatory but hidden because advanced
          // Product Type specific Information Lists
          if (mProductType) {
            if (!C.cboPurpose.Text() &amp;&amp; !mProductType.AccountPurposeAllowBlank) {
              Ok = false;
              cmdAdvanced.trigger("click");
              C.cboPurpose.Focus();
            }
            else if (!C.cboSource.Text() &amp;&amp; !mProductType.AccountSourceAllowBlank) {
              Ok = false;
              cmdAdvanced.trigger("click");
              C.cboSource.Focus();
            }
          }

          // Other Mandatory fields
          if (Ok) {
            if (!C.cboRegion.Text() &amp;&amp; !mRecord.RegionAllowBlank) {
              Ok = false;
              cmdAdvanced.trigger("click");
              C.cboRegion.Focus();
            }
            else if (!C.cboInsurancePolicyType.Text() &amp;&amp; !mRecord.PolicyTypeAllowBlank) {
              Ok = false;
              cmdAdvanced.trigger("click");
              C.cboInsurancePolicyType.Focus();
            }
          }
        }
        break;

      case "Financial":
        // Server-side validation
        break;
        
      case "Disbursements":
        var updateDisbursements = false

        // Find any Disbursements dated prior to the Opening Date
        for (var i = 0; i &lt; mRecord_Disbursements.length; i++) {
          var item = mRecord_Disbursements[i];
          
          if (widget.CompareDates(item.Date, C.afFinancial.OpeningDate()) == -1) {
            updateDisbursements = true;
            break;
          }          
        }
        
        // Prompt User to update
        if (updateDisbursements) {
          var options = {
            captionOk: "Yes", 
            captionCancel: "No",
            icon: "Warning",
          }
          widget.UI.MsgBoxConfirm("One or more Disbursements is dated before the Account is due to be opened.\n\nContinue and re-date Disbursements?", options, function() { RefreshDisbursements(true); });
          return;
        }
        else {
          validCallback();
          return;
        }
        break;  
        
      default:
        // No validation
        validCallback();
        return;
    }
  }

  // Server-side validation
  if (Ok) {
    var params;

    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        params = { AccountTypeId: C.cboAccountType.Text(),
                   AccountTypePromotionId: C.cboAccountTypePromotion.Text(),
                   BranchId: C.cboBranch.Text(),
                   BrokerId: C.cboBroker.Text(),
                   DealerId: C.cboDealer.Text()};
        break;

      case "Clients":
      case "Security":
      case "Financial":
        // Clients, Security, Financial
        Fields_Save();
        params = { AccountDetails: JSON.stringify(mRecord_Account) };
        break;
    }

    if (params) {
      // Disable Form
      frmMain.FormDisable("Validating");

      // Extend parameters
      params.pageId = tabWizard.SelectedTabId();

      // Call WizardValidate method in Script
      widget.GetString("WizardValidate",
                       params,
                       function (data) { tabWizard_ValidatePost(validCallback, data); },
                       tabWizard_ValidateFail);
    }
    else {
      // No server-side validation
      validCallback();
    }
  }
}

function tabWizard_ValidatePost(validCallback, data) {
  // Enable form
  frmMain.FormEnable();

  // Parse Data
  var o = {};
  if (data) o = JSON.parse(data);

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      default:
        break;
    }

    // Callback
    validCallback();
  }
}

function tabWizard_ValidateFail(errorMessage)
{
  widget.UI.MsgBoxAlert(errorMessage);

  // Enable form
  frmMain.FormEnable();
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId) {
     case "FormClose":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabWizard_Cancel();
      break;
   }
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      tabWizard_Cancel();
      break;

    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

    default:
      window.alert(mViewName + ".Form_ExecuteAction: Unhandled action '" + actionId + "'");
      break;
  }
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Quote Mode?
  if (mQuoteMode) {
    widget.Close();
    return;
  }

  // Validate
  tabWizard_Validate(function () {
    // Save Fields
    Fields_Save();

    if (mRecord.PromptOnSave) {
      // Confirm
      var msg, heading;

      if (mRecord_Account.AccountId) {
        heading = "Update 'Quote' Account";
        msg = "Are you sure you want to update Account '" + mRecord_Account.AccountId + "'?";
      }
      else {
        heading = "Add New Account";
        msg = "Are you sure you want to add a new Account?";
      }
      if (C.chkPrintContract.Value()) {
        if (mAccountType.AccountClass == "Deposit") {
          msg += "\n\nNOTE: Once saved, a Deposit Certicate document will be generated."
        }
        else {
          msg += "\n\nNOTE: Once saved, a Contract document will be generated."
        }
      }

      widget.UI.MsgBoxConfirm(msg, { heading: heading }, Form_ExecuteAction_FinishPost, null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishPost(moveAction) {
  // Disable Form
  widget.UI.Block("Saving, please wait...");

  // Create Parameters
  var params = mRecord_Account;

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      data = JSON.parse(data);

      // Finalise
      if (data.Warning) {
        var msg;

        if (mRecord_Account.AccountId) {
          msg = "Account '" + data.AccountId + "' was successfully updated but the following warning was given:";
        }
        else {
          msg = "The new Account '" + data.AccountId + "' was successfully created but the following warning was given:";
        }

        widget.UI.MsgBoxAlert(msg + "\n\n" + data.Warning, {}, function() { Form_ExecuteAction_FinishPost_PrintContract(data); });
      }
      else {
        Form_ExecuteAction_FinishPost_PrintContract(data);
      }
    },

    function (data) {
      // Show Error
      widget.UI.MsgBoxAlert(data);

      // Enable Form
      widget.UI.Unblock();
    }
  );
}

function Form_ExecuteAction_FinishPost_PrintContract(data) {
  // Print Contract
  // NOTE: Since this is a file download, cannot reliably detect whether it worked or not hence finalise regardless
  if (C.chkPrintContract.Value()) {
    widget.DownloadFile("PrintContract", { AccountId: data.AccountId });
  }

  // Finalise
  Form_ExecuteAction_FinishPost_Finalise(data);
}

function Form_ExecuteAction_FinishPost_Finalise(data) {
  // Close Form
  widget.Close();

  // Show New/ Updated Account record (after closing Widget to avoid notification on Web)
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=Accounts&amp;id=" + data.AccountId);

  // Begin acceptance process?
  if (!C.chkQuote.Value()) {
    if (widget.GetHostingContext() == "HtmlViewer") {
      // Desktop wizard
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountAcceptDecline&amp;id=" + data.AccountId);
    }
    else {
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountAcceptDecline&amp;action=accept&amp;accountid=" + data.AccountId);
    }
  }
}

// =============
// Client Search
// =============
function ClientSearch() {
  // Validate
  if (!C.txtClientSearch.Text()) {
    C.txtClientSearch.Focus();
    return;
  }

  // Search
  widget.GetString("ClientSearch", { query: C.txtClientSearch.Text() }, ClientSearch_Done, ClientSearch_Fail);

  // Finalise
  mClientSearchText = C.txtClientSearch.Text();
}

function ClientSearch_Done(data) {
  // Parse
  mClientSearchResults = JSON.parse(data);

  // Build results list
  if (!C.gridClientSearch) {
    C.gridClientSearch = widget.UI.Grid("gridSearchResults", {
      stickyHeader: true,
      showRowSelectors: true,
      allowMultiRowSelect: true,

      onAction: gridClientSearch_Action,
      onInitialiseRow: gridClientSearch_InitialiseRow,
      onRowDrilldown: gridClientSearch_RowDrilldown,
    });

    // Columns
    C.gridClientSearch.AddColumnDrilldown("Drilldown", { drilldownGlyph: "add" });
    C.gridClientSearch.AddColumnIcon("ClientStatusIcon", { caption: "", allowEdit: false });
    C.gridClientSearch.AddColumnCode("ClientId", { caption: "Client" });
    C.gridClientSearch.AddColumnString("Name", { caption: "Name" });
    C.gridClientSearch.AddColumnDate("DateOfBirth", { caption: "DOB" });

    // Actions
    C.gridClientSearch.Actions().Define([{ actionId: "AddAll", icon: "Grid_CardView|Add", caption: "Add all Selected Clients" }]);
  }

  // Show Search
   C.divSearchResults.show();

  // Bind grid
  C.gridClientSearch.VirtualDataRefresh(mClientSearchResults);
  C.gridClientSearch.ActivateFirstDataRow(true);
}

function ClientSearch_Fail(error) {
  widget.UI.MsgBoxAlert(error);
}

// ================
// gridClientSearch
// ================
function gridClientSearch_InitialiseRow(e) {
  var item = mClientSearchResults[e.row.listIndex];

  // Update cells
  if (item.ClientStatus) e.row.cells.ClientStatusIcon.value = "ClientStatus_" + item.ClientStatus;
  e.row.cells.ClientId.value = item.ClientId;
  e.row.cells.Name.value = item.Name;
  e.row.cells.DateOfBirth.value = item.DateOfBirth;
}

function gridClientSearch_RowDrilldown(e) {
  // Add Client
  AddClient(mClientSearchResults[e.row.listIndex].ClientId, mClientSearchResults[e.row.listIndex].Name, mClientSearchResults[e.row.listIndex].ClientStatus, true);

  // Close Client Search
  C.divSearchResults.hide();
}

function gridClientSearch_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "ADDALL":
      // Add all selected Clients
      var rows = C.gridClientSearch.GetSelectedRowIndexes(true);
      for (var i = 0; i &lt; rows.length; i++) {
        var item = mClientSearchResults[rows[i]];        
        AddClient(item.ClientId, item.Name, item.ClientStatus, rows.length &lt;= 1);
      }

      // Close Client Search
      C.divSearchResults.hide();
      return;

    default:
      window.alert("Unhandled grid action '" + actionId + "'.");
      break;
  }
}

// ==========
// Add Client
// ==========
function AddClient(clientId, name, status, showWarning) {
  // Check if already exists
  if (!mQuoteMode) {
    for(var i = 0; i &lt; mRecord_Clients.length; i++) {
      var item = mRecord_Clients[i];

      if (item.ClientId == clientId) {
        C.gridClients.ActiveDataRowIndex(i);

        if (showWarning) widget.UI.MsgBoxInfo("This Client has already been added to this Account.");
        return;
      }
    }
  }

  // Add
  if (name) {
    // Add immediately
    AddClient_Done(clientId, name, status);
  }
  else {
    // Fetch Client details and then add
    widget.GetString("GetClientDetails", { ClientId: clientId },
    function(data) {
      // Parse
      data = JSON.parse(data);

      // Add
      AddClient_Done(data.ClientId, data.Name, data.Status);
    },

    function(error) {
      widget.UI.MsgBoxAlert(error);
    });
  }
}

function AddClient_Done(clientId, name, status) {
  // Add
  var item = { 
    AccountRoleId: mProductType.DefaultAccountRoleId, 
    ClientId: clientId, 
    ClientName: name, 
    ClientStatus: status,
    AccountSignatory: mRecord.DefaultClientAccountSignatory,
    PrivacyConsent: mRecord.DefaultClientPrivacyConsent,
    SendDocuments: mRecord.DefaultClientSendDocuments,
    SecurityParty: mRecord.DefaultClientSecurityParty,
  };
  mRecord_Clients.push(item);

  // Refresh
  C.gridClients.VirtualDataRefresh(mRecord_Clients);

  // Select
  C.gridClients.ActivateLastDataRow();
}

// ===============
// txtClientSearch
// ===============
function txtClientSearch_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Show/ Hide search results
  if (mClientSearchResults &amp;&amp; mClientSearchText == C.txtClientSearch.Text()) {
    C.divSearchResults.show();

    // Force a resize to keep grid layout tidy
    $(window).trigger("resize");
  }
  else {
    C.divSearchResults.hide();
  }
}

function txtClientSearch_Focus(sender, e) {
  if (mClientSearchResults &amp;&amp; mClientSearchText == C.txtClientSearch.Text()) {
    C.divSearchResults.show();

    // Force a resize to keep grid layout tidy
    $(window).trigger("resize");
  }
}

// =======
// txtName
// =======
function txtName_ButtonClick(sender, e) {
  switch (e.id) {
    case "Reset":
      C.txtName.Text(mLastDefaultName);
      
      // Update Controls
      txtName_Change();
      break;
  }
}

function txtName_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Actions
  C.txtName.Buttons().ButtonVisible("Reset", mLastDefaultName &amp;&amp; mLastDefaultName != C.txtName.Text());
}

// ==============
// txtDescription
// ==============
function txtDescription_ButtonClick(sender, e) {
  switch (e.id) {
    case "Reset":
      C.txtDescription.Text(mLastDefaultDescription);
      
      // Update Controls
      txtDescription_Change();
      break;
  }
}

function txtDescription_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Actions
  C.txtDescription.Buttons().ButtonVisible("Reset", mLastDefaultDescription &amp;&amp; mLastDefaultDescription != C.txtDescription.Text());
}

// ===========
// afFinancial
// ===========
function afFinancial_Action(actionId) {
  switch(actionId) {    
    case "PaymentsCleanup":
      // Clean up Payments
      afFinancial_OverridingPaymentsHandling("PaymentsCleanup");
      break;

    case "RegularPaymentsCreate":
      // Create Blank Regular Payments
      afFinancial_OverridingPaymentsHandling("RegularPaymentsCreate");
      break;

    case "Reset":
      // Reset
      widget.UI.MsgBoxConfirm("Are you sure you want to reset all Financial details to their defaults (as defined on the Account Type)?", { heading: "Reset Financial" },
        function() {
          Calculate(null, actionId);
        });
      break;

    case "ScheduleShow":
      // Show Schedule
      ScheduleShow();
      break;

    case "StdTransReset":
      // Reset Standard Transactions
      widget.UI.MsgBoxConfirm("Are you sure you want to reset all Transactions to their defaults (as defined on the Account Type)?", { heading: "Reset Transactions" },
        function() {
          Calculate(null, actionId);
        });
      break;

    default:
      window.alert("Unhandled action '" + actionId + "'.");
  }
}

function afFinancial_Change(fieldUpdated) {
  // Clear Summary
  C.wbAccountSummary.Clear();

  // Calculate delayed
  if (mCalculationTimer) {
    window.clearTimeout(mCalculationTimer);
    mCalculationTimer = null;
  }

  if (fieldUpdated) {
    // A named field has been updated that is known to affect other fields so calculate immediately
    Calculate(fieldUpdated);
  }
  else {
    // Delayed calculation
    mCalculationTimer = window.setTimeout(function () {
      Calculate();
      mCalculationTimer = null;
    }, 500);
  }
}

// =======================
// Regular Payments Create
// =======================
function afFinancial_OverridingPaymentsHandling(action) {
  // Block
  widget.UI.Block("Updating Overriding Payments, please wait...");
  
  // Save
  Fields_Save();
  
  // Params
  var params = {
    action: action,
    accountJson: JSON.stringify(mRecord_Account),
    overridingPaymentsJson: C.afFinancial.GetOverridingPaymentsJson(),    
  }
  
  // Create Payments
  widget.GetString("OverridingPaymentsHandling", params, afFinancial_OverridingPaymentsHandling_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();
    
    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function afFinancial_OverridingPaymentsHandling_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Set Payments
  C.afFinancial.SetOverridingPayments(data);
  
  // Unblock
  widget.UI.Unblock();
}

// ==============
// blProductTypes
// ==============
function blProductTypes_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Reset if User has changed Product Type
  if (sender) {
    mAccountType = null;
    C.cboAccountType.Text("");
  }

  if (C.blProductTypes.SelectedItemIndex() != -1) {
    // Select Product Type
    mProductType = mRecord.ProductTypes[C.blProductTypes.SelectedItemIndex()];
    mRecord.ProductTypeId = mProductType.ProductTypeId;

    // Refresh Account Types
    cboAccountType_Refresh_Data(sender);

    // Refresh Promotions
    cboAccountType_Change();

    // Refresh Page
    pageGeneral_Refresh();

    // Financial needs refreshing?
    if (sender) mFinancialInitialise = true;
  }
}

function blProductTypes_Refresh() {
  // Build Product Types List
  var buttons = [];
  for(var i = 0; i &lt; mRecord.ProductTypes.length; i++) {
    var item = mRecord.ProductTypes[i];

    buttons.push({ id: item.ProductTypeId,
                   caption: item.Caption,
                   icon: item.Icon });
  }
  C.blProductTypes.ButtonsDefine(buttons);

  // Hide?
  if (buttons.length &lt;= 1) {
    C.tbProductType.hide();
    if (buttons.length == 1) C.blProductTypes.SelectedItemIndex(0);
  }
  else {
    C.tbProductType.show();
  }
}

// ==============
// cboAccountType
// ==============
function cboAccountType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Really Changed?
  if (mAccountType &amp;&amp; mAccountType.AccountTypeId === C.cboAccountType.Text()) return;

  // Get Account Type
  mAccountType = mRecord.AccountTypes.GetItem(C.cboAccountType.Text());
  mRecord.AccountTypeId = C.cboAccountType.Text();

  // Reset Ledger
  C.cboLedger.Text("");

  // Refresh Promotions List
  if (mRecord.AddOnsPromotions) {
    cboAccountTypePromotions_Refresh();
  }
  else {
    C.cboAccountTypePromotion.VisibleRow(false);
  }

  // Financial needs refreshing?
  if (sender) mFinancialInitialise = true;

  if (mAccountType) {
    // Account-level Insurance?  
    if (mAccountType.IncludeAccountLevelInsurance) {
      C.lblInsurance.VisibleRow(true);
      C.cboInsurer.VisibleRow(mRecord.AddOnsExternalPartyInsurers);
      C.cboInsurancePolicyType.VisibleRow(true);
      C.txtInsurancePolicyNumber.VisibleRow(true);
    }
    else {
      C.lblInsurance.VisibleRow(false);
      C.cboInsurer.VisibleRow(false);
      C.cboInsurancePolicyType.VisibleRow(false);
      C.txtInsurancePolicyNumber.VisibleRow(false);
    }
    
    // Account Type Specific Options
    if (mRecord_Account.AccountId) {
      // Returning Quote - so default to True
      C.chkQuote.Value(true);    
    }
    else {
      // Get default from Account Type
      C.chkQuote.Value(mAccountType.DefaultStatusAsQuote);
    }
  }
}

function cboAccountType_Refresh(sender, e) {
  if(C.cboBranch.Text()) {
    var params = {
      branchId: C.cboBranch.Text()
    }

    widget.GetString("GetAccountAndProductTypes", params, function(data, e) { cboAccountType_Refresh_Done(data, e) } , function(errorMessage) {
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }
  else {
    C.cboAccountType.Text("");
  }
}

function cboAccountType_Refresh_Done(data, e) {
  var o = JSON.parse(data);
  mRecord.ProductTypes = o.ProductTypes;
  mRecord.AccountTypes = o.AccountTypes;

  // Give Collections ability to lookup by code
  widget.ArrayAllowLookupById(mRecord.AccountTypes, "AccountTypeId");

  // Refresh Product Types
  blProductTypes_Refresh();

  // Refresh Account Types
  cboAccountType_Refresh_Data(true);

  // Refresh Promotions List
  if (e &amp;&amp; mRecord.AddOnsPromotions) cboAccountTypePromotions_Refresh();
}

function cboAccountType_Refresh_Data(setDefault) {
  var accountTypes = "";
  var accountTypesList = [];

  for (var i = 0; i &lt; mProductType.AccountTypesList.length; i++) {
    var found = false;

    // Ensure that the Product Type Account Type is valid for our Branch
    var tAccountType = mRecord.AccountTypes.GetItem(mProductType.AccountTypesList[i]);
    if(tAccountType) found = true;

    // Add to list if found
    if(found) {
      if (accountTypes) accountTypes += ",";
      accountTypes += "'" + mProductType.AccountTypesList[i] + "'";

      // Add to temporary object for use with defaults later
      var o = {
        accountTypeId: mProductType.AccountTypesList[i],
        productTypeId: mProductType.ProductTypeId
      }
      accountTypesList.push(o);
    }
  }
  if (!accountTypes) accountTypes = "'~'";
  var sqlWhere = "AccountTypeId IN (" + accountTypes + ")";
  C.cboAccountType.RefreshFromStandardRange("AccountTypes", sqlWhere);

  // Default Account Type if User has changed Product Type
  if (setDefault) {
    var defaultAccountTypeId = "";
    var defaultProductTypeId = "";

    // Determine default
    for(var i = 0; i &lt; accountTypesList.length; i++) {
      if(accountTypesList[i].accountTypeId == mProductType.DefaultAccountTypeId) {
        defaultAccountTypeId = mProductType.DefaultAccountTypeId;
        defaultProductTypeId = mProductType.ProductTypeId;
        break;
      }
    }

    // If not found, assume first in list
    if(!defaultAccountTypeId &amp;&amp; accountTypesList.length &gt; 0) {
      defaultAccountTypeId = accountTypesList[0].accountTypeId;
      defaultProductTypeId = accountTypesList[0].productTypeId;
    }

    // Set Default
    C.cboAccountType.Text(defaultAccountTypeId);
    C.blProductTypes.SelectedItemId(defaultProductTypeId);
  }

  // Refresh Promotions
  cboAccountTypePromotions_Refresh();
}

// ========================
// cboAccountTypePromotions
// ========================
function cboAccountTypePromotion_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Financial needs recalculating?
  mAccountTypePromotionChanged = true;
}

function cboAccountTypePromotions_Refresh() {
  C.cboAccountTypePromotion.Text(mPreservedAccountTypePromotionId);

  if (!mAccountType || !mAccountType.HasPromotions) {
    C.cboAccountTypePromotion.VisibleRow(false);
  }
  else {
    C.cboAccountTypePromotion.VisibleRow(true);
    C.cboAccountTypePromotion.AllowBlank(!mAccountType.PromotionMandatory);

    // Save
    // NOTE: Do not save during initial load, this is because fields may not yet be populated and mRecord_Account will be more accurate!
    if (!mInitialLoad) {
      Fields_Save();
    }

    // Get Promotions
    widget.GetString("GetPromotions", mRecord_Account,
      function(data) {
        mPromotions = JSON.parse(data);
        mPreservedAccountTypePromotionId = "";
        C.cboAccountTypePromotion.RefreshFromCollection(mPromotions, "Code", "Description");
      },

      function(error) {
        widget.UI.MsgBoxAlert(error);
      });
  }
}

// ===========
// gridClients
// ===========
function gridClients_Refresh() {
  // Initialise
  var showAdvanced = mRecord.ShowClientAdditional == "True" || (mAdvancedVisible &amp;&amp; mRecord.ShowClientAdditional == "Advanced");

  // Add Columns
  C.gridClients.ClearColumns();
  C.gridClients.AddColumnIcon("ClientStatusIcon", { caption: "", allowEdit: false});
  C.gridClients.AddColumnString("AccountRoleId", { caption: "Role", width: widget.UI.FIELD_WIDTH_CODE_5, allowEdit: true, collection: mProductType.AccountRolesList, columns: "Description", idColumn: "Code" });
  C.gridClients.AddColumnBoolean("RoleJoint", { caption: "Joint", allowEdit: true });
  C.gridClients.AddColumnCode("ClientId", { caption: "Client", width: widget.UI.FIELD_WIDTH_CODE_10, allowEdit: true, standardRange: "Clients", sqlWhere: "", displayColumns: "ClientId,Name" });
  C.gridClients.AddColumnString("ClientName", { caption: "Name", allowEdit: false });
  C.gridClients.AddColumnBoolean("AccountSignatory", { caption: "Signatory", allowEdit: true, visible: showAdvanced });
  C.gridClients.AddColumnBoolean("PrivacyConsent", { caption: "Privacy", allowEdit: true, visible: showAdvanced });
  C.gridClients.AddColumnBoolean("SendDocuments", { caption: "Mail", allowEdit: true, visible: showAdvanced });
  if (mRecord.AddOnsSecurityRegister) C.gridClients.AddColumnBoolean("SecurityParty", { caption: "Security", allowEdit: true, visible: showAdvanced });

  // Actions
  C.gridClients.Actions().Define([{ actionId: "DeleteRow", tooltipText: "Remove row", icon: "Delete" },
                                  {},
                                  { actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" },
                                  { actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" }]);

  // Refresh
  C.gridClients.VirtualDataRefresh(mRecord_Clients);
}

function gridClients_InitialiseRow(e) {
  var item = mRecord_Clients[e.row.listIndex];

  // Update cells
  if (item.ClientStatus) e.row.cells.ClientStatusIcon.value = "ClientStatus_" + item.ClientStatus;
  e.row.cells.AccountRoleId.value = item.AccountRoleId;
  e.row.cells.RoleJoint.value = item.RoleJoint;
  e.row.cells.ClientId.value = item.ClientId;
  e.row.cells.ClientName.value = item.ClientName;
  e.row.cells.AccountSignatory.value = item.AccountSignatory;
  e.row.cells.PrivacyConsent.value = item.PrivacyConsent;
  e.row.cells.SendDocuments.value = item.SendDocuments;
  if (mRecord.AddOnsSecurityRegister) e.row.cells.SecurityParty.value = item.SecurityParty;

  // Special for Main Client
  if (e.row.listIndex == 0) {
    e.row.cells.RoleJoint.readOnly = true;
    e.row.cells.AccountSignatory.readOnly = true;
    e.row.cells.SendDocuments.readOnly = true;
    if (mRecord.AddOnsSecurityRegister) e.row.cells.SecurityParty.readOnly = true;
  }
  
  // Update Privacy Read-Only state for the Account role
  var accountRole = mAccountRoles.GetItem(item.AccountRoleId);
  if (accountRole) {
    e.row.cells.PrivacyConsent.readOnly = !accountRole.UsePrivacyConsent;
  }
  else {
    e.row.cells.PrivacyConsent.readOnly = true;
  }

  // Style non-editable cells
  e.row.cells.ClientStatusIcon.readOnly = true;
  e.row.cells.ClientName.readOnly = true;

  // Cell Styles
  e.row.cells.ClientName.small = true;
}

function gridClients_BeforeCellUpdate(e) {
  var item = mRecord_Clients[e.row.listIndex];

  switch(e.columnKey) {
    case "AccountRoleId":
      if (item.AccountRoleId != e.newValue) {
        item.AccountRoleId = e.newValue;

        // Defaults
        if (item.AccountRoleId) {
          var accountRole = mAccountRoles.GetItem(item.AccountRoleId);
          if (accountRole) {
            item.AccountSignatory = accountRole.AccountSignatory;
            item.SendDocuments = accountRole.SendDocuments;
            if (!accountRole.UsePrivacyConsent) item.PrivacyConsent = false;
            if (mRecord.AddOnsSecurityRegister) item.SecurityParty = accountRole.IncludeInSecurityStatement;            
          }
        }
      }
      break;

    case "ClientId":
      item.ClientId = e.newValue;
      UpdateClientDetails(e.row.listIndex);
      break;

    case "RoleJoint":
      item.RoleJoint = e.newValue;
      break;

    case "AccountSignatory":
      item.AccountSignatory = e.newValue;
      break;

    case "PrivacyConsent":
      item.PrivacyConsent = e.newValue;
      break;

    case "SendDocuments":
      item.SendDocuments = e.newValue;
      break;

    case "SecurityParty":
      item.SecurityParty = e.newValue;
      break;
 }

  // Refresh row to update styles
  e.refreshRow = true;
}

function gridClients_AfterRowActivate(e) {
  // Refresh Buttons
  gridClients_RefreshButtons();
}

function gridClients_RefreshButtons() {
  if (C.gridClients.ActiveDataRowListIndex() == -1) {
    C.gridClients.Actions().SetEnabled("DeleteRow", false);
    C.gridClients.Actions().SetEnabled("RowMoveUp", false);
    C.gridClients.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    C.gridClients.Actions().SetEnabled("DeleteRow", true);
    C.gridClients.Actions().SetEnabled("RowMoveUp", C.gridClients.ActiveDataRowListIndex() &gt; 0);
    C.gridClients.Actions().SetEnabled("RowMoveDown", C.gridClients.ActiveDataRowListIndex() &lt; mRecord_Clients.length - 1);
  }

  C.gridClients.RefreshButtons();
  C.gridClients.Focus();
}

function gridClients_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "DELETEROW":
      C.gridClients.RemoveRowAndCollectionItem(C.gridClients.ActiveDataRowListIndex());
      break;

    case "ROWMOVEDOWN":
      C.gridClients.RowMoveDown();
      break;

    case "ROWMOVEUP":
      C.gridClients.RowMoveUp();
      break;

    default:
      window.alert("Unhandled grid action '" + actionId + "'.");
      break;
  }

  C.gridClients.RefreshButtons();
}

function gridClients_RowAdd(e) {
  // Create item
  var item = {
    ClientStatusIcon: null,
    AccountRoleId: mProductType.DefaultAccountRoleId,
    RoleJoint: false,
    ClientId: null,
    AccountName: null,
    AccountSignatory: mRecord.DefaultClientAccountSignatory,
    PrivacyConsent: mRecord.DefaultClientPrivacyConsent,
    SendDocuments: mRecord.DefaultClientSendDocuments,
    SecurityParty: mRecord.DefaultClientSecurityParty,
  };

  // Add
  mRecord_Clients.push(item);
}

// =================
// gridSecurityItems
// =================
function gridSecurityItems_Refresh() {
  var showTradeInColumn = true;
  var showValueColumn = true;
  
  if (mRecord &amp;&amp; mRecord.Terminology_SecurityStmtInsuranceBroker) {
    showTradeInColumn = false;
    showValueColumn = false;
  }

  // Add Columns
  C.gridSecurityItems.ClearColumns();
  C.gridSecurityItems.AddColumnDrilldown();
  C.gridSecurityItems.AddColumnIcon("SecurityTypeIcon");
  C.gridSecurityItems.AddColumnString("SecurityTypeDescription", { caption: "Type", width: widget.UI.FIELD_WIDTH_CODE_10 });
  C.gridSecurityItems.AddColumnBoolean("TradeIn", { caption: "Trade-In", visible: showTradeInColumn });
  C.gridSecurityItems.AddColumnString("Description", { caption: "Description" });
  C.gridSecurityItems.AddColumnCurrency("Value", { caption: "Value", visible: showValueColumn });
  C.gridSecurityItems.AddColumnCurrency("SecurityValue", { caption: "Security Value" });

  // Actions
  var actions = [];
  if (mRecord &amp;&amp; mRecord.Terminology_SecurityStmtInsuranceBroker) {
    actions.push({ actionId: "Add", tooltipText: "Add a new Policy Item", icon: "Add" });
  }
  else {
    actions.push({ actionId: "Add", tooltipText: "Add a new Security Item", icon: "Add" });
  }
  
  actions.push({ actionId: "DeleteRow", tooltipText: "Remove row", icon: "Delete" },
                {},
                { actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" },
                { actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });

  C.gridSecurityItems.Actions().Define(actions);

  // Refresh
  C.gridSecurityItems.VirtualDataRefresh(mRecord_SecurityItems);
}

function gridSecurityItems_InitialiseRow(e) {
  var item = mRecord_SecurityItems[e.row.listIndex];

  // Update cells
  e.row.cells.SecurityTypeIcon.value = item.SecurityTypeIcon;
  e.row.cells.SecurityTypeDescription.value = item.SecurityTypeDescription;
  e.row.cells.TradeIn.value = item.TradeIn;
  e.row.cells.Description.value = item.Description;
  e.row.cells.Value.value = item.Value;
  e.row.cells.SecurityValue.value = item.SecurityValue;
}

function gridSecurityItems_AfterRowActivate(e) {
  // Refresh Buttons
  gridSecurityItems_RefreshButtons();
}

function gridSecurityItems_RefreshButtons() {
  if (C.gridSecurityItems.ActiveDataRowListIndex() == -1) {
    C.gridSecurityItems.Actions().SetEnabled("DeleteRow", false);
    C.gridSecurityItems.Actions().SetEnabled("RowMoveUp", false);
    C.gridSecurityItems.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    C.gridSecurityItems.Actions().SetEnabled("DeleteRow", true);
    C.gridSecurityItems.Actions().SetEnabled("RowMoveUp", C.gridSecurityItems.ActiveDataRowListIndex() &gt; 0);
    C.gridSecurityItems.Actions().SetEnabled("RowMoveDown", C.gridSecurityItems.ActiveDataRowListIndex() &lt; mRecord_Clients.length - 1);
  }

  C.gridSecurityItems.RefreshButtons();
  C.gridSecurityItems.Focus();
}

function gridSecurityItems_RowDrilldown(e) {
  EditSecurityItem(e.row.listIndex);
}

function gridSecurityItems_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "ADD":
      EditSecurityItem(-1);
      return;

    case "DELETEROW":
      C.gridSecurityItems.RemoveRowAndCollectionItem(C.gridSecurityItems.ActiveDataRowListIndex());
      break;

    case "ROWMOVEDOWN":
      C.gridSecurityItems.RowMoveDown();
      break;

    case "ROWMOVEUP":
      C.gridSecurityItems.RowMoveUp();
      break;

    default:
      window.alert("Unhandled grid action '" + actionId + "'.");
      break;
  }

  C.gridSecurityItems.RefreshButtons();
}

// =================
// gridDisbursements
// =================
function gridDisbursements_Refresh() {
  // Add Columns
  C.gridDisbursements.ClearColumns();
  C.gridDisbursements.AddColumnDrilldown("Drilldown", {});
  C.gridDisbursements.AddColumnString("ElementId", { caption: "Element", width: "2em" });
  C.gridDisbursements.AddColumnString("ElementDescription", { caption: "Description", doNotCreateBelowScreenWidth: 640, autoHideBelowWidth: 640 });
  C.gridDisbursements.AddColumnString("StatusText", { caption: "Status", width: "2em" });
  C.gridDisbursements.AddColumnString("TypeText", { caption: "Type", width: "2em" });
  C.gridDisbursements.AddColumnString("PayeeTypeText", { caption: "Payee Type", width: "2em" });
  C.gridDisbursements.AddColumnString("PayeeName", { caption: "Payee" });
  C.gridDisbursements.AddColumnDate("Date", { caption: "Date" });
  C.gridDisbursements.AddColumnDate("DateDue", { caption: "Date Due" });
  C.gridDisbursements.AddColumnCurrency("Value", { caption: "Value" });

  // Actions
  C.gridDisbursements.Actions().Define([{ actionId: "CreateDefaultDisbursements", tooltipText: "Create default Disbursements", icon: "Reset" },
                                        {},
                                        { actionId: "Add", tooltipText: "Add a new Disbursement", icon: "Add" },
                                        { actionId: "DeleteRows", tooltipText: "Remove selected Disbursements", icon: "Delete" },
                                        {},
                                        { actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" },
                                        { actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" },
                                        {},
                                        { actionId: "Action_Hold", tooltipText: "Set selected items to 'Hold'", icon: "Hold", caption: "Hold" },
                                        { actionId: "Action_Pending", tooltipText: "Set selected items to 'Pending'", icon: "Hourglass", caption: "Pending" },
                                        { actionId: "Action_Cancelled", tooltipText: "Cancel selected items", icon: "Trash", caption: "Cancel" }]);

  // Refresh
  C.gridDisbursements.VirtualDataRefresh(mRecord_Disbursements);
}

function gridDisbursements_InitialiseRow(e) {
  var item = mRecord_Disbursements[e.row.listIndex];

  // Update cells
  e.row.cells.ElementId.value = item.ElementId;
  e.row.cells.ElementDescription.value = item.ElementDescription;
  e.row.cells.StatusText.value = item.StatusText;
  e.row.cells.TypeText.value = item.TypeText;
  e.row.cells.PayeeTypeText.value = item.PayeeTypeText;
  e.row.cells.PayeeName.value = item.PayeeName;
  e.row.cells.Date.value = item.Date;
  e.row.cells.DateDue.value = item.DateDue;
  e.row.cells.Value.value = item.Value;
}

function gridDisbursements_AfterRowActivate(e) {
  // Refresh Buttons
  gridDisbursements_RefreshButtons();
}

function gridDisbursements_RefreshButtons() {
  var rows = C.gridDisbursements.GetSelectedRowIndexes(true, true);

  if (C.gridDisbursements.ActiveDataRowListIndex() == -1) {
    C.gridDisbursements.Actions().SetEnabled("RowMoveUp", false);
    C.gridDisbursements.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    C.gridDisbursements.Actions().SetEnabled("RowMoveUp", C.gridDisbursements.ActiveDataRowListIndex() &gt; 0);
    C.gridDisbursements.Actions().SetEnabled("RowMoveDown", C.gridDisbursements.ActiveDataRowListIndex() &lt; mRecord_Disbursements.length - 1);
  }

  C.gridDisbursements.Actions().SetEnabled("DeleteRows", rows.length != 0);
  C.gridDisbursements.Actions().SetEnabled("Action_Hold", rows.length != 0);
  C.gridDisbursements.Actions().SetEnabled("Action_Pending", rows.length != 0);
  C.gridDisbursements.Actions().SetEnabled("Action_Cancelled", rows.length != 0);

  C.gridDisbursements.RefreshButtons();
  C.gridDisbursements.Focus();
}

function gridDisbursements_RowDrilldown(e) {
  EditDisbursement(e.row.listIndex);
}

function gridDisbursements_Action(actionId) {
  // Get selected rows (including the active row if no selected rows)
  var rows = C.gridDisbursements.GetSelectedRowIndexes(true, true);

  switch (actionId.toUpperCase()) {
    case "ACTION_CANCELLED":
    case "ACTION_HOLD":
    case "ACTION_PENDING":
     for (var i = 0; i &lt; rows.length; i++) {
        var item = mRecord_Disbursements[rows[i]];

        // Must set Status on actual item (for grid display) and also the JSON object (for editing and updating the actual Disbursement)
        var o = JSON.parse(item.Json);
        item.StatusText = actionId.substr(7);
        o.StatusText = item.StatusText;
        item.Json = JSON.stringify(o);

        C.gridDisbursements.RefreshRow(rows[i]);
      }
      break;

    case "ADD":
      EditDisbursement(-1);
      return;

    case "CREATEDEFAULTDISBURSEMENTS":
      widget.UI.MsgBoxConfirm("Are you sure you want to reset Disbursements to default values?", {}, gridDisbursements_Action_CreateDefaultDisbursements);
      return;

    case "DELETEROWS":
      for (var i = rows.length-1; i&gt;=0; i--) {
        C.gridDisbursements.RemoveRowAndCollectionItem(rows[i]);
      }
      break;

    case "ROWMOVEDOWN":
      C.gridDisbursements.RowMoveDown();
      break;

    case "ROWMOVEUP":
      C.gridDisbursements.RowMoveUp();
      break;

    default:
      window.alert("Unhandled grid action '" + actionId + "'.");
      break;
  }

  C.gridDisbursements.RefreshButtons();
}

function gridDisbursements_Action_CreateDefaultDisbursements() {
  // Block UI
  widget.UI.Block("Creating default Disbursements, please wait...");

  Fields_Save();

  widget.GetString("CreateDefaultDisbursements", mRecord_Account,
    function (data) {
      mRecord_Disbursements = JSON.parse(data);
      mRecord_Account.Disbursements = mRecord_Disbursements;

      // Refresh
      C.gridDisbursements.VirtualDataRefresh(mRecord_Disbursements);

      widget.UI.Unblock();
    },

    function (error) {
      widget.UI.Unblock();
      widget.UI.MsgBoxAlert(error);
    }
  );
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Controls
  if (C.blProductTypes.SelectedItemId()) {
    C.tbGeneral.show();
  }
  else {
    C.tbGeneral.hide();
  }

  // Configuration and Licensing
  // NOTE: The AdvancedInitialise method deals with much of the showing and hiding of controls
  if (mRecord) {
  }
}

// =============
// pageFinancial
// =============
function pageFinancial_Refresh(recalculate) {
  // Recalculate
  if (recalculate) Calculate();
}

// ========
// pageName
// ========
function pageName_Refresh() {
  // Information Lists
  C.cboPurpose.SetComboFromInformationList(mProductType.AccountPurposeInformationListId, true);
  C.cboSource.SetComboFromInformationList(mProductType.AccountSourceInformationListId, true);

  // Other defaults
  if (mRecord_Account.AccountId) {
    // Don't opt to print contract for existing Accounts
  }
  else {
    C.chkPrintContract.Value(mRecord_Page_Name.OptionDefaultPrintContractDocument);
  }

  // Controls
  C.lblLedger.VisibleRow(mRecord_Page_Name.OptionAllowLedger);
  C.cboLedger.VisibleRow(mRecord_Page_Name.OptionAllowLedger);
  if (mRecord_Page_Name.OptionAllowLedger &amp;&amp; !C.cboLedger.Text()) C.cboLedger.Text(mRecord_Page_Name.DefaultLedger);
  
  txtName_Change();
	txtDescription_Change();
}


// =========
// pageOther
// =========
function pageOther_Refresh() {
  var paymentDetails_Params = {
    branchId: C.cboBranch.Text(),
    defaultValuesOnPaymentMethodChange: true,
    isNewAccountWizard: true,
  }

  // Get a comma-separated list of Client Ids
  var arrClientIds = [];
  for (var i = 0; i &lt; mRecord_Clients.length; i++) {
    arrClientIds.push(mRecord_Clients[i].ClientId);
  }
  var clientIds = widget.ArrayToCsvString(arrClientIds);

  // Controls
  C.lblReviewDate.VisibleRow(mRecord_Page_Other.OptionAllowReviewDate);
  C.dateReview.VisibleRow(mRecord_Page_Other.OptionAllowReviewDate);
  if (mRecord_Page_Other.OptionAllowReviewDate) found = true;

  C.lblStatement.VisibleRow(mRecord_Page_Other.StatementUse);
  C.cboStatementCycle.VisibleRow(mRecord_Page_Other.StatementUse);
  C.dateStatementFirst.VisibleRow(mRecord_Page_Other.StatementUse);
  if (mRecord_Page_Other.StatementUse) {
    C.cboStatementCycle.ListFromCsvString(mRecord_Page_Other.StatementCycleList);
    cboStatementCycle_Change();
  }

  C.lblPaymentDetailsIncoming.VisibleRow(mRecord_Page_Other.ShowPaymentDetailsIncoming);
  C.apdPaymentDetailsIncoming.Visible(mRecord_Page_Other.ShowPaymentDetailsIncoming);
  if (mRecord_Page_Other.ShowPaymentDetailsIncoming) {
    // Initialise
    C.apdPaymentDetailsIncoming.Initialise(mRecord_Account.AccountId, paymentDetails_Params, clientIds);
    C.apdPaymentDetailsIncoming.FromBankingDetailsJson(mRecord_Account.BankingDetailsIncomingJson);
  }

  C.lblPaymentDetailsOutgoing.VisibleRow(mRecord_Page_Other.ShowPaymentDetailsOutgoing);
  C.apdPaymentDetailsOutgoing.Visible(mRecord_Page_Other.ShowPaymentDetailsOutgoing);
  if (mRecord_Page_Other.ShowPaymentDetailsOutgoing) {
    // Filter to relevant Payment Types
    C.apdPaymentDetailsOutgoing.PaymentTypeCategoryFilter(mRecord_Page_Other.ShowPaymentDetailsOutgoing_PaymentTypeCategoryFilter);

    // Initialise
    C.apdPaymentDetailsOutgoing.Initialise(mRecord_Account.AccountId, paymentDetails_Params, clientIds);
    C.apdPaymentDetailsOutgoing.FromBankingDetailsJson(mRecord_Account.BankingDetailsOutgoingJson);
  }

  C.lblPaymentDetailsMaturity.VisibleRow(mRecord_Page_Other.ShowPaymentDetailsMaturity);
  C.apdPaymentDetailsMaturity.Visible(mRecord_Page_Other.ShowPaymentDetailsMaturity);
  if (mRecord_Page_Other.ShowPaymentDetailsMaturity) {
    // Initialise
    C.apdPaymentDetailsMaturity.Initialise(mRecord_Account.AccountId, paymentDetails_Params, clientIds);
    C.apdPaymentDetailsMaturity.FromBankingDetailsJson(mRecord_Account.BankingDetailsMaturityJson);
  }

  // Interest Payment
  switch(mAccountType.AccountClass) {
    case "Deposit":
      // Deposits
      C.lblPaymentDetailsOutgoing.Text("Interest Payment details");
      C.apdPaymentDetailsOutgoing.PaymentMethodAllowBlank(false);
      switch(C.afFinancial.InterestPaymentType()) {
        case "Cheque":
          C.lblPaymentDetailsOutgoing.VisibleRow(true);
          C.lblInterestTransferTo.VisibleRow(false);
          C.cboInterestTransferToAccount.VisibleRow(false);
          break;

        case "Capitalise":
          C.lblPaymentDetailsOutgoing.VisibleRow(false);
          C.lblInterestTransferTo.VisibleRow(false);
          C.cboInterestTransferToAccount.VisibleRow(false);
          break;

        case "Compound":
          C.lblPaymentDetailsOutgoing.VisibleRow(false);
          C.lblInterestTransferTo.VisibleRow(false);
          C.cboInterestTransferToAccount.VisibleRow(false);
          break;

        case "DirectCredit":
          C.lblPaymentDetailsOutgoing.VisibleRow(true);
          C.lblInterestTransferTo.VisibleRow(false);
          C.cboInterestTransferToAccount.VisibleRow(false);
          break;

        case "Transfer":
          C.lblPaymentDetailsOutgoing.VisibleRow(false);
          C.lblInterestTransferTo.VisibleRow(true);
          C.cboInterestTransferToAccount.VisibleRow(true);

          if (mRecord_Page_Other.MaturityAccountFilter) {
            // Use "@" prefix to ensure a proper list is displayed rather than an Account Search dropdown
            C.cboInterestTransferToAccount.RefreshFromStandardRange("@Accounts", mRecord_Page_Other.MaturityAccountFilter);
          }
          else {
            C.cboInterestTransferToAccount.RefreshFromStandardRange("Accounts", mRecord_Page_Other.MaturityAccountFilter);
          }
          break;

        default:
          window.alert("Interest Payment Type '" + C.afFinancial.InterestPaymentType() + "' not handled.");
      }
      break;

    default:
      // Loans
      C.lblPaymentDetailsOutgoing.Text("Outgoing Payment details");
      C.apdPaymentDetailsOutgoing.PaymentMethodAllowBlank(true);
      C.lblInterestTransferTo.VisibleRow(false);
      C.cboInterestTransferToAccount.VisibleRow(false);
      break;
  }

  // Maturity Instructions
  switch(mAccountType.AccountClass) {
    case "Deposit":
      // Deposits
      if (!mRecord_Page_Other || C.afFinancial.TermCycle() == "On Call") {
        C.lblMaturityInstructions.VisibleRow(false);
        C.cboMaturityInstruction.VisibleRow(false);
        C.lblMaturityReinvestment.VisibleRow(false);
        C.numMaturityValue.VisibleRow(false);
        C.cboMaturityAccountType.VisibleRow(false);
        C.cboMaturityAccount.VisibleRow(false);
        C.cboMaturityPaymentType.VisibleRow(false);
        C.cboMaturityTransferToAccount.VisibleRow(false);
        C.lblPaymentDetailsMaturity.VisibleRow(false);
        C.apdPaymentDetailsMaturity.Visible(false);
      }
      else {
        C.lblMaturityInstructions.VisibleRow(true);
        C.cboMaturityInstruction.VisibleRow(true);
        C.cboMaturityInstruction.ListFromCodeDescriptionList(mRecord_Page_Other.MaturityAvailableInstructionsList);
        C.cboMaturityInstruction.Text(mRecord_Page_Other.MaturityInstructionText);
        C.cboMaturityAccountType.RefreshFromStandardRange("AccountTypes", mRecord_Page_Other.MaturityAccountTypeFilter);
        if (mRecord_Page_Other.MaturityAccountFilter) {
          // Use "@" prefix to ensure a proper list is displayed rather than an Account Search dropdown
          C.cboMaturityAccount.RefreshFromStandardRange("@Accounts", mRecord_Page_Other.MaturityAccountFilter);
        }
        else {
          C.cboMaturityAccount.RefreshFromStandardRange("Accounts", mRecord_Page_Other.MaturityAccountFilter);
        }

        C.cboMaturityPaymentType.ListFromCodeDescriptionList(mRecord_Page_Other.MaturityPaymentAvailableTypesList);
        C.cboMaturityPaymentType.Text(mRecord_Page_Other.MaturityPaymentTypeText);
        if (mRecord_Page_Other.MaturityAccountFilter) {
          // Use "@" prefix to ensure a proper list is displayed rather than an Account Search dropdown
          C.cboMaturityTransferToAccount.RefreshFromStandardRange("@Accounts", mRecord_Page_Other.MaturityAccountFilter);
        }
        else {
          C.cboMaturityTransferToAccount.RefreshFromStandardRange("Accounts", mRecord_Page_Other.MaturityAccountFilter);
        }

        cboMaturityInstruction_Change();
      }
      break;

    default:
      // Loans
      C.lblMaturityInstructions.VisibleRow(false);
      C.cboMaturityInstruction.VisibleRow(false);
      C.lblMaturityReinvestment.VisibleRow(false);
      C.numMaturityValue.VisibleRow(false);
      C.cboMaturityAccountType.VisibleRow(false);
      C.cboMaturityAccount.VisibleRow(false);
      C.cboMaturityPaymentType.VisibleRow(false);
      C.cboMaturityTransferToAccount.VisibleRow(false);
      break;
  }

  // Auto-Format to sort out topmost headings
  tabWizard.AutoFormatPage();
}

// ============
// pageFinalise
// ============
function pageFinalise_Refresh() {
  // Controls
  if (mAccountType.AccountClass == "Deposit") {
    C.lblPrintContract.Text("Do you wish to generate a Deposit Certificate for this Account?");
    C.chkPrintContract.Caption("Generate a Deposit Certificate document?");
  }
  else {
    C.lblPrintContract.Text("Do you wish to generate a Contract for this Account?");
    C.chkPrintContract.Caption("Generate a Contract document?");
  }
}

// =================
// Fetch Tab Details
// =================
function tabWizard_FetchDetails(page) {
  var params;

  // Save Fields
  Fields_Save();

  // Create Parameters
  switch(page) {
    case "Clients":
    case "Name":
    case "Other":
      params = { AccountDetails: mRecord_Account };
      break;
  }

  if (params) {
    // Extend parameters
    params.pageId = page;

    // Block UI
    widget.UI.Block("Fetching details, please wait...");

    widget.GetString("WizardRefresh", params,
      function (data) { tabWizard_FetchDetails_Done(page, data); },
      function (error) { tabWizard_FetchDetails_Fail(page, error); }
    );
  }
}

function tabWizard_FetchDetails_Done(page, data) {
  // Parse
  data = JSON.parse(data);

  switch(page) {
    case "Clients":
      // Client Account Roles may have been tweaked
      mRecord_Account.Clients = data;
      mRecord_Clients = data;

      gridClients_Refresh();
      break;

    case "Name":
      // Default Name and Description
      if (!C.txtName.Text() || C.txtName.Text() == mLastDefaultName) C.txtName.Text(data.DefaultName);
      if (!C.txtDescription.Text() || (mRecord_Page_Name &amp;&amp; mRecord_Page_Name.AccountTypeId != C.cboAccountType.Text())) C.txtDescription.Text(data.DefaultDescription);

      mLastDefaultName = data.DefaultName;
      mLastDefaultDescription = data.DefaultDescription;
      mRecord_Page_Name = data;
      pageName_Refresh();
      break;

    case "Other":
      mRecord_Page_Other = data;
      pageOther_Refresh();
      break;
  }

  // Unblock UI
  widget.UI.Unblock();
}

function tabWizard_FetchDetails_Fail(page, error) {
  widget.UI.MsgBoxAlert(error);

  // Unblock UI
  widget.UI.Unblock();
}

// =========
// Calculate
// =========
function Calculate(fieldUpdated, action) {
  // Save Fields
  Fields_Save(fieldUpdated);

  // Block UI
  if (action) {
    widget.UI.Block("Actioning, please wait...");
  }

  // Set Action
  mRecord_Account.Action = action ? action : "";

  // Promotion has changed? Force Account Type to recalculate
  if (mAccountTypePromotionChanged) {
    var accountCalc = JSON.parse(mRecord_Account.AccountCalcJson);
    if (accountCalc.AccountTypeIdOriginal &amp;&amp; accountCalc.AccountTypeIdOriginal.length != 0) {
      accountCalc.AccountTypeIdOriginal = "[[Recalc]]";
    }
    else {
      accountCalc.AccountTypeIdOriginal = "";
    }
    mRecord_Account.AccountCalcJson = JSON.stringify(accountCalc);

    mAccountTypePromotionChanged = false;
  }

  // Calculate
  widget.GetString("Calculate", mRecord_Account, Calculate_Done, Calculate_Fail);
}

function Calculate_Done(data) {
  // Parse
  data = JSON.parse(data);

  // Update record
  mRecord_Account.AccountTypeIdOriginal = data.Account.AccountTypeId;
  mRecord_Account.AccountCalcJson = data.Account.AccountCalcJson;

  // Update Financial
  // NOTE: Since this may be a new, unsaved Account, supply a list of owner Clients so the Account Standard Transaction form can filter Transfer if required  
  C.afFinancial.FromAccountCalcJson(data.Account.AccountCalcJson, data.OwnerClientIds);  
  if (mRecord_Account.AccountId) C.afFinancial.SetAccountId(mRecord_Account.AccountId);
  C.afFinancial.Visible(true);

  // Update other fields that may have been affected, e.g., Review Date is affected by the Opening Date
  mRecord_Account.DateReview = data.Account.DateReview;
  mRecord_Account.StatementCycle = data.Account.StatementCycle;
  mRecord_Account.StatementDateFirst = data.Account.StatementDateFirst;

  mRecord_Account.MaturityInstructionText = data.Account.MaturityInstructionText;
  mRecord_Account.MaturityAccountTypeId = data.Account.MaturityAccountTypeId;

  C.dateReview.Value(mRecord_Account.DateReview);
  C.cboStatementCycle.Text(mRecord_Account.StatementCycle);
  C.dateStatementFirst.Value(mRecord_Account.StatementDateFirst);

  C.cboMaturityInstruction.Text(mRecord_Account.MaturityInstructionText);
  C.cboMaturityAccountType.Text(mRecord_Account.MaturityAccountTypeId);

  // No longer needs initialising
  mFinancialInitialise = false;

  // Update Summary
  C.wbAccountSummary.SetContent(data.AccountSummaryHtml, false);

  // Unblock UI
  widget.UI.Unblock();
}

function Calculate_Fail(error) {
  C.wbAccountSummary.SetContentError(error);

  // Unblock UI
  widget.UI.Unblock();
}

// =========
// cboBranch
// =========
function cboBranch_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Refresh Account Types
  cboAccountType_Refresh();
}

// =========
// cboDealer
// =========
function cboDealer_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Employees
  if (e) C.cboDealerEmployee.Text("");
  if (C.cboDealer.Text()) {
    C.cboDealerEmployee.RefreshFromStandardRange("ExternalPartiesDealerEmployees", "ExternalPartyId='" + C.cboDealer.Text() + "'", false);
  }

  // Refresh BDM
  if (e) cboBdm_Refresh();

  // Refresh Promotions List
  if (e &amp;&amp; mRecord.AddOnsPromotions) cboAccountTypePromotions_Refresh();
}

// =========
// cboBroker
// =========
function cboBroker_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Employees
  if (e) C.cboBrokerEmployee.Text("");
  if (C.cboBroker.Text()) {
    C.cboBrokerEmployee.RefreshFromStandardRange("ExternalPartiesBrokerEmployees", "ExternalPartyId='" + C.cboBroker.Text() + "'", false);
  }

  // Refresh BDM
  if (e) cboBdm_Refresh();

  // Refresh Promotions List
  if (e &amp;&amp; mRecord.AddOnsPromotions) cboAccountTypePromotions_Refresh();
}

// ======
// cboBdm
// ======
function cboBdm_Refresh() {
  //TODO: Refresh read-only BDM
}

// =================
// cboStatementCycle
// =================
function cboStatementCycle_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Controls
  switch(C.cboStatementCycle.Text().toUpperCase()) {
    case "NONE":
    case "ON DEMAND":
      C.dateStatementFirst.VisibleRow(false);
      break;

    default:
      C.dateStatementFirst.VisibleRow(true);
  }

  // Refresh Date
  if (e &amp;&amp; C.dateStatementFirst.VisibleRow()) {
    // Clear existing date
    C.dateStatementFirst.Value(null);

    // Save Fields
    Fields_Save();

    // Get Next Statement Date
    var params = {
      Account: mRecord_Account,
      StatementCycle: C.cboStatementCycle.Text()
    };
    widget.GetString("GetNextStatementDate", params, cboStatementCycle_Change_Done, function(errorMessage) {
      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }
}

function cboStatementCycle_Change_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);

  // Set Date
  if (data) {
    C.dateStatementFirst.Value(data.StatementDateNext);
  }
}

// ======================
// cboMaturityInstruction
// ======================
function cboMaturityInstruction_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Initialise
  var maturityInstruction = (C.cboMaturityInstruction.ListIndex() == -1 ? "" : mRecord_Page_Other.MaturityAvailableInstructionsList[C.cboMaturityInstruction.ListIndex()].Code);

  // Controls
  switch(maturityInstruction) {
    case "ReinvestAll":
      C.lblMaturityReinvestment.VisibleRow(true);
      C.numMaturityValue.VisibleRow(false);
      C.cboMaturityAccountType.VisibleRow(true);
      C.cboMaturityAccount.VisibleRow(true);

      C.lblPaymentDetailsMaturity.VisibleRow(false);
      C.cboMaturityPaymentType.VisibleRow(false);
      C.cboMaturityTransferToAccount.VisibleRow(false);
      C.apdPaymentDetailsMaturity.Visible(false);
      break;

    case "ReinvestAmount":
      C.lblMaturityReinvestment.VisibleRow(true);
      C.numMaturityValue.VisibleRow(true);
      C.cboMaturityAccountType.VisibleRow(true);
      C.cboMaturityAccount.VisibleRow(true);

      C.lblPaymentDetailsMaturity.VisibleRow(true);
      C.cboMaturityPaymentType.VisibleRow(true);
      cboMaturityPaymentType_Change();
      break;

    case "ReinvestPrincipal":
      C.lblMaturityReinvestment.VisibleRow(true);
      C.numMaturityValue.VisibleRow(false);
      C.cboMaturityAccountType.VisibleRow(true);
      C.cboMaturityAccount.VisibleRow(true);

      C.lblPaymentDetailsMaturity.VisibleRow(true);
      C.cboMaturityPaymentType.VisibleRow(true);
      C.cboMaturityTransferToAccount.VisibleRow(false);
      C.apdPaymentDetailsMaturity.Visible(true);
      break;

    case "PayoutAll":
      C.lblMaturityReinvestment.VisibleRow(false);
      C.numMaturityValue.VisibleRow(false);
      C.cboMaturityAccountType.VisibleRow(false);
      C.cboMaturityAccount.VisibleRow(false);

      C.lblPaymentDetailsMaturity.VisibleRow(true);
      C.cboMaturityPaymentType.VisibleRow(true);
      cboMaturityPaymentType_Change();
      break;

    case "ToBeAdvised":
      C.lblMaturityReinvestment.VisibleRow(false);
      C.numMaturityValue.VisibleRow(false);
      C.cboMaturityAccountType.VisibleRow(false);
      C.cboMaturityAccount.VisibleRow(false);

      C.lblPaymentDetailsMaturity.VisibleRow(false);
      C.cboMaturityPaymentType.VisibleRow(false);
      C.cboMaturityTransferToAccount.VisibleRow(false);
      C.apdPaymentDetailsMaturity.Visible(false);
      break;

    default:
      C.lblMaturityReinvestment.VisibleRow(false);
      C.numMaturityValue.VisibleRow(false);
      C.cboMaturityAccountType.VisibleRow(false);
      C.cboMaturityAccount.VisibleRow(false);

      C.lblPaymentDetailsMaturity.VisibleRow(false);
      C.cboMaturityPaymentType.VisibleRow(false);
      C.cboMaturityTransferToAccount.VisibleRow(false);
      C.apdPaymentDetailsMaturity.Visible(false);
      break;
  }
}

// ======================
// cboMaturityPaymentType
// ======================
function cboMaturityPaymentType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Initialise
  var maturityPaymentType = (C.cboMaturityPaymentType.ListIndex() == -1 ? "" : mRecord_Page_Other.MaturityPaymentAvailableTypesList[C.cboMaturityPaymentType.ListIndex()].Code);

  // Controls
  switch(maturityPaymentType) {
    case "Cheque":
      C.cboMaturityTransferToAccount.VisibleRow(false);
      C.apdPaymentDetailsMaturity.Visible(true);
      C.apdPaymentDetailsMaturity.PaymentTypeCategoryFilter("Cheque");
      break;

    case "DirectCredit":
      C.cboMaturityTransferToAccount.VisibleRow(false);
      C.apdPaymentDetailsMaturity.Visible(true);
      C.apdPaymentDetailsMaturity.PaymentTypeCategoryFilter("DirectCredit");
      break;

    case "Transfer":
      C.cboMaturityTransferToAccount.VisibleRow(true);
      C.apdPaymentDetailsMaturity.Visible(false);
      break;

    default:
      C.cboMaturityTransferToAccount.VisibleRow(false);
      C.apdPaymentDetailsMaturity.Visible(false);
      break;
  }
}

function chkQuote_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  C.chkQuoteReady.ReadOnly(! C.chkQuote.Value());
  C.cboQuoteNotes.ReadOnly(! C.chkQuote.Value());
  
  tabWizard_Resize();
}

// =======================
// New Client (Individual)
// =======================
function NewClientIndividual() {
  // Parameters
  var params = {};
  if (mRecord.WidgetClientNewIndividual_StartupParametersJson) params = JSON.parse(mRecord.WidgetClientNewIndividual_StartupParametersJson);
  params.ShowNewRecordOnFinish = false;

  // Show Widget
  widget.UI.Forms.ShowHtmlWidgetModal(mRecord.WidgetClientNewIndividual, { startupParametersJson: JSON.stringify(params) }, NewClientIndividual_Notify);
}

function NewClientIndividual_Notify(actionId, data) {
  // Parse
  data = JSON.parse(data);

  // Handle
  switch(actionId) {
    case "RecordAdded":
      AddClient(data.ClientId);
      break;
  }
}

// =========================
// New Client (Organisation)
// =========================
function NewClientOrganisation() {
  // Parameters
  var params = {};
  if (mRecord.WidgetClientNewOrganisation_StartupParametersJson) params = JSON.parse(mRecord.WidgetClientNewOrganisation_StartupParametersJson);
  params.ShowNewRecordOnFinish = false;

  // Show Widget
  widget.UI.Forms.ShowHtmlWidgetModal(mRecord.WidgetClientNewOrganisation, { startupParametersJson: JSON.stringify(params) }, NewClientOrganisation_Notify);
}

function NewClientOrganisation_Notify(actionId, data) {
  // Parse
  data = JSON.parse(data);

  // Handle
  switch(actionId) {
    case "RecordAdded":
      AddClient(data.ClientId);
      break;
  }
}

// ==================
// Edit Security Item
// ==================
function EditSecurityItem(index) {
  mEditSecurityItemIndex = index;
  var json = index == -1 ? "" : mRecord_SecurityItems[index].Json;

  // Parameters
  var params = {};
  if (mRecord.WidgetSecurityStmtItem_StartupParametersJson) params = JSON.parse(mRecord.WidgetSecurityStmtItem_StartupParametersJson);
  params.BranchId = C.cboBranch.Text();
  params.EditJson = true;
  params.ProductTypeId = C.blProductTypes.SelectedItemId();
  params.SecurityStmtItemJson = json;

  // Show Widget
  widget.UI.Forms.ShowHtmlWidgetModal(mRecord.WidgetSecurityStmtItem, { startupParametersJson: JSON.stringify(params) }, NewSecurityItem_Notify);
}

function NewSecurityItem_Notify(actionId, data) {
  // Parse
  var dataRaw = data;
  data = JSON.parse(data);

  // Handle
  switch(actionId) {
    case "RecordUpdated":
      // Update underlying data
      var item;
      if (mEditSecurityItemIndex == -1) {
        // New
        item = { Pk: 0 };
        mRecord_SecurityItems.push(item);
      }
      else {
        // Existing
        item = mRecord_SecurityItems[mEditSecurityItemIndex];
      }
      item.Json = dataRaw;

      // Save Fields
      Fields_Save();

      // Block UI
      widget.UI.Block("Refreshing Security Items, please wait...");

      // Refresh Grid
      widget.GetString("GetSecurityItemsRefreshed", mRecord_Account,
        function (data) {
          // Parse
          mRecord_SecurityItems = JSON.parse(data);
          mRecord_Account.SecurityItems = mRecord_SecurityItems;

          // Refresh Grid
          C.gridSecurityItems.VirtualDataRefresh(mRecord_SecurityItems, -2);
          if (mEditSecurityItemIndex == -1) C.gridSecurityItems.ActivateLastDataRow();

          widget.UI.Unblock();
        },

        function (error) {
          widget.UI.MsgBoxAlert(error);

          // Unblock UI
          widget.UI.Unblock();
        });
      break;
  }
}

// =================
// Edit Disbursement
// =================
function EditDisbursement(index) {
  mEditDisbursementIndex = index;
  var json = index == -1 ? "" : mRecord_Disbursements[index].Json;

  // Parameters
  var params = {};
  if (mRecord.WidgetDisbursement_StartupParametersJson) params = JSON.parse(mRecord.WidgetDisbursement_StartupParametersJson);
  params.EditJson = true;
  params.DisbursementJson = json;

  // Show Widget
  widget.UI.Forms.ShowHtmlWidgetModal(mRecord.WidgetDisbursement, { startupParametersJson: JSON.stringify(params) }, NewDisbursement_Notify);
}

function NewDisbursement_Notify(actionId, data) {
  // Parse
  var dataRaw = data;
  data = JSON.parse(data);

  // Handle
  switch(actionId) {
    case "RecordUpdated":
      // Update underlying data

      var item;
      if (mEditDisbursementIndex == -1) {
        // New
        item = { Pk: 0 };
        mRecord_Disbursements.push(item);
      }
      else {
        // Existing
        item = mRecord_Disbursements[mEditDisbursementIndex];
      }
      item.Json = dataRaw;

      // Refresh
      RefreshDisbursements(false);
      break;
  }
}

// =================================================================================================================================
// Refresh Disbursements (after adding, editting, or Disbursement Date must be updated as part of validating the Disbursements page)
// =================================================================================================================================
function RefreshDisbursements(matchDateToOpening) {
  // Block UI
  widget.UI.Block("Refreshing Disbursements, please wait...");
  
  // Save Fields
  Fields_Save();  

  // Match Date?
  mRecord_Account.MatchDisbursementDateToOpening = matchDateToOpening;

  // Refresh Grid
  widget.GetString("GetDisbursementsRefreshed", mRecord_Account,
    function (data) {
      // Parse
      mRecord_Disbursements = JSON.parse(data);
      mRecord_Account.Disbursements = mRecord_Disbursements;

      // Refresh Grid
      C.gridDisbursements.VirtualDataRefresh(mRecord_Disbursements, -2);
      if (mEditDisbursementIndex == -1) C.gridDisbursements.ActivateLastDataRow();

      // Unblock UI
      widget.UI.Unblock();
      
      // Move if updating dates
      if (matchDateToOpening) tabWizard_Move(1);
    },

    function (error) {
      widget.UI.MsgBoxAlert(error);

      // Unblock UI
      widget.UI.Unblock();
    }
  );
}

// =============
// Show Schedule
// =============
function ScheduleShow() {
  // Save Fields
  Fields_Save();

  // Block UI
  widget.UI.Block("Fetching Schedule, please wait...");

  // Clear Field Updated and Action
  mRecord_Account.Action = "";
  mRecord_Account.FieldUpdated = "";

  // Calculate
  widget.GetString("GetAccountSchedule", mRecord_Account, ScheduleShow_Done, ScheduleShow_Fail);
}

function ScheduleShow_Done(data) {
  // Unblock UI
  widget.UI.Unblock();

  // Show Schedule
  widget.UI.Forms.ShowAccountSchedule({scheduleJson: data});
}

function ScheduleShow_Fail(error) {
  // Unblock UI
  widget.UI.Unblock();

  widget.UI.MsgBoxAlert(error);
}

// ==============
// Preview Client
// ==============
function PreviewClient(clientId) {
  widget.GetString("GetClientPreview", { clientId: clientId },
    function (data) {
      widget.UI.Forms.ShowHtml("Client Summary", data, {});
    },

    function (error) {
      widget.UI.MsgBoxAlert(error);
    });
}

// =================
// Advanced handling
// =================
function AdvancedInitialise() {
  // Tweaks
  switch(mRecord.ShowBranch.toUpperCase()) {
    case "TRUE":
      C.lblBranch.Text("Specify Branch and Department");
      break;

    case "FALSE":
      C.lblBranch.Text("Specify Department");
      break;

    case "ADVANCED":
      $("#trBranch").attr("advancedId", "Branch");
      $("#trBranchDepartment").attr("advancedId", "Branch");
      if (mAdvancedVisible) {
        C.lblBranch.Text("Specify Branch and Department");
      }
      else {
        C.lblBranch.Text("Specify Department");
      }
      break;
  }

  // General
  AdvancedInitialiseSection("Branch", mRecord.ShowBranch);
  AdvancedInitialiseSection("Dealer", mRecord.ShowDealer);
  AdvancedInitialiseSection("Broker", mRecord.ShowBroker);
  AdvancedInitialiseSection("AccountManager", mRecord.ShowAccountManager);
  AdvancedInitialiseSection("Pool", mRecord.ShowPool);

  // Name
  AdvancedInitialiseSection("PurposeSourceRegion", mRecord.ShowPurposeSourceRegion);
  AdvancedInitialiseSection("Insurance", mRecord.ShowInsurance);
}

function AdvancedInitialiseSection(id, option) {
  // Get elements
  var els=$("*[advancedId='" + id + "']");

  // Update
  switch(option.toUpperCase()) {
    case "TRUE":
      // Always show, i.e., not advanced
      break;

    case "FALSE":
      // Never show
      els.hide();
      break;

    case "ADVANCED":
      // Only show in 'Advanced' mode
      els.addClass("advanced");
      break;
  }
}

function AdvancedToggle() {
  // Toggle Advanced
  mAdvancedVisible = !mAdvancedVisible;

  // Update Controls
  if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }

  // Other
  switch (tabWizard.SelectedTabId()) {
    case "Clients":
      gridClients_Refresh();
      break;
  }

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

// =====================
// Update Client Details
// =====================
function UpdateClientDetails(index) {
  var item = mRecord_Clients[index];

  // Clear informational values
  item.ClientName = null;

  // Lookup
  if (item.ClientId) {
   widget.GetString("GetClientDetails", { clientId: item.ClientId },
      function (data) {
        // Parse
        data = JSON.parse(data);

        // Update objects
        item.ClientId = data.ClientId;
        item.ClientName = data.Name;
        item.ClientStatus = data.Status;

        // Refresh Grid rows
        C.gridClients.RefreshRow(index);
      },

      function (error) {
        // Ignore
        console.warn(error);
      }
    );
  }
}

// ==============
// Print Qutation
// ==============
function PrintQuotation() {
  // Confirm
  widget.UI.MsgBoxConfirm("Generate a Quotation document?", { heading: "Print Quotation", icon: "DocumentType_PDF"}, function () {
    // Save Fields
    Fields_Save();
    mRecord_Account.QuoteClientId = C.cboQuoteClient.Text();
  
    // Print Quotation
    widget.DownloadFile("PrintQuotation", mRecord_Account);
  });
}

// =========================
// apdPaymentDetailsMaturity
// =========================
function apdPaymentDetailsMaturity_PaymentMethodChange(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Act as if the Payment Type has changed since this may have been changed from the Client Bank Account Lookup
  cboMaturityPaymentType_Change();
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>Lb6HVnADwkahjErWIPNvYw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowBranch" type="List">
            <BlankTip />
            <Caption>Show Branch and Department</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowDealer" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowBroker" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccountManager" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowPool" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowClientAdditional" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowPurposeSourceRegion" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowInsurance" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>HTML Widgets.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="UseBuiltInClientIndividualWidget" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="UseBuiltInClientOrganisationWidget" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="UseBuiltInDisbursementWidget" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="UseBuiltInSecurityStatementItemWidget" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="StdTransWidgetId" type="List">
            <BlankTip />
            <Caption>Edit Standard Transaction Widget:</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Scripts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AccountId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Accounts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ProductType" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.ProductTypes</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountType" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.AccountTypes</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ClientsToAdd" type="Range">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <Rows>1</Rows>
            <RangeSingle>false</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>Clients</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="DuplicateAccountId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Accounts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="RefinancedAccountId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Accounts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="QuoteMode" type="Boolean">
            <BlankTip />
            <Caption>Quote Mode?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>