<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-05T04:42:07.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-07-30T23:37:36.6600000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-05T04:41:54.3990000</UpdatedUtcDate>
    <ScriptId>HWAC</ScriptId>
    <Description>Account Close</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountClose
Option Explicit On
Option Strict On

' #################################################################
' Account Close wizard HTML Widget
'
' Copyright (C) Intersoft Systems Limited 2021
'
' Version: 1.18 (05/08/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.08  24/05/2021  ISS
'    1.09  15/11/2021  ISS      J026790   Added 'Reinvest' Support for Deposit Accounts
'          22/11/2021  ISS      J027721   Transaction Type list issue
'    1.10  18/03/2022  ISS      J028462   Updated Data View Filter reference to finTransactionTypes.GetDataViewFilter_AccountClose
'    1.11  20/06/2022  ISS      J028993   Fixed blank values in the Summary Grid, Credit column
'    1.12  07/09/2022  ISS      J029424   Now supports Bank Interface Send return message  
'    1.13  26/01/2023  ISS      J030338   Allow other Clients to be emailed
'    1.14  11/05/2023  ISS      J031059   Updated wording on the Schedule
'          12/06/2023  ISS      J030460   Added support For 'Refinance' Close Method
'    1.15  07/07/2023  ISS      J030262   Print Summary Document will now generate correctly
'    1.16  16/10/2023  ISS      J031553   Improved handling for Cash Registers
'          20/11/2023  ISS      J031388   Fixed accruals calculation when updating values
'    1.17  14/02/2024  ISS      J032903   Warnings are now displayed if a User doesn't have Permission to Close (or update to Closed Pending) an Account
'    1.18  31/07/2024  ISS      J033963   Changing Accrued Other Interest label to use Other Interest Description
'          05/08/2024  ISS      J033999   Correctly defaulting close method for early settlements
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountClose"

' Common Parameters
Private mAccountId As String
Private mChargeAndWriteOff As Boolean
Private mCloseDate As Date
Private mCloseMethod As isefinAccountCloseMethod
Private mCloseMethodText As String
Private mReadOnly As Boolean
Private mWriteOff As Boolean

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

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

  ' 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")
    mChargeAndWriteOff = .GetBoolean("ChargeAndWriteOff")
    mCloseDate = .GetDate("CloseDate")
    mCloseMethodText = .GetString("CloseMethod")
    mReadOnly = .GetBoolean("ReadOnly")
    mWriteOff = .GetBoolean("WriteOff")
  End With

  ' Update Parameters
  If eventId &lt;&gt; "" Then
    If Len(mCloseMethodText) &lt;&gt; 0 Then
      If Not [Enum].TryParse(Of isefinAccountCloseMethod)(mCloseMethodText, mCloseMethod) Then
        Main = False
        finBL.Error.ErrorBeginFormat("Invalid Close Method '{0}'.", mCloseMethodText)      
      End If
    End If
  End If
  
  ' Handle Events
  If Main Then
    Select Case eventId
      Case ""
        ' Main event, i.e., return initial HTML content (excluding html and body tags)
        returnValue = ScriptInfo.TemplateText
  
      Case "Finish"
        ' Finish wizard
        Main = Finish(parametersJson, requestInfo, returnValue)
  
      Case "Form_PaymentMethod_Change"
        ' Get updated form information based on values changing, namely the Payment Method
        Main = Form_PaymentMethod_Change(parametersJson, returnValue)
  
      Case "Form_TransactionType_Change"
        ' Get updated form information based on values changing, namely the Transaction Type
        Main = Form_TransactionType_Change(parametersJson, returnValue)
  
      Case "Form_ExecuteAction"
        ' Get updated form information based on values changing, namely the Transaction Type
        Main = Form_ExecuteAction(parametersJson, returnValue)
  
      Case "GetAccountClose"
        ' Get updated form information based on values changing
        Main = GetAccountClose(parametersJson, returnValue)
  
      Case "GetAccountSchedule"
        ' Get Account Schedule
        Main = GetAccountSchedule(parametersJson, returnValue)
  
      Case "GetRefinanceSummary"
        ' Get Refinance Summary
        Main = GetRefinanceSummary(parametersJson, returnValue)
        
      Case "GetInitialAccountClose"
        ' Get updated form information based on values changing
        Main = GetInitialAccountClose(parametersJson, returnValue)
  
      Case "GetInitialisationInfo"
        ' Get Initialisation Information required for this wizard
        Main = GetInitialisationInfo(returnValue)
  
      Case "GetSecurityStmtInformation"
        ' Get Security Statement Information
        Main = GetSecurityStmtInformation(returnValue)
  
      Case "GetSecuritySummary"
        ' Get Security Summary
        Main = GetSecuritySummary(parametersJson, returnValue)
        
      Case "GetSummaryItemPreview"
        ' Get Summary Item Preview
        Main = GetSummaryItemPreview(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 If  

End Function

''' &lt;summary&gt;
'''  Create a finAccountClose object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountClose(parameters As WizardFinishParameters,
                                    ByRef accountClose As finAccountClose) As Boolean

  Dim AccountCloseRefinanceOption As isefinAccountCloseRefinanceOption
  Dim ReverseValues As Integer
  Dim Success As Boolean
  Dim SummaryItem As SummaryItem

  ' Assume Success
  Success = True

  ' Initialise
  accountClose = finBL.CreateAccountClose()

  ' Load Account
  Success = accountClose.AccountLoad(mAccountId)

  ' Reverse Values?
  If Success Then
    Select Case accountClose.Account.AccountClass
      Case isefinAccountClass.Deposit
        ReverseValues = -1

      Case Else
        ReverseValues = 1
    End Select
  End If

  ' Set Startup Parameters
  If Success AndAlso parameters Is Nothing Then
    With accountClose
      If mCloseMethod &lt;&gt; isefinAccountCloseMethod.NotClosed Then
        ' Use the user specified value
        .CloseMethod = mCloseMethod
      Else
        ' Use finAccountClose default value.
        mCloseMethod = .CloseMethod
      End If
      
      ' Close Date
      If Success AndAlso mCloseDate &lt;&gt; Nothing Then
        .CloseDate = mCloseDate
        Success = .Calculate()
      End If

      ' Write off
      If Success AndAlso mWriteOff Then
        .CloseMethod = isefinAccountCloseMethod.WrittenOff
        Success = .Calculate()
      End If

      ' Charge and Write off
      If Success AndAlso mChargeAndWriteOff AndAlso Not mWriteOff Then
        .AdjustmentValue = -.BalanceDue
      End If
    End With
  End If

  ' Calculate Initial values
  If Success AndAlso parameters IsNot Nothing Then
    With accountClose
      ' General
      .CloseDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.CloseDate)
      .CloseMethodText = parameters.CloseMethodText
      .FuturePaymentsShow = parameters.FuturePaymentsShow
      .CloseNote = parameters.CloseNote

      ' Calculate
      Success = .Calculate()

      ' Set Close Pending after Calculate as it will be reset
      .ClosePending = parameters.ClosePending
      .ClosePendingReviewDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.ClosePendingReviewDate)
    End With
  End If

  ' Update
  If Success AndAlso parameters IsNot Nothing Then
    ' Summary Items
    If parameters.SummaryItems IsNot Nothing Then
      For Each SummaryItem In parameters.SummaryItems
        If Not SummaryItem.CreditReadOnly Then
          With accountClose.Summary(SummaryItem.RowIndex)
            .Credit = finBL.Runtime.NumberUtilities.ConvertToCurrency(SummaryItem.Credit * ReverseValues)
            .TransactionNotes = SummaryItem.TransactionNotes
          End With
        End If
      Next
    End If

    With accountClose
      ' Balance
      .AccruedDefaultInterest = parameters.AccruedDefaultInterest * ReverseValues
      .AccruedDefaultInterestCharge = parameters.AccruedDefaultInterestCharge
      .AccruedInterest = parameters.AccruedInterest * ReverseValues
      .AccruedInterestCharge = parameters.AccruedInterestCharge
      .AccruedOtherInterest = parameters.AccruedOtherInterest * ReverseValues
      .AccruedOtherInterestCharge = parameters.AccruedOtherInterestCharge
      .AdjustmentValue = parameters.AdjustmentValue
      .CloseMethodText = parameters.CloseMethodText      
      .FeeChargeFee = parameters.FeeChargeFee
      .FeeValue = parameters.FeeValue * ReverseValues
      .LossValue = parameters.LossValue
      .Other1Charge = parameters.Other1Charge
      .Other1Value = parameters.Other1Value * ReverseValues
      .Other2Charge = parameters.Other2Charge
      .Other2Value = parameters.Other2Value * ReverseValues
      .ResidualValueCredit = parameters.ResidualCreditResidual
      .ResidualValue = parameters.ResidualValue * ReverseValues
      .UnpostedDefaultFeesCharge = parameters.UnpostedDefaultFeesCharge
      .UnpostedDefaultFees = parameters.UnpostedDefaultFees * ReverseValues
      .UnpostedOverLimitFeesCharge = parameters.UnpostedOverLimitFeesCharge
      .UnpostedOverLimitFees = parameters.UnpostedOverLimitFees * ReverseValues
      .UnpostedFacilityFeesCharge = parameters.UnpostedFacilityFeesCharge
      .UnpostedFacilityFees = parameters.UnpostedFacilityFees * ReverseValues
      .UnpostedStandardTransactionsCharge = parameters.UnpostedStandardTransactionsCharge

      ' Withholding Tax
      If .Account.SupportsWithholdingTax Then
        .WithholdingTaxValue = (.AccruedInterest * CDec(.WithholdingTaxRate / 100))
      End If      
      
      ' Transaction
      .TransactionTypeId = parameters.TransactionTypeId
      .TransactionReference = parameters.TransactionReference
      .TransactionNotes = parameters.TransactionNotes

      ' Document
      .PrintSummary = parameters.PrintSummary
      
      ' Reinvest
      If .CloseMethod = isefinAccountCloseMethod.Reinvested AndAlso Len(parameters.ReinvestedOption) &lt;&gt; 0 Then
        If [Enum].TryParse(Of isefinAccountCloseRefinanceOption) (parameters.ReinvestedOption, AccountCloseRefinanceOption) Then                
          .RefinanceOption = AccountCloseRefinanceOption
          .RefinanceAccountTypeId = parameters.ReinvestedAccountTypeId
          .RefinanceAccountTypePromotionId = parameters.ReinvestedAccountTypePromotionId
          .RefinanceIntoAccountId = parameters.ReinvestedToAccountId
        Else 
          Success = False
        End If
      End If

      ' Refinanced      
      If Success AndAlso .CloseMethod = isefinAccountCloseMethod.Refinanced AndAlso Len(parameters.RefinancedOption) &lt;&gt; 0 Then
        If [Enum].TryParse(Of isefinAccountCloseRefinanceOption) (parameters.RefinancedOption, AccountCloseRefinanceOption) Then                
          .RefinanceOption = AccountCloseRefinanceOption                             
          
          Select Case .RefinanceOption
            Case isefinAccountCloseRefinanceOption.ExistingAccount
              ' Existing Account
              .RefinanceIntoAccountId = parameters.RefinancedToAccountId
              .RefinanceIntoMainSecurityStmtIsFromRefinancedAccount = GetRefinanceIntoMainSecurityStmtIsFromRefinancedAccount(.Account, parameters.RefinanceIntoMainSecurityStmtIsFromRefinancedAccountSecurityStmtId)
              .RefinanceIntoCopySecurityStmtItems = parameters.RefinanceIntoCopySecurityStmtItems
              .RefinanceIntoDischargeSecurityStmt = parameters.RefinanceIntoDischargeSecurityStmt
              
              .ClosePending = False
              .ClosePendingReviewDate = Nothing
              
            Case isefinAccountCloseRefinanceOption.NewAccount
              ' New Account
              .RefinanceAccountTypeId = parameters.RefinancedAccountTypeId          
              .RefinanceAccountTypePromotionId = parameters.RefinancedAccountTypePromotionId 
              .RefinanceIntoMainSecurityStmtIsFromRefinancedAccount = False
              .RefinanceIntoCopySecurityStmtItems = False
              .RefinanceIntoDischargeSecurityStmt = False
              
              .ClosePending = True
          End Select          
        Else 
          Success = False
        End If
      End If
      
      ' Payment
      If Success Then
        .PaymentFeeCharge = parameters.PaymentFeeCharge
        Select .CloseMethod
          Case isefinAccountCloseMethod.Closed, isefinAccountCloseMethod.EarlyRedemption, isefinAccountCloseMethod.EarlySettlement
            If .BalanceDue &lt; 0 Then
              If Len(parameters.BankingDetailsOutgoingJson) &lt;&gt; 0 Then
                Success = .BankingDetails.FromHtmlWidgetJsonString(parameters.BankingDetailsOutgoingJson)
              End If
            ElseIf Len(parameters.BankingDetailsIncomingJson) &lt;&gt; 0 Then
              Success = .BankingDetails.FromHtmlWidgetJsonString(parameters.BankingDetailsIncomingJson)
            End If
            
            ' Cash Register
            If Success AndAlso Len(parameters.CashRegisterId) &lt;&gt; 0 Then
              .CashRegisterId = parameters.CashRegisterId
            End If
        End Select
      End If      
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get RefinanceIntoMainSecurityStmtIsFromRefinancedAccount option.
''' &lt;/summary&gt;
Private Function GetRefinanceIntoMainSecurityStmtIsFromRefinancedAccount(account As finAccount,
                                                                         securityStmtId As String) As Boolean
  
  ' Is from Refinanced Account?
  If Len(securityStmtId) &lt;&gt; 0 AndAlso Not account.SecurityStmt.IsNew Then
    If StrComp(account.SecurityStmt.SecurityStmtId, securityStmtId, CompareMethod.Text) = 0 Then
      Return True
    End If
  End If
  
  Return False
  
End Function

''' &lt;summary&gt;
'''  Create an AccountCloseData object from a finAccountClose object.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountCloseData(accountClose As finAccountClose,
                                        ByRef accountCloseData As AccountCloseData,
                                        finalise As Boolean) As Boolean

  Dim AllowUpdates As Boolean
  Dim ReverseValues As Decimal
  Dim Success As Boolean
  Dim SummaryItem As finAccountCloseSummaryItem

  ' Assume Success
  Success = True

  ' Initialise
  accountCloseData = New AccountCloseData()
  AllowUpdates = accountClose.AllowUpdateUI()

  ' Reverse Values?
  Select Case accountClose.Account.AccountClass
    Case isefinAccountClass.Deposit
      ReverseValues = -1

    Case Else
      ReverseValues = 1
  End Select

  ' Update
  If Success Then
    With accountCloseData
      ' General
      .CloseDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountClose.CloseDate)
      .CloseMethodText = AccountClose.CloseMethodText
      .FuturePaymentsShow = AccountClose.FuturePaymentsShow
      .FuturePayments = AccountClose.FuturePayments
      .ClosePending = AccountClose.ClosePending
      .CloseNote = AccountClose.CloseNote

      Select Case AccountClose.CloseMethod
        Case isefinAccountCloseMethod.BadDebtWriteOff
          ' Bad Debt Write Off
          If AccountClose.Account.ProductType IsNot Nothing Then
            accountCloseData.CloseNotesListId = AccountClose.Account.ProductType.AccountCloseNoteBadDebtWriteOffInformationListIdResolved
          End If
          accountCloseData.ShowClosePending = False
          accountCloseData.ShowFuturePaymentsShow = False

        Case isefinAccountCloseMethod.Cancelled
          ' Cancelled
          If AccountClose.Account.ProductType IsNot Nothing Then
            accountCloseData.CloseNotesListId = AccountClose.Account.ProductType.AccountCloseNoteCancelledInformationListIdResolved
          End If
          accountCloseData.ShowClosePending = False
          accountCloseData.ShowFuturePaymentsShow = False

        Case isefinAccountCloseMethod.Closed
          ' Closed
          If AccountClose.Account.ProductType IsNot Nothing Then
            accountCloseData.CloseNotesListId = AccountClose.Account.ProductType.AccountCloseNoteClosedInformationListIdResolved
          End If
          accountCloseData.ShowClosePending = AccountClose.Account.SupportsStatusClosedPending
          Select Case AccountClose.Account.AccountClass
            Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
              accountCloseData.ShowFuturePaymentsShow = True
            Case Else
              accountCloseData.ShowFuturePaymentsShow = False
          End Select

        Case isefinAccountCloseMethod.EarlyRedemption
          ' Early Redemtion
          If AccountClose.Account.ProductType IsNot Nothing Then
            accountCloseData.CloseNotesListId = AccountClose.Account.ProductType.AccountCloseNoteEarlyRedemptionInformationListIdResolved
          End If
          accountCloseData.ShowClosePending = AccountClose.Account.SupportsStatusClosedPending
          accountCloseData.ShowFuturePaymentsShow = False

        Case isefinAccountCloseMethod.EarlySettlement
          ' Early Settlement
          If AccountClose.Account.ProductType IsNot Nothing Then
            accountCloseData.CloseNotesListId = AccountClose.Account.ProductType.AccountCloseNoteEarlySettlementInformationListIdResolved
          End If
          accountCloseData.ShowClosePending = AccountClose.Account.SupportsStatusClosedPending
          Select Case AccountClose.Account.AccountClass
            Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
              accountCloseData.ShowFuturePaymentsShow = True
            Case Else
              accountCloseData.ShowFuturePaymentsShow = False
          End Select

        Case isefinAccountCloseMethod.Refinanced
          ' Refinance - for future use.
          If AccountClose.Account.ProductType IsNot Nothing Then
            accountCloseData.CloseNotesListId = AccountClose.Account.ProductType.AccountCloseNoteRefinanceInformationListIdResolved
          End If
          accountCloseData.ShowClosePending = False
          accountCloseData.ShowFuturePaymentsShow = False

        Case isefinAccountCloseMethod.Reinvested
          ' Reinvested - for future use.
          If AccountClose.Account.ProductType IsNot Nothing Then
            accountCloseData.CloseNotesListId = AccountClose.Account.ProductType.AccountCloseNoteReinvestmentInformationListIdResolved
          End If
          accountCloseData.ShowClosePending = False
          accountCloseData.ShowFuturePaymentsShow = False

        Case isefinAccountCloseMethod.WrittenOff
          ' Written Off
          If AccountClose.Account.ProductType IsNot Nothing Then
            accountCloseData.CloseNotesListId = AccountClose.Account.ProductType.AccountCloseNoteWriteOffInformationListIdResolved
          End If
          accountCloseData.ShowClosePending = False
          accountCloseData.ShowFuturePaymentsShow = False

        Case Else
          accountCloseData.CloseNotesListId = ""
          accountCloseData.ShowClosePending = False
          accountCloseData.ShowFuturePaymentsShow = False
      End Select

      ' Close Note default value
      If Len(accountCloseData.CloseNotesListId) &lt;&gt; 0 Then
        accountCloseData.CloseNoteDefault = finBL.InformationLists(accountCloseData.CloseNotesListId).DefaultValue
      End If

      ' Summary
      .SummaryItems = New List(Of SummaryItem)
      For Each SummaryItem In accountClose.Summary
        .SummaryItems.Add(New SummaryItem(finBL, SummaryItem, ReverseValues, AllowUpdates))
      Next

      ' Balance
      SetBalances(accountClose, accountCloseData)

      ' Transactions
      .TransactionReference = accountClose.TransactionReference
      .TransactionNotes = accountClose.TransactionNotes
      .CanPrintSummary = accountClose.SupportsPrintSummary

      Select accountClose.CloseMethod
        Case isefinAccountCloseMethod.Closed, isefinAccountCloseMethod.EarlySettlement, isefinAccountCloseMethod.EarlyRedemption
          ' Payment Due
          If Not SetPaymentDue(accountClose, .PaymentData) Then
            If finalise Then
              Success = False
            Else
            ' NOTE: Ignore errors, e.g., if this is a Deposit but we have insufficient information at this point
            End If
          End If

        Case Else
          ' Write Off
      End Select

      ' Refinance
      .RefinanceOption = accountClose.RefinanceOptionText
      
      ' Account Summary
      .AccountSummaryHtml = finBL.SummaryPageFunctions.AccountCloseSummary(False, AccountClose, "General", 0, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
      .AccountCloseSummaryHtml = finBL.SummaryPageFunctions.AccountCloseSummary(False, AccountClose, "Summary", 0, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create a finAccountClose object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateInitialAccountClose(parameters As WizardFinishParameters,
                                           ByRef accountClose As finAccountClose) As Boolean

  Dim Success As Boolean

  ' Initialise
  accountClose = finBL.CreateAccountClose()

  ' Load Account
  Success = accountClose.AccountLoad(mAccountId)

  ' Update
  If Success AndAlso parameters IsNot Nothing Then
    With accountClose
      ' General
      .CloseDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.CloseDate)
      .CloseMethodText = parameters.CloseMethodText
      .FuturePaymentsShow = parameters.FuturePaymentsShow
      .CloseNote = parameters.CloseNote

      ' Calculate
      Success = .Calculate()
    End With
  End If

  Return Success

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;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim BankInterfaceRequestMessage As String
  Dim BankInterfaceRequestSent As Boolean
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters
  Dim RefinanceAccountId As String

  ' Assume Success
  Success = True

  ' Create Account Close object
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountClose(WizardFinishParameters, AccountClose)
  Else 
    Success = False
  End If

  ' Commit
  If Success Then
    Success = AccountClose.ExecuteCommit(BankInterfaceRequestSent, BankInterfaceRequestMessage)
  End If

  ' Workflow Functionality
  If Success Then
    finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, Warning)
  End If

  ' Refinance Functionality
  If Success Then
    If AccountClose.CloseMethod = isefinAccountCloseMethod.Refinanced AndAlso AccountClose.RefinanceOption = isefinAccountCloseRefinanceOption.NewAccount Then
      RefinanceAccountId = AccountClose.RefinancedAccountId
    End If
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(AccountClose.AccountLogPk, BankInterfaceRequestMessage, BankInterfaceRequestSent, AccountClose.Account.AccountType.ClosingSummaryDocumentId, Nothing, RefinanceAccountId, Warning), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Print the Account Close Summary.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Public Function Form_ExecuteAction(parametersJson As String,
                                   ByRef returnValue As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim AccountLog As finAccountLog
  Dim Client As finClient
  Dim Document As finDocumentRO
  Dim EmailAddress As String
  Dim ExternalParty As finExternalPartyRO
  Dim Message As String
  Dim Information As String
  Dim Parameters As ISKeyValueList
  Dim Subject As String
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Create Account Close object
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountClose(WizardFinishParameters, AccountClose)
  Else 
    Success = False
  End If

  ' Validate
  If Success Then
    If Not AccountClose.CanCommitConsumerRegulationType(Message) Then
      Success = False
      finBL.Error.ErrorBegin(Message)
    End If
  End If

  ' Create Log
  If Success Then
    If AccountClose.ExecuteCreateLog(AccountLog) Then
      ' Save
      Success = AccountLog.Save()
    Else
      Success = False
    End If
  End If

  ' Email
  If Success Then
    Select Case WizardFinishParameters.Action
      Case "EMAIL_MAINCLIENT"
          ' Main Client
          Client = AccountClose.Account.Clients(0).Client
          EmailAddress = Client.ContactMethods.GetCurrentEmail().Value

      Case "EMAIL_BROKER"
          ' Broker
          ExternalParty = AccountClose.Account.BrokerExternalParty
          ExternalParty.GetClient(Client)
          If Client IsNot Nothing Then EmailAddress = Client.ContactMethods.GetCurrentEmail().Value

      Case "EMAIL_CLIENT"
          ' Other Client
          EmailAddress = WizardFinishParameters.ActionData
            
      Case "EMAIL_DEALER"
          ' Dealer
          ExternalParty = AccountClose.Account.DealerExternalParty
          ExternalParty.GetClient(Client)
          If Client IsNot Nothing Then EmailAddress = Client.ContactMethods.GetCurrentEmail().Value

      Case Else
        If WizardFinishParameters.Action.StartsWith("EMAIL_") Then
          Warning = String.Format("Unsupported Email action '{0}'.", WizardFinishParameters.Action)
        End If
    End Select
  End If

  ' Create PDF Document
  ' NOTE: Only necessary if emailing since the document printing is done client-side via an Application Shortcut
  If Success AndAlso Len(EmailAddress) &lt;&gt; 0 Then
    ' Get Document
    Document = finBL.Documents(AccountClose.Account.AccountType.ClosingSummaryDocumentId)

    ' Generate Subject and Message
    Subject = finBL.DocumentFunctions.ResolveTaggedMessageFromObjects(Document.TemplateSubject, finBL.TimeZoneFunctions.GetCurrentDatabaseDate(), AccountClose.Account, Client, ExternalParty, finBL.Users(finBL.CurrentUserInformation.UserId))
    Message = finBL.DocumentFunctions.ResolveTaggedMessageFromObjects(Document.TemplateMessage, finBL.TimeZoneFunctions.GetCurrentDatabaseDate(), AccountClose.Account, Client, ExternalParty, finBL.Users(finBL.CurrentUserInformation.UserId))
    If Len(Subject) = 0 Then Subject = "Account Close Quotation"
    If Len(Message) = 0 Then Message = "Your Account Close Quotation is attached."

    ' Create Parameters
    Parameters = finBL.CreateKeyValueList()
    With Parameters
      .SetInteger("logPk", AccountLog.Pk)
    End With

    ' Email Subject and Body

    ' Execute and Email Document
    ' NOTE: HTML format, includes Signature and Entity-based Signature
    If finBL.DocumentFunctions.SendEmailFromDocumentExecute(Document.DocumentId, parameters, Subject, Message, EmailAddress,,,,,True, True, AccountClose.Account.EntityPk) Then
      ' Override Information
      Information = String.Format("An Account Close Quotation document has been emailed to {0}.", EmailAddress)
    Else
      Warning = finBL.Error.Message(True, True)
    End If
  End If

  ' Clear Log Message
  ' NOTE: This ensures that no notification is given if just generating a Document since it will have been downloaded in the User's browser
  If WizardFinishParameters.Action = "DOCUMENT" Then Information = ""

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(AccountLog.Pk, "", False, AccountClose.Account.AccountType.ClosingSummaryDocumentId, Information, "", Warning), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get updated Payment Information when the Payment Method changes.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Public Function Form_PaymentMethod_Change(parametersJson As String,
                                          ByRef response As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim obj As Object
  Dim PaymentData As PaymentData
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

 ' Assume Success
  Success = True

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

  ' Create Account Close object
  If Success Then
    Success = CreateAccountClose(WizardFinishParameters, AccountClose)
  End If

  ' Create Payment Data object
  If Success Then
    ' Payment Due
    Success = SetPaymentDue(accountClose, PaymentData)
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get updated Transaction Type information when the Transaction Type changes.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Public Function Form_TransactionType_Change(parametersJson As String,
                                            ByRef response As String) As Boolean

  Dim obj As Object
  Dim Success As Boolean
  Dim TransactionType As finTransactionTypeRO
  Dim TransactionTypeId As String

 ' Assume Success
  Success = True

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

  ' Get Transaction Type
  If finBL.TransactionTypes.Exists(TransactionTypeId) Then
    TransactionType = finBL.TransactionTypes(TransactionTypeId)
  Else
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Transaction Type '{0}'.", TransactionTypeId)
  End If

  ' Create response object
  If Success Then
    obj = New With {
      .TransactionReference = TransactionType.TransactionReferenceResolved,
      .TransactionNotes = TransactionType.TransactionNotes,
      .PrintSummaryDefault = TransactionType.PrintReceipt
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get updated Account Close object.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Public Function GetAccountClose(parametersJson As String,
                                ByRef response As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim AccountCloseData As AccountCloseData
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

 ' Assume Success
  Success = True

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

  ' Create Account Close object
  If Success Then
    Success = CreateAccountClose(WizardFinishParameters, AccountClose)
  End If

  ' Create Account Close Data object
  If Success Then
    Success = CreateAccountCloseData(AccountClose, AccountCloseData, False)
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account Schedule for the button next to the Current Balance.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Public Function GetAccountSchedule(parametersJson As String,
                                   ByRef response As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Account Payment
  If Success Then
    Success = CreateAccountClose(WizardFinishParameters, AccountClose)
  End If

  ' Get Schedule
  If Success Then
    response = AccountClose.Account.Calculation.Schedule.ToHtmlWidgetJsonString()
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get the confirm list before submitting the Account Close.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function GetFinishConfirmList(accountClose As finAccountClose,
                                      ByRef confirmList As List(Of String),
                                      ByRef failedMessage As String) As Boolean

  Dim Account As finAccount
  Dim strTemp As String

  With AccountClose
    Select Case .CloseMethod
      Case isefinAccountCloseMethod.BadDebtWriteOff
        confirmList.Add(String.Format("Are you sure you want to WRITE OFF Account {0}, '{1}' as a bad debt?", .Account.AccountId, .Account.Name))

      Case isefinAccountCloseMethod.Cancelled
        confirmList.Add(String.Format("Are you sure you want to CANCEL and WRITE OFF Account {0}, '{1}'?", .Account.AccountId, .Account.Name))

      Case isefinAccountCloseMethod.EarlySettlement, isefinAccountCloseMethod.EarlyRedemption
        confirmList.Add(String.Format("Are you sure you want to settle Account {0}, '{1}' early?", .Account.AccountId, .Account.Name))

      Case isefinAccountCloseMethod.Reinvested
        If accountClose.RefinanceOption = isefinAccountCloseRefinanceOption.ExistingAccount Then
          ' Load 'to' Account for Name (Ignore return value as this is only for display purposes)
          Account = finBL.CreateAccount()
          Account.Load(.RefinanceIntoAccountId)

          strTemp = String.Format("Are you sure you want to Reinvest Account {0}, '{1}' into existing Account {2}, '{3}'?", .Account.AccountId, .Account.Name, .RefinanceIntoAccountId, Account.Name)
          strTemp &amp;= vbNewLine &amp; vbNewLine
          strTemp &amp;= String.Format("WARNING: Account '{0}' will be closed immediately and the balance (plus any fees) transferred to Account '{1}'.", .Account.AccountId, .RefinanceIntoAccountId)
        Else
          strTemp = String.Format("Are you sure you want to Reinvest Account {0}, '{1}'?", .Account.AccountId, .Account.Name)
        End If
        confirmList.Add(strTemp)

      Case isefinAccountCloseMethod.WrittenOff
        confirmList.Add(String.Format("Are you sure you want to WRITE OFF Account {0}, '{1}'?", .Account.AccountId, .Account.Name))

      Case isefinAccountCloseMethod.Refinanced
        If accountClose.RefinanceOption = isefinAccountCloseRefinanceOption.ExistingAccount Then
          ' Load 'to' Account for Name (Ignore return value as this is only for display purposes)
          Account = finBL.CreateAccount()
          Account.Load(.RefinanceIntoAccountId)

          strTemp = String.Format("Are you sure you want to Refinance Account {0}, '{1}' into existing Account {2}, '{3}'?", .Account.AccountId, .Account.Name, .RefinanceIntoAccountId, Account.Name)
          strTemp &amp;= vbNewLine &amp; vbNewLine
          strTemp &amp;= String.Format("WARNING: Account '{0}' will be closed immediately and the balance (plus any fees) transferred to Account '{1}'.", .Account.AccountId, .RefinanceIntoAccountId)
        Else
          strTemp = String.Format("Are you sure you want to Refinance Account {0}, '{1}'?", .Account.AccountId, .Account.Name)
        End If
        confirmList.Add(strTemp)
        
      Case Else
        confirmList.Add(String.Format("Are you sure you want to close Account {0}, '{1}'?", .Account.AccountId, .Account.Name))
    End Select

    ' Close Pending
    If .ClosePending Then
      Select Case accountClose.CloseMethod
        Case isefinAccountCloseMethod.Refinanced
          confirmList.Add("The closing of this Account will be held as pending until the new Account is opened.")
        Case Else 
          confirmList.Add(String.Format("Close will be held as pending with a review date of {0}.", finBL.FormatDateLong(.ClosePendingReviewDate)))
      End Select      
    End If

    ' Balance Due
    If AccountClose.BalanceDue = 0 Then
      confirmList.Add("There is no Balance Due.")
    End If
  End With

  Return True

End Function

''' &lt;summary&gt;
'''  Get updated Initialised Account Close object.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Public Function GetInitialAccountClose(parametersJson As String,
                                       ByRef response As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim AccountCloseData As AccountCloseData
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

 ' Assume Success
  Success = True

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

  ' Create Account Close object
  If Success Then
    Success = CreateInitialAccountClose(WizardFinishParameters, AccountClose)
  End If

  ' Create Account Close Data object
  If Success Then
    Success = CreateAccountCloseData(AccountClose, AccountCloseData, False)
  End If

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

  Return Success

End Function

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

  Dim AccountClient As finAccountClient
  Dim AccountClose As finAccountClose
  Dim AccountCloseMethod As ISCodeDescriptionListItem
  Dim AccountCloseMethodList As ISCodeDescriptionList
  Dim AccountTypeRO As finAccountTypeRO
  Dim cdl As ISCodeDescriptionList
  Dim Client As finClient
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim List As New ISList
  Dim strTemp As String
  Dim Success As Boolean
  Dim swb As ISSqlWhereBuilder

  ' Assume Success
  Success = True

  ' Validate
  If Len(mAccountId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Id not specified.")
  ElseIf finBL.CurrentUserInformation.IsAccountFilteredOut(mAccountId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this record.")
  End If

  ' Create Account Close object
  If Success Then
    Success = CreateAccountClose(Nothing, AccountClose)
  End If

  ' Further Validations
  If Success Then
    Select Case mCloseMethod
      Case isefinAccountCloseMethod.Refinanced
        ' Refinanced
        If Not AccountClose.Account.CanRefinance(strTemp) Then
          Success = False
          finBL.Error.ErrorBegin(strTemp)
        End If
    End Select
  End If
  
  ' Get Close Method list
  If Success Then
    AccountCloseMethodList = AccountClose.GetCloseMethodsAvailableTypesCodeDescriptionList(True, True)
    
    ' Validate
    If Not AccountCloseMethodList.Exists(mCloseMethod.ToString()) Then
      Success = False
      finBL.Error.ErrorBeginFormat("Close Method '{0}' is invalid for Account Class '{1}'.", finBL.Enums.isefinAccountCloseMethod_ToString(mCloseMethod), AccountClose.Account.AccountClassText)
    End If
  End If
  
  ' Get Refinance To SQL Where
  If Success Then
    Success = finBL.AccountFunctions.GetRefinanceToAccountsSqlWhere(AccountClose.Account, swb)
  End If
  
  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Read Only
      .ReadOnly = mReadOnly OrElse finBL.Database.IsReadOnly
      .AllowUpdates = AccountClose.AllowUpdateUI()

      ' Record
      .RecordId = AccountClose.Account.AccountId
      .RecordDescription = AccountClose.Account.Name
      .AccountClassIsDeposit = (AccountClose.Account.AccountClass = isefinAccountClass.Deposit)
      .AccountTypeId = AccountClose.Account.AccountTypeId
      .ProductTypeId = AccountClose.Account.ProductTypeId

      ' General
      .ClosedPendingReviewDays = AccountClose.Account.AccountType.ClosedPendingReviewDays
      Success = CreateAccountCloseData(AccountClose, .AccountClose, False)
      
      ' Balance
      .OtherInterestDescription = AccountClose.Account.AccountType.OtherInterestDescriptionResolved

      ' Original
      .AccruedInterestOriginal = AccountClose.AccruedInterestOriginal
      .AccruedDefaultInterestOriginal = AccountClose.AccruedDefaultInterestOriginal
      .UnpostedDefaultFeesOriginal = AccountClose.UnpostedDefaultFeesOriginal
      .UnpostedFacilityFeesOriginal = AccountClose.UnpostedFacilityFeesOriginal
      .UnpostedOverLimitFeesOriginal = AccountClose.UnpostedOverLimitFeesOriginal
      .FeeValueOriginal = AccountClose.FeeValueOriginal

      ' Permissions
      If .ReadOnly Then
        .CanAddLog = False
        .CanCreateDocument = False
        .CanSendEmail = False

        .DocumentWarning = "Database is Read-Only."
      Else
        ' Default Permissions
        .CanAddLog = True
        .CanCreateDocument = True
        .CanSendEmail = True

        ' Can Document be generated?
        If AccountClose.Account.AccountType.ClosingSummaryDocumentPk = 0 Then
          .CanCreateDocument = False
          .DocumentWarning = "Document not defined."
        Else
          ' Document Warning
          With finBL.Documents(AccountClose.Account.AccountType.ClosingSummaryDocumentId)
            If Not .Active Then
              FormInitialisationInfo.CanCreateDocument = False
              FormInitialisationInfo.DocumentWarning = "Document is not active."
            ElseIf Not .HasPermissionToExecute() Then
              FormInitialisationInfo.CanCreateDocument = False
              FormInitialisationInfo.DocumentWarning = "You do not have permission to execute this Document."
            Else
              Select Case .FileType
                Case iseDocumentFileType.WordDocument
                Case Else
                  FormInitialisationInfo.CanCreateDocument = False
                  FormInitialisationInfo.DocumentWarning = "Document File Type is not supported for printing through this interface."
              End Select
            End If
          End With
        End If

        ' Can Email be Sent?
        .CanSendEmail = finBL.CurrentUserInformation.CanSendAccountEmailUnattended AndAlso .CanCreateDocument
        If .CanSendEmail Then
          ' Main Client
          If mCombinedParameters.GetBoolean("EmailAllowMainClient") AndAlso AccountClose.Account.Clients.Count &lt;&gt; 0 Then
            .EmailMainClient = AccountClose.Account.Clients(0).Client.ContactMethods.GetCurrentEmail().Value
          End If

          ' Broker
          If mCombinedParameters.GetBoolean("EmailAllowBroker") AndAlso finBL.Settings.AddOns.ExternalPartyBrokers AndAlso AccountClose.Account.BrokerExternalParty IsNot Nothing Then
            AccountClose.Account.BrokerExternalParty.GetClient(Client)
            If Client IsNot Nothing Then .EmailBroker = Client.ContactMethods.GetCurrentEmail().Value
          End If

          ' Dealer
          If mCombinedParameters.GetBoolean("EmailAllowDealer") AndAlso finBL.Settings.AddOns.ExternalPartyDealers AndAlso AccountClose.Account.DealerExternalParty IsNot Nothing Then
            AccountClose.Account.DealerExternalParty.GetClient(Client)
            If Client IsNot Nothing Then .EmailDealer = Client.ContactMethods.GetCurrentEmail().Value
          End If
          
          ' Other Clients
          If mCombinedParameters.GetBoolean("EmailAllowOtherClients") Then
            cdl = finBL.CreateCodeDescriptionList()
            
            For Each AccountClient In AccountClose.Account.Clients
              If AccountClose.Account.Clients.IndexOf(AccountClient) &lt;&gt; 0 Then
                strTemp = AccountClient.Client.contactmethods.GetCurrentEmail().Value
                If Len(strTemp) &lt;&gt; 0 Then
                  cdl.Add(strTemp, String.Format("{0} ({1})", AccountClient.ClientName, AccountClient.AccountRoleDescriptionShortResolved))
                End If
              End If
            Next
            
            If cdl.Count &lt;&gt; 0 Then
              .EmailClientsOther = cdl.ToJsonObject()
            End If
          End If
        End If
      End If

      ' Lists
      For Each AccountTypeRO In finBL.AccountTypes
        If AccountTypeRO.Active Then
          Select Case AccountClose.Account.AccountClass
            Case isefinAccountClass.Deposit
              ' Deposit Accounts
              If AccountTypeRO.AccountClass = isefinAccountClass.Deposit Then
                .AccountTypes.Add(New AccountTypeData(AccountTypeRO, AccountClose.Account))
              End If

            Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
              ' Other
              Select Case AccountTypeRO.AccountClass
                Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
                  .AccountTypes.Add(New AccountTypeData(AccountTypeRO, AccountClose.Account))
              End Select
          End Select
        End If
      Next      
      .RefinanceOptionList = finBL.Enums.isefinAccountCloseRefinanceOption_ToCodeDescriptionList().ToJsonObject()
      .RefinanceToSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(swb.SqlWhere)

      ' Close Method Data
      For Each AccountCloseMethod In AccountCloseMethodList
        .CloseMethodsData.Add(New CloseMethodData(finBL.Enums.isefinAccountCloseMethod_FromString(AccountCloseMethod.Description), AccountClose.Account))
      Next 
      
      ' Other
      .IsRefinance = (mCloseMethod = isefinAccountCloseMethod.Refinanced)
      .LockCloseMethod = (Len(mCloseMethodText) &lt;&gt; 0)
      
      ' Permissions
      .CanClose = finBL.CurrentUser.Permissions.Allow("Account." &amp; AccountClose.Account.GetAccountClassSimple(False) &amp; ".Status.OpenToClosed")
      .CanClosePending = finBL.CurrentUser.Permissions.Allow("Account." &amp; AccountClose.Account.GetAccountClassSimple(False) &amp; ".Status.OpenToClosedPending")
      
      ' Configuration
      ' NOTE: Not used by this Widget
      .AddonSecurityRegister = finBL.Settings.AddOns.SecurityRegister
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      .SecurityFullDetails = (finBL.CountryCode = "NZ")
      
      ' Payment Details
      .ShowCashRegister = (finBL.Settings.AddOns.BankingAdvanced AndAlso finBL.CashRegisters.Count &lt;&gt; 0)
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Refinance Summary.
''' &lt;/summary&gt;
Private Function GetRefinanceSummary(parametersJson As String, 
                                     ByRef returnValue As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True
  
  ' Create Account Close object
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountClose(WizardFinishParameters, AccountClose)
  Else 
    Success = False
  End If
  
  ' Get Summary
  If Success Then        
    returnValue = finBL.SummaryPageFunctions.AccountCloseSummary(False, AccountClose, "Refinance", 0, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY, "Refinance"))
  End If
  
  Return Success
                                     
End Function

''' &lt;summary&gt;
'''  Get Security Summary.
''' &lt;/summary&gt;
Private Function GetSecuritySummary(parametersJson As String,
                                    ByRef returnValue As String) As Boolean
  
  Dim AccountClose As finAccountClose
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim SecurityStmtA As finSecurityStmt
  Dim SecurityStmtB As finSecurityStmt
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True
  
  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()
  
  ' Get Parameters
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountClose(WizardFinishParameters, AccountClose)
  Else 
    Success = False
  End If
  
  ' Get Security Statement(s)
  If Success Then
    Success = LoadSecurityStatements(AccountClose.RefinanceIntoAccountId, SecurityStmtA, SecurityStmtB)
  End If
  
  ' Get Security Statements
  If Success Then
    With AccountClose
      returnValue = finBL.SummaryPageFunctions.AccountCloseSecuritySummary(AccountClose, .RefinanceIntoAccountId, .RefinanceOption, SecurityStmtA, SecurityStmtB, .RefinanceIntoCopySecurityStmtItems)
    End With    
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Load Security Statements.
''' &lt;/summary&gt;
Private Function LoadSecurityStatements(refinanceToAccountId As String,
                                        ByRef securityStmtA As finSecurityStmt,
                                        ByRef securityStmtB As finSecurityStmt) As Boolean
  
  Dim Account As finAccount
  Dim RefinanceToAccount As finAccount
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise ByRef Parameters
  securityStmtA = Nothing
  securityStmtB = Nothing
  
  ' Initialise
  Account = finBL.CreateAccount()  
  
  ' Security Statement A
  If Account.Load(mAccountId) Then    
    If Not Account.SecurityStmt.IsNew Then
      securityStmtA = Account.SecurityStmt
    End If
  Else 
    Success = False
  End If
  
  ' Security Statement B
  If Success AndAlso Len(refinanceToAccountId) &lt;&gt; 0 Then
    RefinanceToAccount = finBL.CreateAccount()
    If RefinanceToAccount.Load(refinanceToAccountId) Then
      If Not RefinanceToAccount.SecurityStmt.IsNew Then
        securityStmtB = RefinanceToAccount.SecurityStmt
      End If
    Else 
      Success = False
    End If
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get Security Statement Information for Refinancing to an existing Account.
''' &lt;/summary&gt;
Private Function GetSecurityStmtInformation(ByRef returnValue As String) As Boolean
  
  Dim Data As Object
  Dim SameSecurityStmt As Boolean
  Dim SecurityStmtA As finSecurityStmt
  Dim SecurityStmtADescription As String
  Dim SecurityStmtAId As String
  Dim SecurityStmtAIsNew As Boolean
  Dim SecurityStmtAIsRegistered As Boolean
  Dim SecurityStmtARegisterStatusText As String
  Dim SecurityStmtB As finSecurityStmt
  Dim SecurityStmtBDescription As String
  Dim SecurityStmtBId As String
  Dim SecurityStmtBIsRegistered As Boolean
  Dim SecurityStmtBRegisterStatusText As String
  Dim SecurityStmtList As ISList
  Dim ShowSecurityStmtPage As Boolean
  Dim Success As Boolean
  Dim RefinanceToAccountId As String
  
  ' Assume Success
  Success = True
  
  ' Initialise
  SecurityStmtList = finBL.Runtime.CreateList()
  
  ' Parameters
  With mCombinedParameters
    RefinanceToAccountId = .GetString("RefinanceToAccountId")  
  End With  

  ' Get Security Statements
  If LoadSecurityStatements(RefinanceToAccountId, SecurityStmtA, SecurityStmtB) Then
    ' Security Statement A
    If SecurityStmtA IsNot Nothing Then      
      SecurityStmtList.Add(SecurityStmtA.SecurityStmtId)
      
      SecurityStmtAId = SecurityStmtA.SecurityStmtId
      SecurityStmtADescription = SecurityStmtA.Description
      SecurityStmtARegisterStatusText = SecurityStmtA.RegisterStatusText
      SecurityStmtAIsRegistered = (SecurityStmtA.RegisterStatus = iseSecurityStmtRegisterStatus.Registered)      
    End If
    
    ' Security Statement B
    If SecurityStmtB IsNot Nothing Then
      SecurityStmtList.Add(SecurityStmtB.SecurityStmtId)
      
      SecurityStmtBId = SecurityStmtB.SecurityStmtId
      SecurityStmtBDescription = SecurityStmtB.Description
      SecurityStmtBRegisterStatusText = SecurityStmtB.RegisterStatusText
      SecurityStmtBIsRegistered = (SecurityStmtB.RegisterStatus = iseSecurityStmtRegisterStatus.Registered)
    End If
  Else
    Success = False
  End If
  
  ' Perform Checks
  If Success Then    
    ' Two Statements are available
    If SecurityStmtA IsNot Nothing AndAlso SecurityStmtB IsNot Nothing Then
      ' Security Statements are the same
      SameSecurityStmt = (SecurityStmtA.Pk = SecurityStmtB.Pk)
      
      ' Statement A is 'New'
      If SecurityStmtA.RegisterStatus = iseSecurityStmtRegisterStatus.New Then
        If SecurityStmtB.RegisterStatus &lt;&gt; iseSecurityStmtRegisterStatus.Cancelled AndAlso SecurityStmtB.RegisterStatus &lt;&gt; iseSecurityStmtRegisterStatus.Discharged AndAlso SecurityStmtB.RegisterStatus &lt;&gt; iseSecurityStmtRegisterStatus.Expired AndAlso SecurityStmtB.RegisterStatus &lt;&gt; iseSecurityStmtRegisterStatus.Historic Then
          SecurityStmtAIsNew = True
        End If
      End If
    End If
    
    ' Show Security Statement page?
    If SameSecurityStmt Then
      ShowSecurityStmtPage = False
    Else
      ShowSecurityStmtPage = (SecurityStmtA IsNot Nothing OrElse SecurityStmtB IsNot Nothing)
    End If
  End If
  
  ' Build Object
  If Success Then
    Data = New With {
      .HasSecurityStmtA = (SecurityStmtA IsNot Nothing),
      .HasSecurityStmtB = (SecurityStmtB IsNot Nothing),
      .SameSecurityStmt = SameSecurityStmt,
      .SecurityStmtAId = SecurityStmtAId,
      .SecurityStmtADescription = SecurityStmtADescription,
      .SecurityStmtARegisterStatusText = SecurityStmtARegisterStatusText,
      .SecurityStmtAIsNew = SecurityStmtAIsNew,
      .SecurityStmtAIsRegistered = SecurityStmtAIsRegistered,      
      .SecurityStmtBId = SecurityStmtBId,
      .SecurityStmtBDescription = SecurityStmtBDescription,
      .SecurityStmtBRegisterStatusText = SecurityStmtBRegisterStatusText,
      .SecurityStmtBIsRegistered = SecurityStmtBIsRegistered,
      .ShowSecurityStmtPage = ShowSecurityStmtPage,
      .SecurityStmtList = SecurityStmtList.ToCsvString()
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get Summary Item preview.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Public Function GetSummaryItemPreview(parametersJson As String,
                                      ByRef response As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

 ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    RowIndex = .GetInteger("RowIndex")
  End With

  ' Create Account Close object
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountClose(WizardFinishParameters, AccountClose)
  Else 
    Success = False
  End If

  ' Valid Row Index
  If RowIndex &lt; 0 Then RowIndex = 0

  ' Get Summary
  If Success Then
    response = finBL.SummaryPageFunctions.AccountCloseSummary(False, AccountClose, "Summary", RowIndex, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef wizardFinishParameters As WizardFinishParameters) As Boolean
  
  Dim obj As Object                                           
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
            
  ' Initialise ByRef Parameters
  wizardFinishParameters = Nothing
  
  ' Get Wizard Finish Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(WizardFinishParameters), obj) Then
    wizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Set the balance properties of AccountCloseData.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function SetBalances(accountClose As finAccountClose,
                             accountCloseData As AccountCloseData) As Boolean

  Dim AllowUpdates As Boolean
  Dim PermissionKey As String
  Dim ReverseValues As Decimal
  Dim strTemp As String
  Dim Success As Boolean

  ' Initialise
  AllowUpdates = accountClose.AllowUpdateUI()

  ' Assume Success
  Success = True

  ' Reverse Values?
  Select Case accountClose.Account.AccountClass
    Case isefinAccountClass.Deposit
      ReverseValues = -1

    Case Else
      ReverseValues = 1
  End Select

  With accountCloseData
    ' Update Totals
    .BalanceCurrent = accountClose.BalanceCurrent * ReverseValues
    .TotalCredits = -accountClose.Summary.TotalCredits * ReverseValues
    .BalanceNet = accountClose.BalanceNet * ReverseValues
    .LossValue = accountClose.LossValue
    .AdjustmentValue = accountClose.AdjustmentValue
    .BalanceDue = accountClose.BalanceDue * ReverseValues

    ' Accrued Interest
    .AccruedInterest = accountClose.AccruedInterest * ReverseValues
    .AccruedInterestCharge = accountClose.AccruedInterestCharge
    Select Case accountClose.Account.AccountClass
      Case isefinAccountClass.Deposit
        PermissionKey = "Account.Deposit.Close.AccruedInterestAllowChange"
      Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
        PermissionKey = "Account.Loan.Close.AccruedInterestAllowChange"
    End Select
    If Len(PermissionKey) = 0 OrElse finBL.CurrentUser.Permissions.Allow(PermissionKey) Then
      .AccruedInterestReadOnly = Not (accountClose.AccruedInterestAllowChange AndAlso AllowUpdates)
    Else
      .AccruedInterestReadOnly = True
    End If
    If AccountClose.AccruedInterestSuspended Then
      .AccruedInterestChargeCaption = "Charge (currently suspended)?"
    Else
      .AccruedInterestChargeCaption = "Charge?"
    End If

    ' Withholding Tax
    .SupportsWithholdingTax = accountClose.Account.SupportsWithholdingTax
    If accountClose.Account.SupportsWithholdingTax Then
      .WithholdingTaxRate = accountClose.WithholdingTaxRate
      .WithholdingTaxValue = -accountClose.WithholdingTaxValueResolved * ReverseValues

      Select Case accountClose.WithholdingTaxResidentStatus
        Case isefinAccountTransactionResidentStatus.NotApplicable
          .WithholdingTaxLabel = ""

        Case Else
          .WithholdingTaxLabel = String.Format("{0} @ {1}", accountClose.WithholdingTaxResidentStatusShortText, finBL.FormatPercentage(accountClose.WithholdingTaxRate / 100, 4))
      End Select
    Else
      .WithholdingTaxValue = 0
      .WithholdingTaxLabel = ""
    End If

    ' Accrued Default Interest
    .AccruedDefaultInterestCharge = accountClose.AccruedDefaultInterestCharge
    .AccruedDefaultInterest = accountClose.AccruedDefaultInterest * ReverseValues
    .AccruedDefaultInterestReadOnly = Not allowUpdates
    If AccountClose.AccruedDefaultInterestSuspended Then
      .AccruedDefaultInterestChargeCaption = "Charge (currently suspended)?"
    Else
      .AccruedDefaultInterestChargeCaption = "Charge?"
    End If

    ' Accrued Other Interest
    .AccruedOtherInterest = accountClose.AccruedOtherInterest * ReverseValues
    .AccruedOtherInterestCharge = accountClose.AccruedOtherInterestCharge
    .AccruedOtherInterestReadOnly = Not allowUpdates

    ' Unposted Default Fees
    .UnpostedDefaultFees = accountClose.UnpostedDefaultFees * ReverseValues
    .UnpostedDefaultFeesCharge = accountClose.UnpostedDefaultFeesCharge
    .UnpostedDefaultFeesReadOnly = Not allowUpdates
    If AccountClose.UnpostedDefaultFeesSuspended Then
      .UnpostedDefaultFeesChargeCaption = "Charge (currently suspended)?"
    Else
      .UnpostedDefaultFeesChargeCaption = "Charge?"
    End If

    ' Unposted Over Limit Fees
    .UnpostedOverLimitFeesCharge = accountClose.UnpostedOverLimitFeesCharge
    .UnpostedOverLimitFeesReadOnly = Not allowUpdates
    If allowUpdates Then
      .UnpostedOverLimitFees = accountClose.UnpostedOverLimitFees * ReverseValues
    Else
      .UnpostedOverLimitFees = accountClose.UnpostedOverLimitFeesResolved * ReverseValues
    End If
    If AccountClose.UnpostedOverLimitFeesSuspended Then
      .UnpostedOverLimitFeesChargeCaption = "Charge (currently suspended)?"
    Else
      .UnpostedOverLimitFeesChargeCaption = "Charge?"
    End If

    ' Unposted Facility Fees
    .UnpostedFacilityFeesCharge = accountClose.UnpostedFacilityFeesCharge
    .UnpostedFacilityFeesReadOnly = Not allowUpdates
    If allowUpdates Then
      .UnpostedFacilityFees = accountClose.UnpostedFacilityFees * ReverseValues
    Else
      .UnpostedFacilityFees = accountClose.UnpostedFacilityFeesResolved * ReverseValues
    End If
    If AccountClose.UnpostedFacilityFeesSuspended Then
      .UnpostedFacilityFeesChargeCaption = "Charge (currently suspended)?"
    Else
      .UnpostedFacilityFeesChargeCaption = "Charge?"
    End If

    ' Unposted Standard Transactions
    .ShowUnpostedStandardTransactionsCharge = allowUpdates AndAlso accountClose.UnpostedStandardTransactions &lt;&gt; 0
    .UnpostedStandardTransactionsCharge = accountClose.UnpostedStandardTransactionsCharge
    .UnpostedStandardTransactions = accountClose.UnpostedStandardTransactionsResolved * ReverseValues
    If AccountClose.UnpostedStandardTransactionsSuspended Then
      .UnpostedStandardTransactionsChargeCaption = "Charge (currently suspended)?"
    Else
      .UnpostedStandardTransactionsChargeCaption = "Charge?"
    End If

    ' Loss
    .LossValueReadOnly = Not AccountClose.LossAllowChange
    .LossMessage = AccountClose.LossMessageInformation
    .LossError = AccountClose.LossMessageError
    .ShowLossValue = AccountClose.LossElementPk &lt;&gt; 0

    ' Adjustment &amp; Balance Due
    .ShowAdjustmentValue = AccountClose.AdjustmentElementPk &lt;&gt; 0
    .AdjustmentValueReadOnly = Not allowUpdates
    .AdjustmentValue = AccountClose.AdjustmentValue
    If AccountClose.AdjustmentElementPk = 0 Then
    	.BalanceDueReadOnly = True
    Else
    	.BalanceDueReadOnly = Not allowUpdates
    End If

    ' Residual Value
    .ResidualCreditResidual = accountClose.ResidualValueCredit
    .ResidualValue = accountClose.ResidualValue
    .ShowResidualValue = AccountClose.IsResidualValueApplicable
    If AccountClose.IsResidualValueApplicable Then
    	.ShowResidualCreditResidual = AccountClose.ResidualElementPk &lt;&gt; 0
    	.ResidualValueReadOnly = Not AccountClose.ResidualAllowChange
    Else
    	.ShowResidualCreditResidual = False
    End If

    ' Fee
    .FeeChargeFee = accountClose.FeeChargeFee
    .ShowFeeValue = accountClose.FeeAvailable
    .FeeValueReadOnly = Not (accountClose.FeeAllowChange AndAlso allowUpdates)
    If allowUpdates Then
      .FeeValue = accountClose.FeeValue
    Else
      .FeeValue = accountClose.FeeValueResolved
    End If

    ' Other 1
    .Other1Caption = accountClose.Other1Description &amp; ":"
    .Other1Charge = accountClose.Other1Charge
    .Other1ValueReadOnly = Not (accountClose.Other1AllowChange AndAlso allowUpdates)
    .ShowOther1Value = accountClose.Other1Available
    If allowUpdates Then
      .Other1Value = accountClose.Other1Value
    Else
      .Other1Value = accountClose.Other1ValueResolved
    End If

    ' Other 2
    .Other2Caption = accountClose.Other2Description &amp; ":"
    .Other2Charge = accountClose.Other2Charge
    .Other2ValueReadOnly = Not (accountClose.Other2AllowChange AndAlso allowUpdates)
    .ShowOther2Value = accountClose.Other2Available
    If allowUpdates Then
      .Other2Value = accountClose.Other2Value
    Else
      .Other2Value = accountClose.Other2ValueResolved
    End If

    ' Visible
    Select Case AccountClose.Account.AccountClass
      Case isefinAccountClass.Deposit
        .ShowAccruedInterest = True
        .ShowWithholdingTaxValue = True
        .ShowAccruedDefaultInterest = False
        If AccountClose.AccruedOtherInterestAvailable OrElse AccountClose.AccruedOtherInterestOriginal &lt;&gt; 0 Then
          .ShowAccruedOtherInterest = True
        Else
          .ShowAccruedOtherInterest = False
        End If
        .ShowUnpostedDefaultFees = False
        .ShowUnpostedOverLimitFees = False
        .ShowUnpostedFacilityFees = False

      Case isefinAccountClass.Disbursement
        .ShowAccruedInterest = False
        .ShowWithholdingTaxValue = False
        .ShowAccruedDefaultInterest = False
        .ShowAccruedOtherInterest = False
        .ShowUnpostedDefaultFees = False
        .ShowUnpostedOverLimitFees = False
        .ShowUnpostedFacilityFees = False

      Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
        .ShowAccruedInterest = True
        .ShowWithholdingTaxValue = False
        .ShowAccruedDefaultInterest = True
        If AccountClose.AccruedOtherInterestAvailable OrElse AccountClose.AccruedOtherInterestOriginal &lt;&gt; 0 Then
          .ShowAccruedOtherInterest = True
        Else
          .ShowAccruedOtherInterest = False
        End If

        If AccountClose.UnpostedDefaultFeesAvailable OrElse AccountClose.UnpostedDefaultFeesOriginal &lt;&gt; 0 Then
          .ShowUnpostedDefaultFees = True
        Else
          .ShowUnpostedDefaultFees = False
        End If

        If AccountClose.UnpostedOverLimitFeesAvailable OrElse AccountClose.UnpostedOverLimitFeesOriginal &lt;&gt; 0 Then
          .ShowUnpostedOverLimitFees = True
        Else
          .ShowUnpostedOverLimitFees = False
        End If

        If AccountClose.UnpostedFacilityFeesAvailable OrElse AccountClose.UnpostedFacilityFeesOriginal &lt;&gt; 0 Then
          .ShowUnpostedFacilityFees = True
        Else
          .ShowUnpostedFacilityFees = False
        End If

      Case Else
        finBL.Error.ErrorBeginFormat("Unhandled account class '{0}'.", AccountClose.Account.AccountClassText)
        Success = False
    End Select

    ' Fees Heading
    strTemp = ""
    If .ShowLossValue Then strTemp &amp;= "Loss"
    If .ShowFeeValue Then
      If Len(strTemp) &lt;&gt; 0 Then
        If .ShowAdjustmentValue Then strTemp &amp;= ", " Else strTemp &amp;= " and "
      End If
      strTemp &amp;= "Fees"
    End If
    If .ShowAdjustmentValue Then
      If Len(strTemp) &lt;&gt; 0 Then strTemp &amp;= " and "
      strTemp &amp;= "Adjustments"
    End If
    If Len(strTemp) = 0 Then
      If .ShowOther1Value OrElse .ShowOther2Value Then
        strTemp = "Other Adjustments"
      End If
    End If
    If Len(strTemp) = 0 Then
      .ShowFeesHeading = False
    Else
      Select Case AccountClose.Account.AccountClass
        Case isefinAccountClass.Deposit
          .FeesHeadingCaption = "Less " &amp; strTemp &amp; "."
        Case Else
          .FeesHeadingCaption= "Plus " &amp; strTemp &amp; "."
      End Select
      .ShowFeesHeading = True
    End If
  End With

  Return True

End Function

''' &lt;summary&gt;
'''  Set the Payment properties based on Account Close details.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function SetPaymentDue(accountClose As finAccountClose,
                               ByRef paymentData As PaymentData) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  paymentData = New PaymentData()

  With paymentData
    Select accountClose.CloseMethod
      Case isefinAccountCloseMethod.Closed, isefinAccountCloseMethod.EarlySettlement, isefinAccountCloseMethod.EarlyRedemption
        If Len(accountClose.BankingDetails.PaymentMethodId) &lt;&gt; 0 AndAlso finBL.PaymentMethods.Exists(accountClose.BankingDetails.PaymentMethodId) Then
          ' Calculate Fee
          If accountClose.PaymentFeeCalculate(True) Then
            .PaymentFeeCharge = accountClose.PaymentFeeCharge
            .PaymentFeeReadOnly = Not accountClose.PaymentFeeAllowChange
            .PaymentFeeValue = accountClose.PaymentFeeValue
            .ShowPaymentFeeInfo = accountClose.PaymentFeeElementPk &lt;&gt; 0
          Else
            Success = False
            finBL.Error.ErrorExtend("Could not Calculate Payment Fee.")
          End If
        End If

        .TransactionTypeId = accountClose.TransactionTypeId
        Select Case accountClose.Account.AccountClass
          Case isefinAccountClass.Deposit
            ' Deposits
            Select Case accountClose.CloseMethod
              Case isefinAccountCloseMethod.Closed, isefinAccountCloseMethod.EarlyRedemption
                ' Withdrawal - Cannot do an inwards Payment
                If accountClose.BalanceDue &lt; 0 Then
                  .TransactionTypeFilter = finBL.TransactionTypes.GetDataViewFilter_AccountClose(isefinElementType.Withdrawal, accountClose.Account.AccountTypePk)
                  .ConfirmationPaymentCaption = "Please confirm the Redemption value."
                  .PaymentValueCaption = "AMOUNT DUE:"
                  .PaymentValueNetCaption = "Net Due:"
                  .TransactionTypeTag = "Withdrawal"
                  .PaymentMethodCaption = "Enter the Withdrawal method and Banking details."
                  .PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Outgoing
                Else
                  Success = False
                  finBL.Error.ErrorBeginFormat("Cannot make an inwards Payment on Account Class '{0}'.", AccountClose.Account.AccountClassText)
                End If
              Case Else
                Success = False
                finBL.Error.ErrorBeginFormat("Invalid close method for Account Class '{0}'.", AccountClose.Account.AccountClassText)
            End Select

          Case Else
            ' Loans/ Disbursements
            Select Case accountClose.CloseMethod
              Case isefinAccountCloseMethod.Closed, isefinAccountCloseMethod.EarlySettlement
                ' Payment or Refund?
                If accountClose.BalanceDue &lt; 0 Then
                  .TransactionTypeFilter = finBL.TransactionTypes.GetDataViewFilter_AccountClose(isefinElementType.Refund, accountClose.Account.AccountTypePk)
                  .ConfirmationPaymentCaption = "Please confirm the Refund value."
                  .PaymentValueCaption = "REFUND DUE:"
                  .PaymentValueNetCaption = "Net Refund:"
                  .TransactionTypeTag = "Refund"
                  .PaymentMethodCaption = "Enter the Refund method and Banking details."
                  .PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Outgoing
                Else
                  .TransactionTypeFilter = finBL.TransactionTypes.GetDataViewFilter_AccountClose(isefinElementType.PaymentReceived, accountClose.Account.AccountTypePk)
                  .ConfirmationPaymentCaption = "Please confirm the Payment value."
                  .PaymentValueCaption = "PAYMENT DUE:"
                  .PaymentValueNetCaption = "Net Payment:"
                  .TransactionTypeTag = "Payment"
                  .PaymentMethodCaption = "Enter the Payment method and Banking details."
                  .PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Incoming
                End If

              Case Else
                Success = False
                finBL.Error.ErrorBeginFormat("Invalid close method for Account Class '{0}'.", AccountClose.Account.AccountClassText)
            End Select
        End Select
    End Select
  End With

  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 AccountClose As finAccountClose
  Dim ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' 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

  ' Create Account Close object
  If Success Then
    Select Case PageId
      Case "General"
        Success = CreateInitialAccountClose(WizardFinishParameters, AccountClose)

      Case Else
        Success = CreateAccountClose(WizardFinishParameters, AccountClose)
    End Select
  End If

  If Success Then
    ' Validate Page
    Select Case PageId
      Case "General"
        ConfirmList = New List(Of String)

        ' Account Class Specific
        If AccountClose.Account.AccountClass = isefinAccountClass.Deposit AndAlso AccountClose.Account.IsFixedTerm Then
          ConfirmList.Add("This is a Fixed Term Deposit. Continue and manually close Deposit?")
          Data = ConfirmList
        End If

        If Not AccountClose.Validate() Then
          FailedMessage = finBL.Error.Message(True)
        ElseIf AccountClose.RequiresCalculation Then
          FailedMessage = "Account Close failed to Calculate."
        End If

      Case "Balances"
        With accountClose
          Select Case .Account.AccountClass
            Case isefinAccountClass.Deposit
              Select Case .CloseMethod
                Case isefinAccountCloseMethod.Closed, isefinAccountCloseMethod.EarlyRedemption
                  If .BalanceDue &gt; 0 Then
                    failedMessage = "You cannot close a Deposit with a negative balance. Consider Writing Off the Deposit instead."
                  End If
              End Select

            Case Else
              Select Case .CloseMethod
                Case isefinAccountCloseMethod.Refinanced
                  ' NOTE: For future close methods
                  If .BalanceDue = 0 Then
                    failedMessage = "You cannot Refinance an Account with a nil balance."
                  End If
                Case isefinAccountCloseMethod.Reinvested
                  ' NOTE: For future close methods
                  If accountClose.BalanceDue = 0 Then
                    failedMessage = "You cannot Reinvest an Account with a nil balance."
                  End If
              End Select
          End Select
        End With

        ' Finish?
        If AccountClose.BalanceDue = 0 AndAlso Len(FailedMessage) = 0 Then
          ConfirmList = New List(Of String)
          GetFinishConfirmList(AccountClose, ConfirmList, FailedMessage)
          Data = ConfirmList
        End If

      Case "Reinvested"
        Success = WizardValidate_Reinvest(AccountClose, FailedMessage, FailedControlId, Data)

      Case "Refinance"
        Success = WizardValidate_Refinance(AccountClose, FailedMessage, FailedControlId, Data)
        
      Case "Payment", "WriteOff", "Security"
        ConfirmList = New List(Of String)
        GetFinishConfirmList(AccountClose, ConfirmList, FailedMessage)
        Data = ConfirmList
    End Select
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Validates the "Reinvest" page of the wizard.
''' &lt;/summary&gt;
Private Function WizardValidate_Reinvest(accountClose As finAccountClose,
                                         ByRef failedMessage As String,
                                         ByRef failedControlId As String,
                                         ByRef data As Object) As Boolean

  Dim ToAccount As finAccount
  Dim ConfirmList As List(Of String)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate Account if transferring to an existing
  If accountClose.RefinanceOption = isefinAccountCloseRefinanceOption.ExistingAccount Then
    If Len(accountClose.RefinanceIntoAccountId) = 0 Then
      failedMessage = "A valid Account must be specified."
    Else
      ToAccount = finBL.CreateAccount()
      Success = ToAccount.Load(accountClose.RefinanceIntoAccountId)
    End If

    ' Validate to Account
    If Success AndAlso Len(failedMessage) = 0 Then
      If ToAccount.AccountClass &lt;&gt; accountClose.Account.AccountClass Then
        failedControlId = "cboReinvestedToAccount"
        failedMessage = String.Format("The Account to Reinvest into must have an Account Class of '{0}'", accountClose.Account.AccountClassText)
      ElseIf accountClose.Account.AccountClass = isefinAccountClass.Deposit AndAlso ToAccount.Status &lt;&gt; isefinAccountStatus.Open AndAlso ToAccount.Status &lt;&gt; isefinAccountStatus.Quote Then
        failedControlId = "cboReinvestedToAccount"
        failedMessage = "The Deposit Account to Reinvest into must have a Status of 'Quote' or 'Open'."
      End If
    End If
  End If

  ' Confirmation if OK
  If Success AndAlso Len(failedMessage) = 0 Then
    ConfirmList = New List(Of String)
    GetFinishConfirmList(accountClose, ConfirmList, failedMessage)
    data = ConfirmList
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validates the "Refinance" page of the wizard.
''' &lt;/summary&gt;
Private Function WizardValidate_Refinance(accountClose As finAccountClose,
                                          ByRef failedMessage As String,
                                          ByRef failedControlId As String,
                                          ByRef data As Object) As Boolean

  Dim SecurityStmtA As finSecurityStmt
  Dim SecurityStmtB As finSecurityStmt
  Dim ConfirmList As List(Of String)
  Dim Success As Boolean
  Dim IsLastPage As Boolean

  ' Assume Success
  Success = True

  If accountclose.RefinanceOption = isefinAccountCloseRefinanceOption.ExistingAccount Then
    ' Load Security Statements
    If LoadSecurityStatements(accountclose.RefinanceIntoAccountId, SecurityStmtA, SecurityStmtB) Then
      If SecurityStmtA IsNot Nothing OrElse SecurityStmtB IsNot Nothing Then
        ' Page exists after Refinance Page (Security)
        IsLastPage = False
      Else 
        ' No page exists, prompt User
        IsLastPage = True
      End If
    Else 
      Success = False
    End If
  Else 
    IsLastPage = True
  End If

  ' Last page? Validate fully
  If Success AndAlso IsLastPage Then
    ConfirmList = New List(Of String)
    GetFinishConfirmList(accountClose, ConfirmList, failedMessage)
    data = ConfirmList
  End If
  
  Return Success

End Function

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

  ' Record
  Public AccountClassIsDeposit As Boolean
  Public AccountClassMultiplier As Integer
  Public AccountTypeId As String
  Public ProductTypeId As String
  Public RecordDescription As String
  Public RecordId As String

  ' Account Close
  Public AccountClose As AccountCloseData

  ' General
  Public ClosedPendingReviewDays As Integer
  Public CloseNotesListId As String

  ' Balance
  Public AccruedInterestOriginal As Decimal
  Public AccruedDefaultInterestOriginal As Decimal
  Public UnpostedDefaultFeesOriginal As Decimal
  Public UnpostedFacilityFeesOriginal As Decimal
  Public UnpostedOverLimitFeesOriginal As Decimal
  Public FeeValueOriginal As Decimal
  Public OtherInterestDescription As String

  ' Payment Due
  Public TransactionTypeFilter As String

  ' Account Summary
  Public AccountSummaryHtml As String
  Public AccountCloseSummaryHtml As String

  ' Lists
  Public AccountTypes As New List(Of AccountTypeData)
  Public CloseMethodsData As New List(Of CloseMethodData)
  Public RefinanceOptionList As Object
  Public RefinanceToSqlWhere As String

  ' Other
  Public AllowUpdates As Boolean
  Public DocumentWarning As String
  Public EmailBroker As String
  Public EmailClientsOther As Object
  Public EmailDealer As String
  Public EmailMainClient As String
  Public IsRefinance As Boolean
  Public LockCloseMethod As Boolean

  ' Configuration  
  Public AddonSecurityRegister As Boolean
  Public CanAddLog As Boolean
  Public CanClose As Boolean
  Public CanClosePending As Boolean
  Public CanCreateDocument As Boolean
  Public CanSendEmail As Boolean  
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean
  Public SecurityFullDetails As Boolean
  Public ShowCashRegister As Boolean

End Class



''' &lt;summary&gt;
'''  Account Type Information.
''' &lt;/summary&gt;
Public Class AccountTypeData

  Public AccountTypeId As String
  Public Description As String
  Public OptionAllowRefinanceInto As Boolean
  Public ProductTypeId As String
  Public PromotionAllowBlank As Boolean
  Public Promotions As New List(Of AccountTypePromotionData)
  Public PromotionShow As Boolean

  Public Sub New(accountType As finAccountTypeRO,
                 account As finAccount)

    Dim AccountTypePromotionRO As finAccountTypePromotionRO

    With accountType
      Me.AccountTypeId = .AccountTypeId
      Me.Description = .Description      
      Me.ProductTypeId = .ProductTypeId

      ' Refinance
      If accountType.AccountClass = isefinAccountClass.Deposit Then
        Me.OptionAllowRefinanceInto = True
      Else 
        Me.OptionAllowRefinanceInto = .OptionAllowRefinanceInto
      End If
      
      ' Promotions
      If finBLShared.Settings.AddOns.Promotions Then
        Select Case .PromotionBasis
          Case isefinAccountTypePromotionBasis.DoesNotUsePromotions
            Me.PromotionShow = False
            Me.PromotionAllowBlank = True

          Case isefinAccountTypePromotionBasis.MustUsePromotion
            Me.PromotionShow = True
            Me.PromotionAllowBlank = False

          Case isefinAccountTypePromotionBasis.PromotionOptional
            Me.PromotionShow = True
            Me.PromotionAllowBlank = True
        End Select

        ' Promotions
        If Me.PromotionShow Then
          For Each AccountTypePromotionRO In accountType.Promotions.GetAvailablePromotions(account)
            Promotions.Add(New AccountTypePromotionData(AccountTypePromotionRO))
          Next
        End If
      Else
        Me.PromotionShow = False
        Me.PromotionAllowBlank = True
      End If
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Account Type Promotion Data.
''' &lt;/summary&gt;
Public Class AccountTypePromotionData

  Public PromotionId As String
  Public Description As String
  Public DateStart As Date?
  Public DateStop As Date?

  Public Sub New(accountTypePromotionRO As finAccountTypePromotionRO)

    With accountTypePromotionRO
      Me.PromotionId = .PromotionId
      Me.Description = .Description
      Me.DateStart = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateStart)
      Me.DateStop = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateStop)
    End With

  End Sub

End Class


''' &lt;summary&gt;
'''  Account Close Information.
''' &lt;/summary&gt;
Public Class AccountCloseData
  ' General
  Public CloseDate As Date
  Public CloseMethodText As String
  Public CloseNote As String
  Public CloseNoteDefault As String
  Public CloseNotesListId As String
  Public ClosePending As Boolean
  Public ClosedPendingReviewDays As Integer
  Public FuturePayments As Decimal
  Public FuturePaymentsShow As Boolean
  Public ShowClosePending As Boolean
  Public ShowFuturePaymentsShow As Boolean

  ' Summary
  Public SummaryItems As List(Of SummaryItem)

  ' Balance
  Public AccruedDefaultInterest As Decimal
  Public AccruedDefaultInterestCharge As Boolean
  Public AccruedDefaultInterestChargeCaption As String
  Public AccruedDefaultInterestReadOnly As Boolean
  Public AccruedInterest As Decimal
  Public AccruedInterestCharge As Boolean
  Public AccruedInterestChargeCaption As String
  Public AccruedInterestReadOnly As Boolean
  Public AccruedOtherInterest As Decimal
  Public AccruedOtherInterestCharge As Boolean
  Public AccruedOtherInterestReadOnly As Boolean
  Public AdjustmentValue As Decimal
  Public AdjustmentValueReadOnly As Boolean
  Public BalanceCurrent As Decimal
  Public BalanceDue As Decimal
  Public BalanceDueReadOnly As Boolean
  Public BalanceNet As Decimal
  Public FeeChargeFee As Boolean
  Public FeesHeadingCaption As String
  Public FeeValue As Decimal
  Public FeeValueReadOnly As Boolean
  Public LossError As String
  Public LossMessage As String
  Public LossValue As Decimal
  Public LossValueReadOnly As Boolean
  Public Other1Caption As String
  Public Other1Charge As Boolean
  Public Other1ValueReadOnly As Boolean
  Public Other1Value As Decimal
  Public Other2Caption As String
  Public Other2Charge As Boolean
  Public Other2ValueReadOnly As Boolean
  Public Other2Value As Decimal
  Public ResidualValueReadOnly As Boolean
  Public ResidualCreditResidual As Boolean
  Public ResidualValue As Decimal
  Public ResidualValueBlankTip As String
  Public TotalCredits As Decimal
  Public UnpostedDefaultFeesChargeCaption As String
  Public UnpostedOverLimitFeesChargeCaption As String
  Public UnpostedFacilityFeesChargeCaption As String
  Public UnpostedStandardTransactionsChargeCaption As String
  Public UnpostedDefaultFeesCharge As Boolean
  Public UnpostedDefaultFeesReadOnly As Boolean
  Public UnpostedDefaultFees As Decimal
  Public UnpostedOverLimitFeesCharge As Boolean
  Public UnpostedOverLimitFeesReadOnly As Boolean
  Public UnpostedOverLimitFees As Decimal
  Public UnpostedFacilityFeesCharge As Boolean
  Public UnpostedFacilityFeesReadOnly As Boolean
  Public UnpostedFacilityFees As Decimal
  Public UnpostedFacilityFeesBlankTip As String
  Public UnpostedStandardTransactionsCharge As Boolean
  Public UnpostedStandardTransactions As Decimal
  Public UnpostedStandardTransactionsChargeVisible As Boolean
  Public WithholdingTaxRate As Double
  Public WithholdingTaxValue As Decimal
  Public WithholdingTaxLabel As String

  Public SupportsWithholdingTax As Boolean
  Public ShowAccruedDefaultInterest As Boolean
  Public ShowAccruedInterest As Boolean
  Public ShowAccruedOtherInterest As Boolean
  Public ShowAdjustmentValue As Boolean
  Public ShowFeeValue As Boolean
  Public ShowFeesHeading As Boolean
  Public ShowLossValue As Boolean
  Public ShowOther1Value As Boolean
  Public ShowOther2Value As Boolean
  Public ShowResidualCreditResidual As Boolean
  Public ShowResidualValue As Boolean
  Public ShowResidualValueReadOnly As Boolean
  Public ShowUnpostedDefaultFees As Boolean
  Public ShowUnpostedFacilityFees As Boolean
  Public ShowUnpostedOverLimitFees As Boolean
  Public ShowUnpostedStandardTransactionsCharge As Boolean
  Public ShowWithholdingTaxValue As Boolean

  ' Payment Due
  Public PaymentData As PaymentData

  ' Transaction Info
  Public CanPrintSummary As Boolean
  Public TransactionReference As String
  Public TransactionNotes As String

  ' Refinance
  Public RefinanceOption As String

  ' Account Summary
  Public AccountSummaryHtml As String
  Public AccountCloseSummaryHtml As String

End Class

''' &lt;summary&gt;
'''  Close Method data.
''' &lt;/summary&gt;
Public Class CloseMethodData
  
  Public CloseMethod As String
  Public CloseMethodText As String
  Public DefaultNotes As String
  Public DefaultReference As String
  
  Public Sub New(closeMethod As isefinAccountCloseMethod,
                 account As finAccount)
    
    Me.CloseMethod = closeMethod.ToString()
    Me.CloseMethodText = finBLShared.Enums.isefinAccountCloseMethod_ToString(closeMethod)
    
    With account.AccountType.ElementLinks
      Select Case closeMethod
        Case isefinAccountCloseMethod.BadDebtWriteOff
          ' Bad Debt Write Off
          With .ItemByElementLinkType(isefinAccountTypeElementLinkType.CloseBadDebtWriteOff)
            If finBLShared.Elements.ExistsPk(.ElementPk) Then
              With finBLShared.Elements.ItemByPk(.ElementPk)
                Me.DefaultNotes = .TransactionNotes
                Me.DefaultReference = .TransactionReferenceResolved
              End With
            End If
          End With
          
        Case isefinAccountCloseMethod.Cancelled
          ' Cancelled
          With .ItemByElementLinkType(isefinAccountTypeElementLinkType.CloseCancelled)
            If finBLShared.Elements.ExistsPk(.ElementPk) Then
              With finBLShared.Elements.ItemByPk(.ElementPk)
                Me.DefaultNotes = .TransactionNotes
                Me.DefaultReference = .TransactionReferenceResolved
              End With
            End If
          End With
          
        Case isefinAccountCloseMethod.Refinanced
          ' Refinance
          With .ItemByElementLinkType(isefinAccountTypeElementLinkType.CloseRefinance)
            If finBLShared.Elements.ExistsPk(.ElementPk) Then
              With finBLShared.Elements.ItemByPk(.ElementPk)
                Me.DefaultNotes = .TransactionNotes
                Me.DefaultReference = .TransactionReferenceResolved
              End With
            End If
          End With
          
        Case isefinAccountCloseMethod.Reinvested
          ' Reinvested
          With .ItemByElementLinkType(isefinAccountTypeElementLinkType.MaturityReinvestment)
            If finBLShared.Elements.ExistsPk(.ElementPk) Then
              With finBLShared.Elements.ItemByPk(.ElementPk)
                Me.DefaultNotes = .TransactionNotes
                Me.DefaultReference = .TransactionReferenceResolved
              End With
            End If
          End With
          
        Case isefinAccountCloseMethod.WrittenOff
          ' Written Off
          With .ItemByElementLinkType(isefinAccountTypeElementLinkType.CloseWrittenOff)
            If finBLShared.Elements.ExistsPk(.ElementPk) Then
              With finBLShared.Elements.ItemByPk(.ElementPk)
                Me.DefaultNotes = .TransactionNotes
                Me.DefaultReference = .TransactionReferenceResolved
              End With
            End If
          End With
          
        Case Else
          Me.DefaultNotes = ""
          Me.DefaultReference = ""
      End Select
    End With
    
  End Sub
  
End Class

''' &lt;summary&gt;
'''  Payment Information.
''' &lt;/summary&gt;
Public Class PaymentData

  Public ConfirmationPaymentCaption As String
  Public PaymentFeeCharge As Boolean
  Public PaymentFeeReadOnly As Boolean
  Public PaymentFeeValue As Decimal
  Public PaymentFlowDirection As isefinPaymentMethodPaymentFlowDirection
  Public PaymentMethodCaption As String
  Public PaymentValueCaption As String
  Public PaymentValueNetCaption As String
  Public ShowPaymentFeeInfo As Boolean
  Public TransactionTypeFilter As String
  Public TransactionTypeId As String
  Public TransactionTypeTag As String

End Class



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

  Public Data As Object
  Public FailedMessage As String
  Public FailedControlId 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

  ' General
  Public CloseDate As Date
  Public FuturePaymentsShow As Boolean
  Public CloseMethodText As String
  Public ClosePending As Boolean
  Public ClosePendingReviewDate As Date?
  Public CloseNote As String
  Public Action As String
  Public ActionData As String
  Public PrintSummary As Boolean

  ' Summary
  Public SummaryItems As List(Of SummaryItem)

  ' Balance
  Public AccruedDefaultInterest As Decimal
  Public AccruedDefaultInterestCharge As Boolean
  Public AccruedInterest As Decimal
  Public AccruedInterestCharge As Boolean
  Public AccruedOtherInterest As Decimal
  Public AccruedOtherInterestCharge As Boolean
  Public AdjustmentValue As Decimal
  Public BalanceCurrent As Decimal
  Public BalanceDue As Decimal
  Public BalanceNet As Decimal
  Public FeeChargeFee As Boolean
  Public FeeValue As Decimal
  Public LossValue As Decimal
  Public Other1Charge As Boolean
  Public Other1Value As Decimal
  Public Other2Charge As Boolean
  Public Other2Value As Decimal
  Public ResidualCreditResidual As Boolean
  Public ResidualValue As Decimal
  Public TotalCredits As Decimal
  Public UnpostedDefaultFeesCharge As Boolean
  Public UnpostedDefaultFees As Decimal
  Public UnpostedOverLimitFeesCharge As Boolean
  Public UnpostedOverLimitFees As Decimal
  Public UnpostedFacilityFeesCharge As Boolean
  Public UnpostedFacilityFees As Decimal
  Public UnpostedStandardTransactionsCharge As Boolean
  Public UnpostedStandardTransactions As Decimal

  ' Transaction Info
  Public TransactionTypeId As String
  Public TransactionReference As String
  Public TransactionNotes As String

  ' Reinvest
  Public ReinvestedAccountTypeId As String
  Public ReinvestedAccountTypePromotionId As String
  Public ReinvestedOption As String
  Public ReinvestedToAccountId As String

  ' Refinance
  Public RefinancedAccountTypeId As String
  Public RefinancedAccountTypePromotionId As String
  Public RefinancedOption As String
  Public RefinancedToAccountId As String
  Public RefinanceIntoMainSecurityStmtIsFromRefinancedAccountSecurityStmtId As String
  Public RefinanceIntoCopySecurityStmtItems As Boolean
  Public RefinanceIntoDischargeSecurityStmt As Boolean
  
  ' Payment
  Public BankingDetailsIncomingJson As String
  Public BankingDetailsOutgoingJson As String
  Public CashRegisterId As String
  Public PaymentFeeCharge As Boolean
  Public PaymentFeeValue As Decimal

End Class



''' &lt;summary&gt;
''' Summary Item details.
''' &lt;/summary&gt;
Public Class SummaryItem

  Public RowIndex As Integer

  Public Bold As Boolean
  Public Credit As Decimal
  Public CreditReadOnly As Boolean
  Public Description As String
  Public TransactionNotes As String
  Public Value As Decimal

  Public Sub New()
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 summaryItem As finAccountCloseSummaryItem,
                 reverseValues As Decimal,
                 allowUpdate As Boolean)

    Me.RowIndex = summaryItem.Parent.IndexOf(summaryItem)

    If summaryItem.ElementType = isefinElementType.Interest AndAlso summaryItem.LastTransactionDate &lt;&gt; Nothing Then
      Me.Description = summaryItem.Description &amp; " to " &amp; finBL.FormatDateLong(summaryItem.LastTransactionDate)
    Else
      Me.Description = summaryItem.Description
    End If
    If summaryItem.IsTotalItem Then
      Me.Value = summaryItem.Balance * reverseValues
      Me.Bold = True
    Else
      Me.Value = summaryItem.Value * reverseValues
      Me.Bold = False
    End If
    If summaryItem.CreditAllowEntry Then
      Me.Credit = summaryItem.Credit * reverseValues
    Else
      Me.Credit = 0
    End If
    Me.TransactionNotes = summaryItem.TransactionNotes

    If allowUpdate AndAlso summaryItem.CreditAllowEntry AndAlso summaryItem.CreditAllowUpdates Then
      Me.CreditReadOnly = False
    Else
      Me.CreditReadOnly = True
    End If
  End Sub

End Class



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

  ' General
  Public AccountLogPk As Integer
  Public BankInterfaceRequestMessage As String
  Public BankInterfaceRequestSent As Boolean
  Public DocumentId As String
  Public Information As String
  Public RefinanceAccountId As String
  Public Warning As String

  Public Sub New(accountLogPk As Integer,
                 bankInterfaceRequestMessage As String,
                 bankInterfaceRequestSent As Boolean,
                 documentId As String,
                 information As String,
                 refinanceAccountId As String,
                 warning As String)

    Me.AccountLogPk = accountLogPk
    Me.BankInterfaceRequestMessage = bankInterfaceRequestMessage
    Me.BankInterfaceRequestSent = bankInterfaceRequestSent
    Me.DocumentId = documentId
    Me.Information = information
    Me.RefinanceAccountId = refinanceAccountId
    Me.Warning = warning

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountClose".

LIMITATION: This widget does not support Refinance (Loans).

NOTE: Uses template Email and Message defined on the Account Settlement Summary Document for the Account Type.

This Widget supports being run from a Workflow and automatically actioning the Workflow Item.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Enter the Account Close details."&gt;Account Close Details&lt;/li&gt;
        &lt;li tabId="Summary"&gt;Credits (Rebates) Due&lt;/li&gt;
        &lt;li tabId="Balances"&gt;Accruals and Other Charges&lt;/li&gt;
        &lt;li tabId="Reinvested"&gt;Reinvestment Details&lt;/li&gt;
        &lt;li tabId="WriteOff"&gt;Transaction Details&lt;/li&gt;
        &lt;li tabId="Refinance"&gt;Transaction Details&lt;/li&gt;
        &lt;li tabId="Payment"&gt;Transaction Details&lt;/li&gt;
        &lt;li tabId="Security" tooltipText="Specify how to handle Security Statements for the Refinanced Account."&gt;Security Statements&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"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAccount"&gt;Account&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRecord"&gt;Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRecord" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblOptions"&gt;Enter the date to close and other options&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateClose"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateClose" /&gt; &lt;input id="chkFuturePaymentsShow" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCloseMethod"&gt;Method:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCloseMethod" /&gt; &lt;input id="chkClosePending" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateClosePendingReview"&gt;Review on:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateClosePendingReview" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCloseNote"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCloseNote" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trPermissionWarning"&gt;
          &lt;td colspan="2"&gt;&lt;div id="divPermissionWarning" class="is-info-text info warning"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAccountSummary"&gt;Account Summary&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="wbAccountSummary"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Summary --&gt;
    &lt;div id="pageSummary" style="display:flex; flex-direction:column"&gt;
      &lt;!-- Top Panel --&gt;
      &lt;div style="flex-grow:3; position:relative"&gt;
        &lt;div id="gridSummaryItems" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;

      &lt;!-- Bottom Panel --&gt;
      &lt;div style="flex-grow:1; position:relative; max-height:200px;"&gt;
        &lt;div id="wbSummaryItems"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Balances --&gt;
    &lt;div id="pageBalances"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:14em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAccountBalance"&gt;Account Balance&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceCurrent"&gt;Current Balance:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceCurrent" /&gt; &lt;button id="cmdSchedule" Class="is-button small" icon="Schedule"&gt;Schedule&lt;/button&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblCreditAccrualsTransactions"&gt;Plus Credits, Accruals and Transactions not yet posted&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numTotalCredits"&gt;Total Credits:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numTotalCredits" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAccruedInterest"&gt;Accrued Interest:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numAccruedInterest" /&gt; &lt;input id="chkAccruedInterestCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numWithholdingTaxValue"&gt;Withholding Tax:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numWithholdingTaxValue" /&gt;&amp;emsp;&lt;label id="lblWithholdingTax"&gt;&lt;/label&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAccruedDefaultInterest"&gt;Accrued Default Interest:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numAccruedDefaultInterest" /&gt; &lt;input id="chkAccruedDefaultInterestCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAccruedOtherInterest"&gt;Accrued Other Interest:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numAccruedOtherInterest" /&gt; &lt;input id="chkAccruedOtherInterestCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numUnpostedDefaultFees"&gt;Unposted Default Fees:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numUnpostedDefaultFees" /&gt; &lt;input id="chkUnpostedDefaultFeesCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numUnpostedOverLimitFees"&gt;Unposted Over Limit Fees:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numUnpostedOverLimitFees" /&gt; &lt;input id="chkUnpostedOverLimitFeesCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numUnpostedFacilityFees"&gt;Unposted Facility Fees:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numUnpostedFacilityFees" /&gt; &lt;input id="chkUnpostedFacilityFeesCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numUnpostedStandardTransactions"&gt;Unposted Transactions:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numUnpostedStandardTransactions" /&gt; &lt;input id="chkUnpostedStandardTransactionsCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceNet"&gt;Net Balance:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceNet" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblLossFeesAdjustments"&gt;Plus Loss, Fees and Adjustments&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numLossValue"&gt;Loss:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numLossValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numFeeValue"&gt;Fee:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numFeeValue" /&gt; &lt;input id="chkFeeChargeFee" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numOther1Value"&gt;Other1:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numOther1Value" /&gt; &lt;input id="chkOther1Charge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numOther2Value"&gt;Other2:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numOther2Value" /&gt; &lt;input id="chkOther2Charge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAdjustmentValue"&gt;Adjustment:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numAdjustmentValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblResidualCredit"&gt;Less Residual credit&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numResidualValue"&gt;Residual Credit:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numResidualValue" /&gt; &lt;input id="chkResidualCreditResidual" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceDue"&gt;PAYMENT DUE:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceDue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="divAccountInformation" class="is-info-text info small" style="display:none"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Reinvested --&gt;
    &lt;div id="pageReinvested"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblReinvestedValue"&gt;Please confirm the value Reinvesting&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numReinvestedValue"&gt;REINVESTMENT:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numReinvestedValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblReinvestedTransactionDetails"&gt;Specify Transaction details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtReinvestedReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtReinvestedReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtReinvestedNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtReinvestedNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblReinvestedOptions"&gt;Specify Reinvestment options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboReinvestedOption"&gt;Option:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboReinvestedOption" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboReinvestedProductType"&gt;Product Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboReinvestedProductType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboReinvestedAccountType"&gt;Account Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboReinvestedAccountType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboReinvestedAccountTypePromotion"&gt;Promotion:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboReinvestedAccountTypePromotion" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboReinvestedToAccount"&gt;Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboReinvestedToAccount" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Write Off --&gt;
    &lt;div id="pageWriteOff"&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="lblConfirmationWriteOff"&gt;Please confirm the value to Write Off&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numWriteOffValue"&gt;WRITTEN OFF:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numWriteOffValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblConfirmationWriteOffTransactionDetails"&gt;Specify Transaction details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtWriteOffReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtWriteOffReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtWriteOffNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtWriteOffNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Refinance --&gt;
    &lt;div id="pageRefinance"&gt;
      &lt;table class="is-form" style="height:100%"&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="lblConfirmationRefinance"&gt;Please confirm the value Refinancing&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numRefinanceValue"&gt;REFINANCE:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numRefinanceValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblConfirmationRefinanceTransactionDetails"&gt;Specify Transaction details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRefinanceReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRefinanceReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRefinanceNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRefinanceNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRefinanceOptions"&gt;Specify Refinance options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRefinanceOption"&gt;Option:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRefinanceOption" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRefinanceProductType"&gt;Product Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRefinanceProductType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRefinanceAccountType"&gt;Account Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRefinanceAccountType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRefinanceAccountTypePromotion"&gt;Promotion:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRefinanceAccountTypePromotion" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRefinanceToAccount"&gt;Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRefinanceToAccount" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRefinanceSummary"&gt;Refinance summary&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="wbRefinanceSummary"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Payment --&gt;
    &lt;div id="pagePayment"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPayment"&gt;Please confirm the Payment value&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numPaymentValue"&gt;PAYMENT DUE:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numPaymentValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPaymentTransactionDetails"&gt;Specify Transaction details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboPaymentTransactionType"&gt;Trans Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboPaymentTransactionType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPaymentReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPaymentReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPaymentNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPaymentNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPaymentWithdrawalMethod"&gt;Enter the Payment method and Banking details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tbody id="apdPaymentDetailsIncoming"&gt;&lt;/tbody&gt;
        &lt;tbody id="apdPaymentDetailsOutgoing"&gt;&lt;/tbody&gt;

        &lt;tr style="display:none"&gt;
          &lt;th&gt;&lt;label for="numPaymentFee"&gt;Payment Fee:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numPaymentFee" /&gt; &lt;input id="chkPaymentFee" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="display:none"&gt;
          &lt;th&gt;&lt;label for="numNetPayment"&gt;Net Payment:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numNetPayment" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblOtherOptions"&gt;Other options&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;input id="chkPrintSummary" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    &lt;!-- Security --&gt;
    &lt;div id="pageSecurity"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:11em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSecurityStmts"&gt;Security Statements&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboSecurityStatementA"&gt;Security Stmt A:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboSecurityStatementA" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboSecurityStatementB"&gt;Security Stmt B:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboSecurityStatementB" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSecurityOptions"&gt;Options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRefinanceSecurityStmtId"&gt;Main Security Stmt:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRefinanceSecurityStmtId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRefinanceSecurityItemsCopy" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRefinanceSecurityStmtDischarge" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSecuritySummary"&gt;Security Summary&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="wbSecuritySummary"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdLog" class="is-button" icon="Log|Add" style="float:left" title="Add a Log to record the Account Close details"&gt;Add Log&lt;/button&gt;
    &lt;button id="cmdSummary" class="is-button" icon="DocumentType_PDF" style="float:left" title="Create an Account Settlement Summary and add a Log to record the Account Close details"&gt;Summary&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;
// Properties
var mRecord;
var mRecord_AccountClose;
var mRecord_AccountCloseInitial;
var mRecord_PaymentData;
var mRecord_SummaryItems;

// Controls
var C = {
  // General
  lblAccount: null,
  cboRecord: null,

  lblOptions: null,
  dateClose: null,
  chkFuturePaymentsShow: null,
  cboCloseMethod: null,
  chkClosePending: null,
  dateClosePendingReview: null,
  cboCloseNote: null,
  
  trPermissionWarning: null,
  divPermissionWarning: null,

  lblAccountSummary: null,
  wbAccountSummary: null,

  // Summary
  lblPageSummary: null,
  gridSummaryItems: null,
  wbSummaryItems: null,

  // Balances
  lblAccountBalance: null,
  numBalanceCurrent: null,
  lblCreditAccrualsTransactions: null,
  numTotalCredits: null,
  numAccruedInterest: null,
  chkAccruedInterestCharge: null,
  numWithholdingTaxValue: null,
  lblWithholdingTax: null,
  numAccruedDefaultInterest: null,
  chkAccruedDefaultInterestCharge: null,
  numAccruedOtherInterest: null,
  chkAccruedOtherInterestCharge: null,
  numUnpostedDefaultFees: null,
  chkUnpostedDefaultFeesCharge: null,
  numUnpostedOverLimitFees: null,
  chkUnpostedOverLimitFeesCharge: null,
  numUnpostedFacilityFees: null,
  chkUnpostedFacilityFeesCharge: null,
  numUnpostedStandardTransactions: null,
  chkUnpostedStandardTransactionsCharge: null,
  numBalanceNet: null,
  lblLossFeesAdjustments: null,
  numLossValue: null,
  numFeeValue: null,
  chkFeeChargeFee: null,
  numOther1Value: null,
  chkOther1Charge: null,
  numOther2Value: null,
  chkOther2Charge: null,
  numAdjustmentValue: null,
  lblResidualCredit: null,
  numResidualValue: null,
  chkResidualCreditResidual: null,
  numBalanceDue: null,
  divAccountInformation: null,

  // Reinvested
  lblReinvestedValue: null,
  numReinvestedValue: null,

  lblReinvestedTransactionDetails: null,
  txtReinvestedReference: null,
  txtReinvestedNotes: null,

  lblReinvestedOptions: null,
  cboReinvestedOption: null,
  cboReinvestedProductType: null,
  cboReinvestedAccountType: null,
  cboReinvestedAccountTypePromotion: null,
  cboReinvestedToAccount: null,

  // Write Off
  lblConfirmationWriteOff: null,
  numWriteOffValue: null,
  lblConfirmationWriteOffTransactionDetails: null,
  txtWriteOffReference: null,
  txtWriteOffNotes: null,

  // Refinance
  lblConfirmationRefinance: null,
  numRefinanceValue: null,
  
  lblConfirmationRefinanceTransactionDetails: null,
  txtRefinanceReference: null,
  txtRefinanceNotes: null,
  
  lblRefinanceOptions: null,
  cboRefinanceOption: null,
  cboRefinanceProductType: null,
  cboRefinanceAccountType: null,
  cboRefinanceAccountTypePromotion: null,
  cboRefinanceToAccount: null,
  
  lblRefinanceSummary: null,
  wbRefinanceSummary: null,

  // Payment
  lblPayment: null,
  numPaymentValue: null,
  lblPaymentTransactionDetails: null,
  cboPaymentTransactionType: null,
  txtPaymentReference: null,
  txtPaymentNotes: null,
  lblPaymentWithdrawalMethod: null,
  apdPaymentDetailsIncoming: null,
  apdPaymentDetailsOutgoing: null,
  numPaymentFee: null,
  chkPaymentFee: null,
  numNetPayment: null,
  lblOtherOptions: null,
  chkPrintSummary: null,
  
  // Security
  lblSecurityStmts: null,
  cboSecurityStatementA: null,
  cboSecurityStatementB: null,
  
  lblSecurityOptions: null,
  cboRefinanceSecurityStmtId: null,
  chkRefinanceSecurityItemsCopy: null,
  chkRefinanceSecurityStmtDischarge: null,
  
  lblSecuritySummary: null,
  wbSecuritySummary: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdLog;
var cmdSummary;

var cmdSchedule;

// Other
var mAccountClose_RefetchRequired = false;
var mRefreshTimerRefinanceToAccount;
var mRefreshTimerInitialAccountClose;
var mRefreshTimerSecuritySummary;
var mSecurityStmtInformation;

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

  // --------
  // Controls
  // --------
  //  General
  C.lblAccount = widget.UI.Label("lblAccount", {});
  C.cboRecord = widget.UI.DBCombo("cboRecord", {
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10
  });

  C.lblOptions = widget.UI.Label("lblOptions", {});
  C.dateClose = widget.UI.DateBox("dateClose", {
    allowBlank: false,

    onChange: Close_Change,
  });
  C.chkFuturePaymentsShow = widget.UI.CheckBox("chkFuturePaymentsShow", {
    caption: "Show Future Payments?",

    onChange: Close_Change,
  });

  C.cboCloseMethod = widget.UI.ComboBox("cboCloseMethod", {
    limitToList: true,
    allowBlank: false,
    width: "13em",

    onChange: Close_Change,
  });
  C.chkClosePending = widget.UI.CheckBox("chkClosePending", {
    caption: "Leave Pending?",

    onChange: chkClosePending_Change,
  });
  C.dateClosePendingReview = widget.UI.DateBox("dateClosePendingReview", {
    allowBlank: false,
  });
  C.cboCloseNote = widget.UI.InformationListComboBox("cboCloseNote", {
    maxLength: 1024,
  });

  C.trPermissionWarning = $("#trPermissionWarning");
  C.divPermissionWarning = $("#divPermissionWarning");

  C.lblAccountSummary = widget.UI.Label("lblAccountSummary", {});
  C.wbAccountSummary = widget.UI.PreviewPane("wbAccountSummary", {});

  // Summary
  C.lblPageSummary = widget.UI.Label("lblPageSummary", {});
  C.gridSummaryItems = widget.UI.Grid("gridSummaryItems", {
    stickyHeader: true,

    onBeforeCellUpdate: gridSummaryItems_BeforeCellUpdate,
    onInitialiseRow: gridSummaryItems_InitialiseRow,
    onAfterRowActivate: gridSummaryItems_AfterRowActivate,
  });
  C.wbSummaryItems = widget.UI.PreviewPane("wbSummaryItems", {});

  // Balances
  C.lblAccountBalance = widget.UI.Label("lblAccountBalance", {});
  C.numBalanceCurrent = widget.UI.NumberBox("numBalanceCurrent", {
    fontBold: true,
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,
  });
  C.lblCreditAccrualsTransactions = widget.UI.Label("lblCreditAccrualsTransactions", {});
  C.numTotalCredits = widget.UI.NumberBox("numTotalCredits", {
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,
  });
  C.numAccruedInterest = widget.UI.NumberBox("numAccruedInterest", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkAccruedInterestCharge = widget.UI.CheckBox("chkAccruedInterestCharge", {
    caption: "Charge?",

    onChange: chkAccruedInterestCharge_Change,
  });
  C.numWithholdingTaxValue = widget.UI.NumberBox("numWithholdingTaxValue", {
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,
  });
  C.lblWithholdingTax = widget.UI.Label("lblWithholdingTax", {});
  C.numAccruedDefaultInterest = widget.UI.NumberBox("numAccruedDefaultInterest", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkAccruedDefaultInterestCharge = widget.UI.CheckBox("chkAccruedDefaultInterestCharge", {
    caption: "Charge?",

    onChange: chkAccruedDefaultInterestCharge_Change,
  });
  C.numAccruedOtherInterest = widget.UI.NumberBox("numAccruedOtherInterest", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkAccruedOtherInterestCharge = widget.UI.CheckBox("chkAccruedOtherInterestCharge", {
    caption: "Charge?",

    onChange: chkAccruedOtherInterestCharge_Change,
  });
  C.numUnpostedDefaultFees = widget.UI.NumberBox("numUnpostedDefaultFees", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkUnpostedDefaultFeesCharge = widget.UI.CheckBox("chkUnpostedDefaultFeesCharge", {
    caption: "Charge?",

    onChange: chkUnpostedDefaultFeesCharge_Change,
  });
  C.numUnpostedOverLimitFees = widget.UI.NumberBox("numUnpostedOverLimitFees", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkUnpostedOverLimitFeesCharge = widget.UI.CheckBox("chkUnpostedOverLimitFeesCharge", {
    caption: "Charge?",

    onChange: chkUnpostedOverLimitFeesCharge_Change,
  });
  C.numUnpostedFacilityFees = widget.UI.NumberBox("numUnpostedFacilityFees", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkUnpostedFacilityFeesCharge = widget.UI.CheckBox("chkUnpostedFacilityFeesCharge", {
    caption: "Charge?",

    onChange: chkUnpostedFacilityFeesCharge_Change,
  });
  C.numUnpostedStandardTransactions = widget.UI.NumberBox("numUnpostedStandardTransactions", {
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,
  });
  C.chkUnpostedStandardTransactionsCharge = widget.UI.CheckBox("chkUnpostedStandardTransactionsCharge", {
    caption: "Charge?",

    onChange: chkUnpostedStandardTransactionsCharge_Change,
  });
  C.numBalanceNet = widget.UI.NumberBox("numBalanceNet", {
    fontBold: true,
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,
  });
  C.lblLossFeesAdjustments = widget.UI.Label("lblLossFeesAdjustments", {});
  C.numLossValue = widget.UI.NumberBox("numLossValue", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onButtonClick: numLossValue_ButtonClick,
    onChange: numBalance_Change,
  });
  C.numLossValue.ButtonsDefine([{id: "Info", icon: "Information", tooltipText: "Information" }]);
  C.numFeeValue = widget.UI.NumberBox("numFeeValue", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkFeeChargeFee = widget.UI.CheckBox("chkFeeChargeFee", {
    caption: "Charge?",

    onChange: chkFeeChargeFee_Change,
  });
  C.numOther1Value = widget.UI.NumberBox("numOther1Value", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkOther1Charge = widget.UI.CheckBox("chkOther1Charge", {
    caption: "Charge?",

    onChange: chkOther1Charge_Change,
  });
  C.numOther2Value = widget.UI.NumberBox("numOther2Value", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkOther2Charge = widget.UI.CheckBox("chkOther2Charge", {
    caption: "Charge?",

    onChange: chkOther2Charge_Change,
  });
  C.numAdjustmentValue = widget.UI.NumberBox("numAdjustmentValue", {
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.lblResidualCredit = widget.UI.Label("lblResidualCredit", {});
  C.numResidualValue = widget.UI.NumberBox("numResidualValue", {
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.chkResidualCreditResidual = widget.UI.CheckBox("chkResidualCreditResidual", {
    caption: "Credit?",

    onChange: chkResidualCreditResidual_Change,
  });
  C.numBalanceDue = widget.UI.NumberBox("numBalanceDue", {
    fontBold: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,

    onChange: numBalance_Change,
  });
  C.divAccountInformation = $("#divAccountInformation");

  // Reinvested
  C.lblReinvestedValue = widget.UI.Label("lblReinvestedValue", {});
  C.numReinvestedValue = widget.UI.NumberBox("numReinvestedValue", {
    fontBold: true,
    readOnly: true,
  });

  C.lblReinvestedTransactionDetails = widget.UI.Label("lblReinvestedTransactionDetails", {});
  C.txtReinvestedReference = widget.UI.TextBox("txtReinvestedReference", {
    maxLength: 20,
  });
  C.txtReinvestedNotes = widget.UI.TextBox("txtReinvestedNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });

  C.lblReinvestedOptions = widget.UI.Label("lblReinvestedOptions", {});
  C.cboReinvestedOption = widget.UI.ComboBox("cboReinvestedOption", {
    allowBlank: false,
    limitToList: true,
    width: "12em",

    onChange: cboReinvestedOption_Change,
  });
  C.cboReinvestedProductType = widget.UI.DBCombo("cboReinvestedProductType", {
    allowBlank: false,
    limitToList: true,

    onChange: cboReinvestedProductType_Change,
  });
  C.cboReinvestedAccountType = widget.UI.DBCombo("cboReinvestedAccountType", {
    allowBlank: false,
    limitToList: true,

    onChange: cboReinvestedAccountType_Change,
  });
  C.cboReinvestedAccountTypePromotion = widget.UI.DBCombo("cboReinvestedAccountTypePromotion", {
    limitToList: true,
  });
  C.cboReinvestedToAccount = widget.UI.DBCombo("cboReinvestedToAccount", {
    allowBlank: false,
  });

  // Write Off
  C.lblConfirmationWriteOff = widget.UI.Label("lblConfirmationWriteOff", {});
  C.numWriteOffValue = widget.UI.NumberBox("numWriteOffValue", {
    fontBold: true,
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,
  });
  C.lblConfirmationWriteOffTransactionDetails = widget.UI.Label("lblConfirmationWriteOffTransactionDetails", {});
  C.txtWriteOffReference = widget.UI.TextBox("txtWriteOffReference", {
    maxLength: 20,
  });
  C.txtWriteOffNotes = widget.UI.TextBox("txtWriteOffNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });

  // Refinance
  C.lblConfirmationRefinance = widget.UI.Label("lblConfirmationRefinance", {});
  
  C.numRefinanceValue = widget.UI.NumberBox("numRefinanceValue", {
    fontBold: true,
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,
  });
  C.lblConfirmationRefinanceTransactionDetails = widget.UI.Label("lblConfirmationRefinanceTransactionDetails", {});
  C.txtRefinanceReference = widget.UI.TextBox("txtRefinanceReference", {
    maxLength: 20,
  });
  C.txtRefinanceNotes = widget.UI.TextBox("txtRefinanceNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });
  
  C.lblRefinanceOptions = widget.UI.Label("lblRefinanceOptions", {});
  C.cboRefinanceOption = widget.UI.ComboBox("cboRefinanceOption", {
    allowBlank: false,
    limitToList: true,
    width: "12em",
    
    onChange: cboRefinanceOption_Change,
  });
  C.cboRefinanceProductType = widget.UI.DBCombo("cboRefinanceProductType", {
    allowBlank: false,
    limitToList: true,
    
    onChange: cboRefinanceProductType_Change,
  });
  C.cboRefinanceAccountType = widget.UI.DBCombo("cboRefinanceAccountType", {
    allowBlank: false,
    limitToList: true,
    
    onChange: cboRefinanceAccountType_Change,
  });
  C.cboRefinanceAccountTypePromotion = widget.UI.DBCombo("cboRefinanceAccountTypePromotion", {
    limitToList: true,
    
    onChange: cboRefinanceAccountTypePromotion_Change,
  });
  C.cboRefinanceToAccount = widget.UI.DBCombo("cboRefinanceToAccount", {
    allowBlank: false,
    limitToList: true,
    forceDropdown: true,
    
    onChange: cboRefinanceToAccount_Change,
  });
  
  C.lblRefinanceSummary = widget.UI.Label("lblRefinanceSummary", {
    tooltipText: "If you are Refinancing to a new Account then the details of the new Account (e.g. Term) can be modified in the New Account wizard upon clicking the 'Refinance' button.",
  });
  C.wbRefinanceSummary = widget.UI.PreviewPane("wbRefinanceSummary", {});

  // Payment
  C.lblPayment = widget.UI.Label("lblPayment", {});
  C.numPaymentValue = widget.UI.NumberBox("numPaymentValue", {
    fontBold: true,
    readOnly: true,
    decimals: -1,
    minValue: -999999999999999,
    maxValue: 999999999999999,
  });
  C.lblPaymentTransactionDetails = widget.UI.Label("lblPaymentTransactionDetails", {});
  C.cboPaymentTransactionType = widget.UI.DBCombo("cboPaymentTransactionType", {
    limitToList: true,
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboPaymentTransactionType_Change
  });
  C.txtPaymentReference = widget.UI.TextBox("txtPaymentReference", {
    maxLength: 20,
  });
  C.txtPaymentNotes = widget.UI.TextBox("txtPaymentNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });
  C.lblPaymentWithdrawalMethod = widget.UI.Label("lblPaymentWithdrawalMethod", {});
  C.apdPaymentDetailsIncoming = widget.UI.AccountIncomingPaymentDetails("apdPaymentDetailsIncoming", {
    paymentEntry: true,
    resolveReference: true,
    visible: false,

    onPaymentMethodChange: apdPaymentDetailsIncoming_Change
  });
  C.apdPaymentDetailsOutgoing = widget.UI.AccountOutgoingPaymentDetails("apdPaymentDetailsOutgoing", {
    paymentEntry: true,
    resolveReference: true,
    visible: false,

    onPaymentMethodChange: apdPaymentDetailsOutgoing_Change
  });
  C.numPaymentFee = widget.UI.NumberBox("numPaymentFee", {
    allowBlank: false,
    decimals: -1,
    minValue: 0,
    maxValue: 999999999999999,

    onChange: numPaymentFee_Change
  });
  C.chkPaymentFee = widget.UI.CheckBox("chkPaymentFee", {
    caption: "Charge?",

    onChange: chkPaymentFee_Change
  });
  C.numNetPayment = widget.UI.NumberBox("numNetPayment", {
    fontBold: true,
    readOnly: true,
    decimals: -1,
    minValue: 0,
    maxValue: 999999999999999,
  });

  C.lblOtherOptions = widget.UI.Label("lblOtherOptions", {});
  C.chkPrintSummary = widget.UI.CheckBox("chkPrintSummary", {
    caption: "Print Summary?",
  });

  // Security
  C.lblSecurityStmts = widget.UI.Label("lblSecurityStmts", {});
  C.cboSecurityStatementA = widget.UI.DBCombo("cboSecurityStatementA", {
    readOnly: true,
    showDropdown: false,
  });
  C.cboSecurityStatementB = widget.UI.DBCombo("cboSecurityStatementB", {
    readOnly: true,
    showDropdown: false,
  });
  
  C.lblSecurityOptions = widget.UI.Label("lblSecurityOptions", {
    tooltipText: "Specify how to handle Security Statements for the Refinanced Account.",
  });
  C.cboRefinanceSecurityStmtId = widget.UI.ComboBox("cboRefinanceSecurityStmtId", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    
    onChange: cboRefinanceSecurityStmtId_Change,
  });
  C.chkRefinanceSecurityItemsCopy = widget.UI.CheckBox("chkRefinanceSecurityItemsCopy", {
    caption: "Copy Security Items?",
    captionWrap: true,
    
    onChange: RefreshSecuritySummary,
  });
  C.chkRefinanceSecurityStmtDischarge = widget.UI.CheckBox("chkRefinanceSecurityStmtDischarge", {
    caption: "Discharge Security Statement?",
    captionWrap: true,
    
    onChange: RefreshSecuritySummary,
  });
  
  C.lblSecuritySummary = widget.UI.Label("lblSecuritySummary", {
    tooltipText: "Read and confirm the summary of how Security Statements should be handled for the Refinanced Account.",
  });
  C.wbSecuritySummary = widget.UI.PreviewPane("wbSecuritySummary", {});

  // Grids

  // Create Widget form
  // NOTE: Hide by default for a cleaner startup
  frmMain = new widget.UI.Form("frmMain", { visible: false });

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

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

  cmdLog = $("#cmdLog");
  cmdLog.click(function () { Form_ExecuteAction("Log"); });
  cmdSummary = $("#cmdSummary");
  cmdSummary.click(function () { Form_ExecuteAction("Summary"); });

  cmdSchedule = $("#cmdSchedule");
  cmdSchedule.click(ShowSchedule);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  C.chkPaymentFee.Value(true);

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_AccountClose = null;
  mRecord_AccountCloseInitial = null;
  mRecord_PaymentData = null;
  mRecord_SummaryItems = null;
  mSecurityStmtInformation = null;

  // 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_AccountClose = mRecord.AccountClose;
      mRecord_AccountCloseInitial = mRecord_AccountClose;
      mRecord_SummaryItems = mRecord_AccountClose.SummaryItems;
      mRecord_PaymentData = mRecord_AccountClose.PaymentData;

      // Load Fields
      Fields_Load();

      // Defaults
      C.cboCloseNote.Text(mRecord_AccountClose.CloseNoteDefault);
      
      // Close Method cannot be changed, so call its change event now to correctly default controls based upon the set Close Method
      if (mRecord.LockCloseMethod) Close_Change();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  // NOTE: The initial parameter is used so that certain values such as Accrued Interest are only set when parameters on the General page are changed

  if (mRecord &amp;&amp; mRecord_AccountClose) {
    // General
    C.cboRecord.RefreshUnbound(mRecord.RecordId, mRecord.RecordDescription);
    C.dateClose.Value(mRecord_AccountClose.CloseDate);
    C.chkFuturePaymentsShow.Value(mRecord_AccountClose.FuturePaymentsShow);
    C.cboCloseMethod.Text(mRecord_AccountClose.CloseMethodText);
    C.cboCloseNote.Text(mRecord_AccountClose.CloseNote);
    C.chkClosePending.Value(mRecord_AccountClose.ClosePending);

    // Summary
    // NOTE: Grid refreshed when moving to page

    // Balances
    C.numBalanceCurrent.Value(mRecord_AccountClose.BalanceCurrent);
    C.numTotalCredits.Value(mRecord_AccountClose.TotalCredits);
    C.numLossValue.Value(mRecord_AccountClose.LossValue);

    C.chkAccruedInterestCharge.Value(mRecord_AccountClose.AccruedInterestCharge);
    C.numAccruedInterest.Value(mRecord_AccountClose.AccruedInterest);
    C.numAccruedInterest.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.AccruedInterest, false));

    C.lblWithholdingTax.Text(mRecord_AccountClose.WithholdingTaxLabel);
    C.numWithholdingTaxValue.Value(mRecord_AccountClose.WithholdingTaxValue);
    C.numWithholdingTaxValue.BlankTip(mRecord_AccountCloseInitial.WithholdingTaxValue);

    C.chkAccruedDefaultInterestCharge.Value(mRecord_AccountClose.AccruedDefaultInterestCharge);
    C.numAccruedDefaultInterest.Value(mRecord_AccountClose.AccruedDefaultInterest);
    C.numAccruedDefaultInterest.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.AccruedDefaultInterest, false));

    C.chkAccruedOtherInterestCharge.Value(mRecord_AccountClose.AccruedOtherInterestCharge);
    C.numAccruedOtherInterest.Value(mRecord_AccountClose.AccruedOtherInterest);
    C.numAccruedOtherInterest.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.AccruedOtherInterest, false));

    C.chkUnpostedDefaultFeesCharge.Value(mRecord_AccountClose.UnpostedDefaultFeesCharge);
    C.numUnpostedDefaultFees.Value(mRecord_AccountClose.UnpostedDefaultFees);
    C.numUnpostedDefaultFees.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.UnpostedDefaultFees, false));

    C.chkUnpostedOverLimitFeesCharge.Value(mRecord_AccountClose.UnpostedOverLimitFeesCharge);
    C.numUnpostedOverLimitFees.Value(mRecord_AccountClose.UnpostedOverLimitFees);
    C.numUnpostedOverLimitFees.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.UnpostedOverLimitFees, false));

    C.chkUnpostedFacilityFeesCharge.Value(mRecord_AccountClose.UnpostedFacilityFeesCharge);
    C.numUnpostedFacilityFees.Value(mRecord_AccountClose.UnpostedFacilityFees);
    C.numUnpostedFacilityFees.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.UnpostedFacilityFees, false));

    C.chkUnpostedStandardTransactionsCharge.Value(mRecord_AccountClose.UnpostedStandardTransactionsCharge);
    C.numUnpostedStandardTransactions.Value(mRecord_AccountClose.UnpostedStandardTransactions);
    C.numUnpostedStandardTransactions.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.UnpostedStandardTransactions, false));

    C.chkFeeChargeFee.Value(mRecord_AccountClose.FeeChargeFee);
    C.numFeeValue.Value(mRecord_AccountClose.FeeValue);
    C.numFeeValue.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.FeeValue, false));

    C.chkOther1Charge.Value(mRecord_AccountClose.Other1Charge);
    C.numOther1Value.Value(mRecord_AccountClose.Other1Value);
    C.numOther1Value.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.Other1Value, false));

    C.chkOther2Charge.Value(mRecord_AccountClose.Other2Charge);
    C.numOther2Value.Value(mRecord_AccountClose.Other2Value);
    C.numOther2Value.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.Other2Value, false));

    C.numAdjustmentValue.Value(mRecord_AccountClose.AdjustmentValue);

    C.chkResidualCreditResidual.Value(mRecord_AccountClose.ResidualValueCredit);
    C.numResidualValue.Value(mRecord_AccountClose.ResidualValue);
    C.numResidualValue.BlankTip(widget.FormatCurrency(mRecord_AccountCloseInitial.ResidualValue, false));

    // Payment Due
    C.apdPaymentDetailsIncoming.ShowCashRegister(mRecord.ShowCashRegister);
    C.apdPaymentDetailsIncoming.Initialise(mRecord.RecordId, {
      applyDefaultPaymentMethod: true,
      applyDefaultCashRegister: true,
      defaultValuesOnPaymentMethodChange: true,
    });
    C.apdPaymentDetailsIncoming.FromBankingDetailsJson(mRecord.BankingDetailsIncomingJson);

    C.apdPaymentDetailsOutgoing.Initialise(mRecord.RecordId, {
      applyDefaultPaymentMethod: true,
      applyDefaultCashRegister: true,
      defaultValuesOnPaymentMethodChange: true,
    });
    C.apdPaymentDetailsOutgoing.FromBankingDetailsJson(mRecord.BankingDetailsOutgoingJson);
  }

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

  // Update Controls
  chkClosePending_Change();
  chkOther1Charge_Change();
  chkOther2Charge_Change();
  chkResidualCreditResidual_Change();

  // Update fields
  Fields_Update();

  // Refresh no longer required
  mAccountClose_RefetchRequired = false;

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Not used by this wizard since there is no concept of updating an object behind the wizard
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord.IsRefinance) {
    widget.SetHeading("Refinance Account");
  }
  
  // Information Lists
  if (mRecord &amp;&amp; mRecord_AccountClose) {
    C.cboCloseNote.SetComboFromInformationList(mRecord_AccountClose.CloseNotesListId);
  }

  // Lists
  if (mRecord &amp;&amp; mRecord_AccountClose) {
    C.cboCloseMethod.ListFromCollection(mRecord.CloseMethodsData, "CloseMethodText");
    C.cboRefinanceOption.ListFromCodeDescriptionList(mRecord.RefinanceOptionList);
    C.cboRefinanceProductType.RefreshFromStandardRange("ProductTypes");
    C.cboRefinanceToAccount.RefreshFromStandardRange("Accounts", mRecord.RefinanceToSqlWhere);
    C.cboReinvestedOption.ListFromCodeDescriptionList(mRecord.RefinanceOptionList);
    C.cboReinvestedProductType.RefreshFromStandardRange("ProductTypes");
    C.cboReinvestedToAccount.RefreshFromStandardRange("Accounts");
    // NOTE: Transaction Types are refreshed in pagePayment_Refresh
    //C.cboPaymentTransactionType.RefreshFromStandardRange("TransactionTypes", mRecord_AccountClose.TransactionTypeFilter);
  }

  // Controls
  if (mRecord &amp;&amp; mRecord_AccountClose) {
    if (mRecord.LockCloseMethod) C.cboCloseMethod.ReadOnly(true);
    if (mRecord.IsRefinance) C.cboCloseMethod.VisibleRow(false);
    C.numAdjustmentValue.ReadOnly(mRecord_AccountClose.AdjustmentValueReadOnly);
    C.numAccruedOtherInterest.Caption("Accrued " + mRecord.OtherInterestDescription);
  }

  // Refresh Page
  pageGeneral_Refresh();

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

function tabWizard_UpdateButtons() {
  // Back, Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();
    var isFinalPage;
    var closeMethod = mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()].CloseMethod;

    // Is final page
    switch(tabWizard.GetTabIdByIndex(tabIndex)) {
      case "Balances":
        if (mRecord.ReadOnly || C.numBalanceDue.Value() == 0 || C.chkFuturePaymentsShow.Value()) {
          isFinalPage = true;
        }
        else {
          isFinalPage = false;
        }
        break;

      case "Reinvested":
        isFinalPage = true;
        break;

      case "Payment":
      case "WriteOff":
        isFinalPage = true;
        break;

      case "Refinance":
        var RefinanceOption = C.cboRefinanceOption.ListIndex() == -1 ? "" : mRecord.RefinanceOptionList[C.cboRefinanceOption.ListIndex()].Code;
        switch (RefinanceOption) {
          case "NewAccount":                     
            isFinalPage = true;
            break;
      
          case "ExistingAccount":                    
            if (!mSecurityStmtInformation || !C.cboRefinanceToAccount.Text()) {
              isFinalPage = true;
            }
            else {
              isFinalPage = !mSecurityStmtInformation.ShowSecurityStmtPage;
            }
            break;
        }
        break;

      case "Security":
        isFinalPage = true;
        break;
      
      default:
        isFinalPage = false;
        break;
    }

    cmdBack.prop("disabled", tabIndex &lt;= 0);
    cmdNext.prop("disabled", isFinalPage);
  }

  // Cancel/ Finish Button
  if (mRecord &amp;&amp; (mRecord.ReadOnly || C.chkFuturePaymentsShow.Value())) {
    cmdCancel.hide();
    cmdFinish.text("Close");
    cmdFinish.prop("disabled", false);
  }
  else {
    cmdCancel.show();
    cmdFinish.prop("disabled", !isFinalPage);

    // Finish Text
    switch (C.cboCloseMethod.Text()) {
      case "Reinvested":
        cmdFinish.text("Reinvest");
        break;

      default:
        if (mRecord.IsRefinance) {
          cmdFinish.text("Refinance");
        }
        else {
          cmdFinish.text("Finish");
        }        
        break;
    }
  }

  // Print/Email Summary
  if (mRecord_AccountClose.CanPrintSummary) {
    cmdSummary.show();
    C.lblOtherOptions.VisibleRow(true);
    C.chkPrintSummary.VisibleRow(true);
  }
  else {
    cmdSummary.hide();
    C.lblOtherOptions.VisibleRow(false);
    C.chkPrintSummary.VisibleRow(false);
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.wbAccountSummary.ResizeFromParent();
      break;

    case "Reinvested":
      C.cboReinvestedProductType.WidthResizeFromParent();
      C.cboReinvestedAccountType.WidthResizeFromParent();
      C.cboReinvestedAccountTypePromotion.WidthResizeFromParent();
      C.cboReinvestedToAccount.WidthResizeFromParent();
      break;

    case "Summary":
      C.wbSummaryItems.ResizeFromParent();
      break;

    case "WriteOff":
      C.txtWriteOffReference.ResizeFromParent();
      break;

    case "Refinance":
      C.wbRefinanceSummary.ResizeFromParent();
      break;

    case "Payment":
      C.txtPaymentReference.ResizeFromParent();
      C.txtPaymentNotes.WidthResizeFromParent();
      C.apdPaymentDetailsIncoming.WidthResizeFromParent();
      C.apdPaymentDetailsOutgoing.WidthResizeFromParent();
      break;

    case "Security":
      C.wbSecuritySummary.ResizeFromParent();
      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;

  // Initialise
  var closeMethod = mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()].CloseMethod;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "Reinvested":
          switch(closeMethod) {
            case "Reinvested":
              found = true;
              break;
          }
          break;

        case "WriteOff":
          switch(closeMethod) {
            case "BadDebtWriteOff":
            case "Cancelled":
            case "WrittenOff":
              if (C.numBalanceDue.Value() != 0) found = true;
              break;
          }
          break;

        case "Refinance":
          switch(closeMethod) {
            case "Refinanced":
              found = true;
              break;
          }   
          break;

        case "Payment":
          switch(closeMethod) {
            case "Closed":
            case "EarlyRedemption":
            case "EarlySettlement":
              if (C.numBalanceDue.Value() != 0) found = true;
              break;
          }
          break;

        case "Security":
          switch(closeMethod) {
            case "Refinanced":
              found = true;
              break;
          }   
          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) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "General":
        pageGeneral_Refresh();
        break;

      case "Summary":
        gridSummaryItems_Refresh();
        break;

      case "Balances":
        pageBalance_Refresh();
        break;

      case "Reinvested":
        pageReinvested_Refresh();
        break;

      case "Payment":
        pagePayment_Refresh();
        break;

      case "WriteOff":
        pageWriteOff_Refresh();
        break;

      case "Refinance":
        pageRefinance_Refresh();
        break;

      case "Security":
        pageSecurity_Refresh();

      default:
        break;
    }
  }

  // Load information regardless of direction
  // NOTE: Required since moving back to a page may have delayed a recalculation of the Account Close details
  if (mAccountClose_RefetchRequired) GetAccountClose();

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

  // Special
  switch(tabWizard.SelectedTabId()) {
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "General":
      if (mRecord.IsRefinance) {
        frmMain.RefreshHeading("Account Refinance Details", "Enter the Account Refinance details.");
      }
      else {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      }      
      break;

    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Account '" + mRecord.RecordId + "', " + mRecord.RecordDescription + " - " + mRecord_AccountClose.CloseMethodText + ".");
      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":
      case "Balances":
      case "Reinvested":
      case "WriteOff":
      case "Refinance":
      case "Payment":
      case "Security":
        break;

      default:
        // No validation
        validCallback();
        return;
    }
  }

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        var params = {
          CloseDate: C.dateClose.Value(),
          CloseMethodText: C.cboCloseMethod.Text(),
          FuturePaymentsShow: C.chkFuturePaymentsShow.Value(),
        };
        break;

      case "Balances":
      case "Reinvested":
      case "WriteOff":
      case "Refinance":
      case "Payment":
      case "Security":
        var params = CreateFinishParameters();
        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()) {
      case "General":
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirm("This is a Fixed Term Deposit.\n\nContinue and manually close Deposit?", { heading: "Additional Confirmation", icon: "Warning", }, function () { validCallback(); }, null);

          // Allow callbacks to continue
          return;
        };
        break;

      case "Reinvested":
      case "WriteOff":
      case "Refinance":
      case "Payment":
      case "Security":
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };
        break;

      case "Balances":
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      // NOTE: Continue to finish when Balance Due = 0
                                      function () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

function Form_ExecuteAction_Option(action, data) {
  // Validate
  if (!tabWizard.Validate(true)) return;

  // Disable Form
  widget.UI.Block("Processing, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();
  params.Action = action;
  if (data) params.ActionData = data;

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

      // Show Information or Warning
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The action was successfully performed but the following warning was given:\n\n" + data.Warning);
      }
      else if(data.Information) {
        widget.UI.MsgBoxInfo(data.Information);
      }

      // Download Document?
      switch (action.toUpperCase()) {
        case "LOG":
          // Use an Application Shortcut to edit the log
          widget.ExecuteApplicationShortcutUrl("app://FormShow?form=AccountLog&amp;id=" + data.AccountLogPk);
          break;

        case "DOCUMENT":
          // Use an Application Shortcut to download the document
          widget.ExecuteApplicationShortcutUrl("app://Document?id=" + encodeURI(data.DocumentId) + "&amp;logPk=" + data.AccountLogPk);
          break;
      }

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

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

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

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      if (mRecord.ReadOnly || C.chkFuturePaymentsShow.Value()) {
        tabWizard_Cancel();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;

    case "DOCUMENT":
    case "EMAIL_BROKER":
    case "EMAIL_CLIENT": // data contains the email address
    case "EMAIL_DEALER":
    case "EMAIL_MAINCLIENT":
    case "LOG":
      // Log or Document
      Form_ExecuteAction_Option(actionId, data);
      break;

    case "SUMMARY":
      // Prompt
      if (C.dateClose.Value() &amp;&amp; C.cboCloseMethod.Text()) {
        if (mRecord.CanCreateDocument || mRecord.CanSendEmail) {
          // Prompt
          var list = [];
          if (mRecord.CanCreateDocument) list.push({ key: "DOCUMENT", caption: "Print", icon: "DocumentType_PDF", details: "Download a Close Quotation PDF." });
          if (mRecord.CanSendEmail) {
            if (mRecord.EmailMainClient) list.push({ key: "EMAIL_MAINCLIENT", caption: "Email Main Client", icon: "Client|Mail", details: "Email a Close Quotation PDF to:\n" + mRecord.EmailMainClient });
            if (mRecord.EmailBroker) list.push({ key: "EMAIL_BROKER", caption: "Email Broker", icon: "ExternalParty|Mail", details: "Email a Close Quotation PDF to:\n" + mRecord.EmailBroker });
            if (mRecord.EmailDealer) list.push({ key: "EMAIL_DEALER", caption: "Email Dealer", icon: "ExternalParty|Mail", details: "Email a Close Quotation PDF to:\n" + mRecord.EmailDealer });
            if (mRecord.EmailClientsOther) {
              for (var i = 0; i &lt; mRecord.EmailClientsOther.length; i++) {
                var item = mRecord.EmailClientsOther[i];
                list.push({ key: "EMAIL_CLIENT_" + item.Code, caption: "Email " + item.Description, icon: "AccountRole_Owner1|Mail", details: "Email a Close Quotation PDF to this Client at:\n" + item.Code });
              }
            }
          }

          widget.UI.MsgBoxList("", list, { closeOnEscape: true, title: "Account Close", showClose: true }, function (action) { 
            // Extract email address for other Clients
            var data = "";
            if (action.startsWith("EMAIL_CLIENT_")) {
              data = action.substr(13);
              action = "EMAIL_CLIENT";
            }

            // Action
            Form_ExecuteAction(action, data);
          });
        }
      }
      else {
        // Fail
        tabWizard_Validate();
      }
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  tabWizard_Validate(function () {
    Form_ExecuteAction_FinishPost();
  });
}

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

  // Create Parameters
  var params = CreateFinishParameters();

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

      // Unblock
      widget.UI.Unblock();

      // Finalise
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The Account Close was successful but the following warning was given:\n\n" + data.Warning, {}, function () { Form_ExecuteAction_FinishPost_BankInterface(data); });
      }
      else {
        Form_ExecuteAction_FinishPost_BankInterface(data);
      }
    },

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

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

function Form_ExecuteAction_FinishPost_BankInterface(data) {
  // Bank Interface information messages
  if (data.BankInterfaceRequestSent) {
    widget.UI.MsgBoxInfo(data.BankInterfaceRequestMessage, {}, function() { Form_ExecuteAction_FinishPost_Finalise(data); });
  }
  else if(data.BankInterfaceRequestMessage) {
    widget.UI.MsgBoxAlert(data.BankInterfaceRequestMessage, {}, function() { Form_ExecuteAction_FinishPost_Finalise(data); });
  }
  else {
    Form_ExecuteAction_FinishPost_Finalise(data);
  }
}

function Form_ExecuteAction_FinishPost_Finalise(data, action) {
  if (C.chkPrintSummary.Value()) {
    // Use an Application Shortcut to download the document
    widget.ExecuteApplicationShortcutUrl("app://Document?id=" + encodeURI(data.DocumentId) + "&amp;logPk=" + data.AccountLogPk);
  }

  // Notify parent (e.g., Close Accounts wizard) that an Account has been closed
  widget.ParentNotify("AccountClosed", { accountId: mRecord.RecordId });

  // Refinance (New Account)
  if (data &amp;&amp; data.RefinanceAccountId) {
    widget.ExecuteApplicationShortcutUrl("app://FormShow?form=AccountNew&amp;refinancedAccountId=" + encodeURI(data.RefinanceAccountId));
  }

  // Close Form
  widget.Close();

  // Refresh Parent (to show updated details)
  widget.RefreshParent();
}

// ============
// Page General
// ============
function Close_Change(source, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Clear Summary Page - so User can't see out-of-date information
  C.wbAccountSummary.Clear();

  // Reset defaults
  C.txtPaymentNotes.Text("");
  C.txtPaymentReference.Text("");
  C.txtRefinanceNotes.Text("");
  C.txtRefinanceReference.Text("");
  C.txtReinvestedNotes.Text("");
  C.txtReinvestedReference.Text("");
  C.txtWriteOffNotes.Text("");
  C.txtWriteOffReference.Text("");

  if (C.dateClose.Value() &amp;&amp; C.cboCloseMethod.Text()) {
    // Get Initial Account Close
    // NOTE: This resets the fields on all other pages
    GetInitialAccountClose();
  }
  
  // Update Warnings
  UpdatePermissionsWarning();
}

// ===============
// chkClosePending
// ===============
function chkClosePending_Change(source, e) {
  if (C.chkClosePending.Value()) {
    // Calculate Review Date
    var reviewDate = new Date(C.dateClose.Value());
    reviewDate.setDate(reviewDate.getDate() + mRecord.ClosedPendingReviewDays);

    // Update Review Date
    C.dateClosePendingReview.Value(reviewDate);
    C.dateClosePendingReview.VisibleRow(mRecord_AccountCloseInitial.ShowClosePending);
  }
  else {
    C.dateClosePendingReview.VisibleRow(false);
  }
  
  // Update Warnings
  UpdatePermissionsWarning();
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Visible
  if (C.cboCloseMethod.ListIndex() == -1) {
    C.chkFuturePaymentsShow.Visible(false);
    C.chkClosePending.Visible(false);
    C.dateClosePendingReview.VisibleRow(false);
  }
  else {
    C.chkFuturePaymentsShow.Visible(mRecord_AccountClose.ShowFuturePaymentsShow);
    C.chkClosePending.Visible(mRecord_AccountClose.ShowClosePending);
    C.dateClosePendingReview.VisibleRow(mRecord_AccountClose.ShowClosePending &amp;&amp; C.chkClosePending.Value());
    C.cboCloseNote.SetComboFromInformationList(mRecord_AccountClose.CloseNotesListId);
  }

  // Summary
  C.wbAccountSummary.SetContent(mRecord_AccountClose.AccountSummaryHtml, false);
}

// ================
// gridSummaryItems
// ================
function gridSummaryItems_Refresh() {
  // Add Columns
  C.gridSummaryItems.ClearColumns();
  C.gridSummaryItems.AddColumnString("Description", { caption: "Description", width: "16em", allowEdit: false });
  C.gridSummaryItems.AddColumnCurrency("Value", { caption: "Value", allowEdit: false });
  C.gridSummaryItems.AddColumnCurrency("Credit", { caption: "Credit", allowEdit: true });
  C.gridSummaryItems.AddColumnString("TransactionNotes", { caption: "Transaction Notes", width: "30em", allowEdit: true });

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mRecord_SummaryItems.GetCacheKey = function (index) { return "Summary" + index; };
  mRecord_SummaryItems.GetPreviewFetchParameters = function (index) {
    var o = {};
    if (index != -1) {
      o.closeDate = C.dateClose.Value();
      o.futurePaymentsShow = C.chkFuturePaymentsShow.Value();
      o.rowIndex = index;
      o.target = "WebInternal";
      o.highDpi = widget.IsHighDpi();
    }
    return o;
  };

  // Refresh
  C.gridSummaryItems.VirtualDataRefresh(mRecord_SummaryItems);

  // Set 1st row as active
  if (C.gridSummaryItems.ActiveDataRowIndex() &lt; 0) C.gridSummaryItems.ActiveDataRowIndex(0);

  // Preview
  wbSummaryItems_Preview();
}

function gridSummaryItems_InitialiseRow(e) {
  var item = mRecord_SummaryItems[e.row.listIndex];

  // Update cells
  e.row.cells.Description.value = item.Description;
  e.row.cells.Value.value = item.Value;
  e.row.cells.Credit.value = item.CreditReadOnly ? null : item.Credit;
  e.row.cells.TransactionNotes.value = item.TransactionNotes;

  // Read-Only
  e.row.cells.Description.readOnly = true;
  e.row.cells.Value.readOnly = true;
  e.row.cells.Credit.readOnly = item.CreditReadOnly;
  e.row.cells.TransactionNotes.readOnly = item.CreditReadOnly;

  // Bold
  e.row.bold = item.Bold;
}

function gridSummaryItems_BeforeCellUpdate(e) {
  var item = mRecord_SummaryItems[e.row.listIndex];
  var min;
  var max;

  switch(e.columnKey) {
    case "Credit":
      if (item.Value &lt; 0) {
        min = item.Value;
        max = 0;
      }
      else {
        min = 0;
        max = item.Value;
      }

      if (e.newValue &gt;= min &amp;&amp; e.newValue &lt;= max) {
        // Do not allow a null value
        if (e.newValue) {
          item.Credit = e.newValue;
        }
        else {
          item.Credit = 0;
        }        
      }
      else {
        if (e.newValue &gt; max) item.Credit = max;
        if (e.newValue &lt; min) item.Credit = min;
      }
      break;

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

  // Requires Refresh
  mAccountClose_RefetchRequired = true;
}

function gridSummaryItems_AfterRowActivate(e) {
  // Preview
  wbSummaryItems_Preview();
}

function wbSummaryItems_Preview() {
  C.wbSummaryItems.PreviewFromGridCollection(C.gridSummaryItems, mRecord_SummaryItems, "GetSummaryItemPreview");
}

// ==============
// Balance Values
// ==============
function chkAccruedInterestCharge_Change(sender, e) {
  // Update
  if (e &amp;&amp; !C.chkAccruedInterestCharge.Value()) {
    C.numAccruedInterest.BlankTip(C.numAccruedInterest.Value());
    C.numAccruedInterest.ValueIsBlank(true);
  }
  
  // Update Controls
  chkCharge_Change(sender, e);
}

function chkAccruedDefaultInterestCharge_Change(sender, e) {
  // Update
  if (e &amp;&amp; !C.chkAccruedDefaultInterestCharge.Value()) {
    C.numAccruedDefaultInterest.BlankTip(C.numAccruedDefaultInterest.Value());
    C.numAccruedDefaultInterest.ValueIsBlank(true);
  }
  
  // Update Controls
  chkCharge_Change(sender, e);
}

function chkAccruedOtherInterestCharge_Change(sender, e) {
  // Update
  if (e &amp;&amp; !C.chkAccruedOtherInterestCharge.Value()) {
    C.numAccruedOtherInterest.BlankTip(C.numAccruedOtherInterest.Value());
    C.numAccruedOtherInterest.ValueIsBlank(true);
  }
  
  // Update Controls
  chkCharge_Change(sender, e);
}

function chkUnpostedDefaultFeesCharge_Change(sender, e) {
  // Update
  if (e &amp;&amp; !C.chkUnpostedDefaultFeesCharge.Value()) {
    C.numUnpostedDefaultFees.BlankTip(C.numUnpostedDefaultFees.Value());
    C.numUnpostedDefaultFees.ValueIsBlank(true);
  }
  
  // Update Controls
  chkCharge_Change(sender, e);
}

function chkUnpostedOverLimitFeesCharge_Change(sender, e) {
  // Update
  if (e &amp;&amp; !C.chkUnpostedOverLimitFeesCharge.Value()) {
    C.numUnpostedOverLimitFees.BlankTip(C.numUnpostedOverLimitFees.Value());
    C.numUnpostedOverLimitFees.ValueIsBlank(true);
  }
  
  // Update Controls
  chkCharge_Change(sender, e);
}

function chkUnpostedFacilityFeesCharge_Change(sender, e) {
  // Update
  if (e &amp;&amp; !C.chkUnpostedFacilityFeesCharge.Value()) {
    C.numUnpostedFacilityFees.BlankTip(C.numUnpostedFacilityFees.Value());
    C.numUnpostedFacilityFees.ValueIsBlank(true);
  }
  
  // Update Controls
  chkCharge_Change(sender, e);
}

function chkUnpostedStandardTransactionsCharge_Change(sender, e) {
  // Update
  if (e &amp;&amp; !C.chkUnpostedStandardTransactionsCharge.Value()) {
    C.numUnpostedStandardTransactions.BlankTip(C.numUnpostedStandardTransactions.Value());
    C.numUnpostedStandardTransactions.ValueIsBlank(true);
  }
  
  // Update Controls
  chkCharge_Change(sender, e);
}

function chkFeeChargeFee_Change(sender, e) {
  // Update
  if (e &amp;&amp; !C.chkFeeChargeFee.Value()) {
    C.numFeeValue.BlankTip(C.numFeeValue.Value());
    C.numFeeValue.ValueIsBlank(true);
  }
  
  // Update Controls
  chkCharge_Change(sender, e);
}

function chkOther1Charge_Change(sender, e) {
  // Update
  // Special case - because this is one of the few checkboxes unchecked by default
  if (!C.chkOther1Charge.Value()) {
    C.numOther1Value.BlankTip(C.numOther1Value.Value());
    C.numOther1Value.ValueIsBlank(true);
  }
  
  // Update Controls
  if (e) chkCharge_Change(sender, e);
}

function chkOther2Charge_Change(sender, e) {
  // Update
  // Special case - because this is one of the few checkboxes unchecked by default
  if (!C.chkOther2Charge.Value()) {
    C.numOther2Value.BlankTip(C.numOther2Value.Value());
    C.numOther2Value.ValueIsBlank(true);
  }
  
  // Update Controls
  if (e) chkCharge_Change(sender, e);
}

function chkResidualCreditResidual_Change(sender, e) {
  // Update
  // Special case - because this is one of the few checkboxes unchecked by default
  if (!C.chkResidualCreditResidual.Value()) {
    C.numResidualValue.BlankTip(C.numResidualValue.Value());
    C.numResidualValue.ValueIsBlank(true);
  }
  
  // Update Controls
  if (e) chkCharge_Change(sender, e);
}

function chkCharge_Change(source, e) {
  mAccountClose_RefetchRequired = true;

  // If unchecking, update blank tip
  if (C.chkAccruedInterestCharge.VisibleRow() &amp;&amp; !C.chkAccruedInterestCharge.Value()) {
    if (mRecord_AccountClose.SupportsWithholdingTax) {
      C.numWithholdingTaxValue.BlankTip(widget.FormatCurrency(C.numWithholdingTaxValue.Value()));
    }
  }

  // Calculate
  Balances_Calculate(false);

  // Requires Refresh
  mAccountClose_RefetchRequired = true;
}

function numBalance_Change(source, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Calculate
  Balances_Calculate(source === C.numBalanceDue);

  // Requires Refresh
  mAccountClose_RefetchRequired = true;
}

function Balances_Calculate(setAdjustmentValue) {
  // Update Controls
  // NOTE: This must be done first since it changes blank tips to values that are used below
  BalanceControlsUpdate()

  // Balance Net
  var netBalance = mRecord_AccountClose.BalanceCurrent - mRecord_AccountClose.FuturePayments;
  netBalance += C.numTotalCredits.Value();
  if (C.chkAccruedInterestCharge.Value()) {
    // Withholding Tax
    if (mRecord_AccountClose.SupportsWithholdingTax) {
      C.numWithholdingTaxValue.Value(-widget.RoundCurrency(C.numAccruedInterest.Value() * (mRecord_AccountClose.WithholdingTaxRate / 100)));
    }

    // Balance
    netBalance += (C.numAccruedInterest.Value() + C.numWithholdingTaxValue.Value());
  }
  if (C.chkAccruedDefaultInterestCharge.Value()) netBalance += C.numAccruedDefaultInterest.Value();
  if (C.chkAccruedOtherInterestCharge.Value()) netBalance += C.numAccruedOtherInterest.Value();
  if (C.chkUnpostedDefaultFeesCharge.Value()) netBalance += C.numUnpostedDefaultFees.Value();
  if (C.chkUnpostedOverLimitFeesCharge.Value()) netBalance += C.numUnpostedOverLimitFees.Value();
  if (C.chkUnpostedFacilityFeesCharge.Value()) netBalance += C.numUnpostedFacilityFees.Value();
  if (C.chkUnpostedStandardTransactionsCharge.Value()) netBalance += C.numUnpostedStandardTransactions.Value();
  C.numBalanceNet.Value(netBalance);

  // Balance Due
  var balanceDue = netBalance;
  if (mRecord.AccountClassIsDeposit) {
    if (C.chkFeeChargeFee.Value()) balanceDue -= C.numFeeValue.Value();
    if (C.chkOther1Charge.Value()) balanceDue -= C.numOther1Value.Value();
    if (C.chkOther2Charge.Value()) balanceDue -= C.numOther2Value.Value();
  }
  else {
    balanceDue += C.numLossValue.Value();
    if (C.chkFeeChargeFee.Value()) balanceDue += C.numFeeValue.Value();
    if (C.chkOther1Charge.Value()) balanceDue += C.numOther1Value.Value();
    if (C.chkOther2Charge.Value()) balanceDue += C.numOther2Value.Value();
    if (C.chkResidualCreditResidual.Value()) balanceDue -= C.numResidualValue.Value();
  }

  // Adjusted Value
  var adjustmentValue = 0;
  if (setAdjustmentValue) {
    adjustmentValue = C.numBalanceDue.Value() - balanceDue;
    if (mRecord.AccountClassIsDeposit) adjustmentValue *= -1; // Reverse for Deposits
  }
  else {
    adjustmentValue = C.numAdjustmentValue.Value();
  }
  C.numAdjustmentValue.Value(adjustmentValue);

  // Finalise Balance Due
  if(mRecord.AccountClassIsDeposit) {
    balanceDue -= adjustmentValue;
  }
  else {
    balanceDue += adjustmentValue;
  }
  C.numBalanceDue.Value(balanceDue);

  // Update Buttons
  tabWizard_UpdateButtons();
}

function BalanceControlsUpdate() {
  // Accrued Interest
  if (C.chkAccruedInterestCharge.Value()) {
    if (C.numAccruedInterest.ValueIsBlank()) {
      // Interest
      if (C.numAccruedInterest.BlankTip()) {
        C.numAccruedInterest.Value(C.numAccruedInterest.BlankTip());
      }
      else {
        C.numAccruedInterest.Value(mRecord_AccountCloseInitial.AccruedInterest);
      }

      // Withholding Tax
      if (C.numWithholdingTaxValue.BlankTip()) {
        C.numWithholdingTaxValue.Value(C.numWithholdingTaxValue.BlankTip());
      }
      else {
        C.numWithholdingTaxValue.Value(mRecord_AccountCloseInitial.WithholdingTaxValue);
      }
    }
    C.numAccruedInterest.ReadOnly(mRecord_AccountClose.AccruedInterestReadOnly);
  }
  else {
    C.numWithholdingTaxValue.ValueIsBlank(true);
    C.numAccruedInterest.ReadOnly(true);
  }

  // Accrued Default Interest
  if (C.chkAccruedDefaultInterestCharge.Value()) {
    if (C.numAccruedDefaultInterest.ValueIsBlank()) {
      if (C.numAccruedDefaultInterest.BlankTip()) {
        C.numAccruedDefaultInterest.Value(C.numAccruedDefaultInterest.BlankTip());
      }
      else {
        C.numAccruedDefaultInterest.Value(mRecord_AccountCloseInitial.AccruedDefaultInterest);
      }      
    }
    C.numAccruedDefaultInterest.ReadOnly(mRecord_AccountClose.AccruedDefaultInterestReadOnly);
  }
  else {
    C.numAccruedDefaultInterest.ReadOnly(true);
  }

  // Accrued Other Interest
  if (C.chkAccruedOtherInterestCharge.Value()) {
    if (C.numAccruedOtherInterest.ValueIsBlank()) {
      if (C.numAccruedOtherInterest.BlankTip()) {
        C.numAccruedOtherInterest.Value(C.numAccruedOtherInterest.BlankTip());
      }
      else {
        C.numAccruedOtherInterest.Value(mRecord_AccountCloseInitial.AccruedOtherInterest);
      }      
    }
    C.numAccruedOtherInterest.ReadOnly(mRecord_AccountClose.AccruedOtherInterestReadOnly);
  }
  else {
    C.numAccruedOtherInterest.ReadOnly(true);
  }

  // Unposted Default Fees
  if (C.chkUnpostedDefaultFeesCharge.Value()) {
    if (C.numUnpostedDefaultFees.ValueIsBlank()) {
      if (C.numUnpostedDefaultFees.BlankTip()) {
        C.numUnpostedDefaultFees.Value(C.numUnpostedDefaultFees.BlankTip());
      }
      else {
        C.numUnpostedDefaultFees.Value(mRecord_AccountCloseInitial.UnpostedDefaultFees);
      }      
    }
    C.numUnpostedDefaultFees.ReadOnly(mRecord_AccountClose.UnpostedDefaultFeesReadOnly);
  }
  else {    
    C.numUnpostedDefaultFees.ReadOnly(true);
  }

  // Unposted Over Limit Fees
  if (C.chkUnpostedOverLimitFeesCharge.Value()) {
    if (C.numUnpostedOverLimitFees.ValueIsBlank()) {
      if (C.numUnpostedOverLimitFees.BlankTip()) {
        C.numUnpostedOverLimitFees.Value(C.numUnpostedOverLimitFees.BlankTip());
      }
      else {
        C.numUnpostedOverLimitFees.Value(mRecord_AccountCloseInitial.UnpostedOverLimitFees);
      }      
    }
    C.numUnpostedOverLimitFees.ReadOnly(mRecord_AccountClose.UnpostedOverLimitFeesReadOnly);
  }
  else {
    C.numUnpostedOverLimitFees.ReadOnly(true);
  }

  // Unposted Facility Fees
  if (C.chkUnpostedFacilityFeesCharge.Value()) {
    if (C.numUnpostedFacilityFees.ValueIsBlank()) {
      if (C.numUnpostedFacilityFees.BlankTip()) {
        C.numUnpostedFacilityFees.Value(C.numUnpostedFacilityFees.BlankTip());
      }
      else {
        C.numUnpostedFacilityFees.Value(mRecord_AccountCloseInitial.UnpostedFacilityFees);
      }      
    }
    C.numUnpostedFacilityFees.ReadOnly(mRecord_AccountClose.UnpostedFacilityFeesReadOnly);
  }
  else {
    C.numUnpostedFacilityFees.ReadOnly(true);
  }

  // Unposted Standard Transactions
  if (C.chkUnpostedStandardTransactionsCharge.Value()) {
    if (C.numUnpostedStandardTransactions.ValueIsBlank()) {
      if (C.numUnpostedStandardTransactions.BlankTip()) {
        C.numUnpostedStandardTransactions.Value(C.numUnpostedStandardTransactions.BlankTip());
      }
      else {
        C.numUnpostedStandardTransactions.Value(mRecord_AccountCloseInitial.UnpostedStandardTransactions);
      }      
    }
  }

  // Fee
  if (C.chkFeeChargeFee.Value()) {
    if (C.numFeeValue.ValueIsBlank()) {
      if (C.numFeeValue.BlankTip()) {
        C.numFeeValue.Value(C.numFeeValue.BlankTip());
      }
      else {
        C.numFeeValue.Value(mRecord_AccountCloseInitial.FeeValue);
      }      
    }
    C.numFeeValue.ReadOnly(mRecord_AccountClose.FeeValueReadOnly);
  }
  else {
    C.numFeeValue.ReadOnly(true);
  }

  // Other 1
  if (C.chkOther1Charge.Value()) {
    if (C.numOther1Value.ValueIsBlank()) {
      if (C.numOther1Value.BlankTip()) {
        C.numOther1Value.Value(C.numOther1Value.BlankTip());
      }
      else {
        C.numOther1Value.Value(mRecord_AccountCloseInitial.Other1Value);
      }      
    }
    C.numOther1Value.ReadOnly(mRecord_AccountClose.Other1ValueReadOnly);
  }
  else {
    C.numOther1Value.ReadOnly(true);
  }

  // Other 2
  if (C.chkOther2Charge.Value()) {
    if (C.numOther2Value.ValueIsBlank()) {
      if (C.numOther2Value.BlankTip()) {
        C.numOther2Value.Value(C.numOther2Value.BlankTip());
      }
      else {
        C.numOther2Value.Value(mRecord_AccountCloseInitial.Other2Value);
      }      
    }
    C.numOther2Value.ReadOnly(mRecord_AccountClose.Other2ValueReadOnly);
  }
  else {
    C.numOther2Value.ReadOnly(true);
  }

  // Residual
  if (C.chkResidualCreditResidual.Value()) {
    if (C.numResidualValue.ValueIsBlank()) {
      if (C.numResidualValue.BlankTip()) {
        C.numResidualValue.Value(C.numResidualValue.BlankTip());
      }
      else {
        C.numResidualValue.Value(mRecord_AccountCloseInitial.ResidualValue);
      }      
    }
    C.numResidualValue.ReadOnly(mRecord_AccountClose.ResidualValueReadOnly);
  }
  else {
    C.numResidualValue.ReadOnly(true);
  }

  // Enable Finish button if no Balance Payable
  tabWizard_UpdateButtons();
}

// ============
// numLossValue
// ============
function numLossValue_ButtonClick(source, e) {
  switch(e.id) {
    case "Info":
      widget.UI.MsgBoxInfo(mRecord_AccountClose.LossMessage);
  }
}

// ===========
// pageBalance
// ===========
function pageBalance_Refresh() {
  // Headings
  C.lblLossFeesAdjustments.Text(mRecord_AccountClose.FeesHeadingCaption);
  C.lblLossFeesAdjustments.Visible(mRecord_AccountClose.ShowFeesHeading);
  C.lblWithholdingTax.Text(mRecord_AccountClose.WithholdingTaxLabel);

  // Charges?
  C.chkAccruedInterestCharge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowAccruedInterest);
  C.chkAccruedDefaultInterestCharge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowAccruedDefaultInterest);
  C.chkAccruedOtherInterestCharge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowAccruedOtherInterest);
  C.chkUnpostedDefaultFeesCharge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowUnpostedDefaultFees);
  C.chkUnpostedOverLimitFeesCharge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowUnpostedOverLimitFees);
  C.chkUnpostedFacilityFeesCharge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowUnpostedFacilityFees);
  C.chkUnpostedStandardTransactionsCharge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowUnpostedStandardTransactionsCharge);
  C.chkFeeChargeFee.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowFeeValue);
  C.chkOther1Charge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowOther1);
  C.chkOther2Charge.Visible(mRecord.AllowUpdates &amp;&amp; mRecord_AccountClose.ShowOther2);

  // Charge Captions
  C.chkAccruedInterestCharge.Caption(mRecord_AccountClose.AccruedInterestChargeCaption);
  C.chkAccruedDefaultInterestCharge.Caption(mRecord_AccountClose.AccruedDefaultInterestChargeCaption);
  C.chkUnpostedDefaultFeesCharge.Caption(mRecord_AccountClose.UnpostedDefaultFeesChargeCaption);
  C.chkUnpostedOverLimitFeesCharge.Caption(mRecord_AccountClose.UnpostedOverLimitFeesChargeCaption);
  C.chkUnpostedFacilityFeesCharge.Caption(mRecord_AccountClose.UnpostedFacilityFeesChargeCaption);
  C.chkUnpostedStandardTransactionsCharge.Caption(mRecord_AccountClose.UnpostedStandardTransactionsChargeCaption);

  // Values
  C.numAccruedInterest.VisibleRow(mRecord_AccountClose.ShowAccruedInterest);
  C.numWithholdingTaxValue.VisibleRow(mRecord_AccountClose.ShowWithholdingTaxValue);
  C.numAccruedDefaultInterest.VisibleRow(mRecord_AccountClose.ShowAccruedDefaultInterest);
  C.numAccruedOtherInterest.VisibleRow(mRecord_AccountClose.ShowAccruedOtherInterest);
  C.numUnpostedDefaultFees.VisibleRow(mRecord_AccountClose.ShowUnpostedDefaultFees);
  C.numUnpostedOverLimitFees.VisibleRow(mRecord_AccountClose.ShowUnpostedOverLimitFees);
  C.numUnpostedFacilityFees.VisibleRow(mRecord_AccountClose.ShowUnpostedFacilityFees);
  C.numLossValue.VisibleRow(mRecord_AccountClose.ShowLossValue);
  C.numLossValue.Buttons().ButtonVisible("Info", mRecord_AccountClose.LossMessage.length != 0);
  C.numLossValue.ReadOnly(mRecord_AccountClose.LossValueReadOnly);
  C.numFeeValue.VisibleRow(mRecord_AccountClose.ShowFeeValue);
  C.numOther1Value.VisibleRow(mRecord_AccountClose.ShowOther1Value);
  C.numOther2Value.VisibleRow(mRecord_AccountClose.ShowOther2Value);
  C.numOther1Value.Caption(mRecord_AccountClose.Other1Caption);
  C.numOther2Value.Caption(mRecord_AccountClose.Other2Caption);

  // Override Adjustment
  if(mRecord_AccountClose.AdjustmentValue != 0) {
    C.numAdjustmentValue.Value(mRecord_AccountClose.AdjustmentValue);
  }

  if (mRecord_AccountClose.ShowResidualValue) {
    C.numResidualValue.VisibleRow(true);
    C.lblResidualCredit.VisibleRow(true);
    C.numResidualValue.ReadOnly(mRecord_AccountClose.ResidualValueReadOnly);
    C.chkResidualCreditResidual.Visible(mRecord_AccountClose.ShowResidualCreditResidual);
  }
  else {
    C.lblResidualCredit.VisibleRow(false);
    C.numResidualValue.VisibleRow(false);
  }

  if (C.cboCloseMethod.ListIndex() != -1) {
    switch(mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()].CloseMethod) {
      case "BadDebtWriteOff":
        C.numBalanceDue.Caption("BAD DEBT:");
        break;

      case "Cancelled":
        C.numBalanceDue.Caption("CANCELLED:");
        break;      

      case "Refinanced":
        C.numBalanceDue.Caption("REFINANCED:");
        break;

      case "Reinvested":
        C.numBalanceDue.Caption("REINVESTMENT:");
        break;

      case "WrittenOff":
        C.numBalanceDue.Caption("WRITTEN OFF:");
        break;
        
      case "Closed":
      case "EarlyRedemption":
      case "EarlySettlement":
        C.numBalanceDue.Caption("BALANCE DUE:");
        break;
    }
  }

  if (mRecord_AccountClose.LossError) {
    C.divAccountInformation.html(mRecord_AccountClose.LossError);
    C.divAccountInformation.show();
  }
  else {
    C.divAccountInformation.hide();
  }

  // Calculate Balances
  Balances_Calculate(false);

  // Other control states
  BalanceControlsUpdate();
}

// ==============
// pageReinvested
// ==============
function pageReinvested_Refresh() {
  // Controls
  C.numReinvestedValue.Value(C.numBalanceDue.Value());

  C.cboReinvestedOption.Text(mRecord_AccountClose.RefinanceOption);
  C.cboReinvestedProductType.Text(mRecord.ProductTypeId);
  C.cboReinvestedAccountType.Text(mRecord.AccountTypeId);

  // Reference &amp; Notes
  var closeMethod = mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()];
  if (closeMethod) {
    if (!C.txtReinvestedNotes.Text()) C.txtReinvestedNotes.Text(closeMethod.DefaultNotes);
    if (!C.txtReinvestedReference.Text()) C.txtReinvestedReference.Text(closeMethod.DefaultReference);
  }

  // Update Controls
  cboReinvestedOption_Change();
  cboReinvestedProductType_Change();
  cboReinvestedAccountType_Change();
}

// =========================
// apdPaymentDetailsIncoming
// =========================
function apdPaymentDetailsIncoming_Change(source, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  if (C.apdPaymentDetailsIncoming.PaymentMethodId()) {
    GetPaymentData();
  }
}

// =========================
// apdPaymentDetailsOutgoing
// =========================
function apdPaymentDetailsOutgoing_Change(source, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  if (C.apdPaymentDetailsOutgoing.PaymentMethodId()) {
    GetPaymentData();
  }
}

// =========================
// cboPaymentTransactionType
// =========================
function cboPaymentTransactionType_Change(source, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  if (C.cboPaymentTransactionType.Text()) {
    var params = { TransactionTypeId: C.cboPaymentTransactionType.Text() }

    widget.GetString("Form_TransactionType_Change", params,
      function (data) {
        if (data) {
          // Parse
          var o = JSON.parse(data);

          C.txtPaymentReference.Text(o.TransactionReference);
          C.txtPaymentNotes.Text(o.TransactionNotes);
          C.chkPrintSummary.Value(o.PrintSummaryDefault &amp;&amp; mRecord_AccountClose.CanPrintSummary);
        }
      },
      function () {
        widget.UI.MsgBoxAlert(JSON.stringify(data));
      }
    );
  }
}

// ===================
// cboReinvestedOption
// ===================
function cboReinvestedOption_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Hide Controls
  C.cboReinvestedProductType.VisibleRow(false);
  C.cboReinvestedAccountType.VisibleRow(false);
  C.cboReinvestedAccountTypePromotion.VisibleRow(false);
  C.cboReinvestedToAccount.VisibleRow(false);  

  // Update
  var ReinvestedOption = C.cboReinvestedOption.ListIndex() == -1 ? "" : mRecord.RefinanceOptionList[C.cboReinvestedOption.ListIndex()].Code;
  switch (ReinvestedOption) {
    case "NewAccount":
      C.cboReinvestedProductType.VisibleRow(true);
      C.cboReinvestedAccountType.VisibleRow(true);
      C.cboReinvestedAccountTypePromotion.VisibleRow(true);
      break;

    case "ExistingAccount":
      C.cboReinvestedToAccount.VisibleRow(true);
      break;
  }
}

// ========================
// cboReinvestedProductType
// ========================
function cboReinvestedProductType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Reset Account Type &amp; Promotion
  if (e) {
    C.cboReinvestedAccountType.Text("");
    C.cboReinvestedAccountTypePromotion.Text("");
  }

  // Update Account Type List
  if (mRecord &amp;&amp; C.cboReinvestedProductType.Text()) {
    var list = [];
    for (var i = 0; i &lt; mRecord.AccountTypes.length; i++) {
      var item = mRecord.AccountTypes[i];

      if (item.ProductTypeId == C.cboReinvestedProductType.Text()) {
        var o = {
          AccountTypeId: item.AccountTypeId,
          Description: item.Description,
        };
        list.push(o);
      }
    }

    // Update List
    C.cboReinvestedAccountType.RefreshFromCollection(list, "AccountTypeId", "Description");
  }
}

// ==================
// cboRefinanceOption
// ==================
function cboRefinanceOption_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Hide Controls
  C.cboRefinanceProductType.VisibleRow(false);
  C.cboRefinanceAccountType.VisibleRow(false);
  C.cboRefinanceAccountTypePromotion.VisibleRow(false);
  C.cboRefinanceToAccount.VisibleRow(false);  

  // Update
  var RefinanceOption = C.cboRefinanceOption.ListIndex() == -1 ? "" : mRecord.RefinanceOptionList[C.cboRefinanceOption.ListIndex()].Code;
  switch (RefinanceOption) {
    case "NewAccount":
      C.cboRefinanceProductType.VisibleRow(true);
      C.cboRefinanceAccountType.VisibleRow(true);
      C.cboRefinanceAccountTypePromotion.VisibleRow(true);
      break;

    case "ExistingAccount":
      C.cboRefinanceToAccount.VisibleRow(true);
      break;
  }
  
  // Update Summary
  if (e) {
    wbRefinanceSummary_Refresh();
  }
  
  // Update Buttons
  tabWizard_UpdateButtons();
}

// =======================
// cboRefinanceProductType
// =======================
function cboRefinanceProductType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Reset Account Type &amp; Promotion
  if (e) {
    C.cboRefinanceAccountType.Text("");
    C.cboRefinanceAccountTypePromotion.Text("");
  }

  // Update Account Type List
  if (mRecord &amp;&amp; C.cboRefinanceProductType.Text()) {
    var list = [];
    for (var i = 0; i &lt; mRecord.AccountTypes.length; i++) {
      var item = mRecord.AccountTypes[i];

      if (item.ProductTypeId == C.cboRefinanceProductType.Text() &amp;&amp; item.OptionAllowRefinanceInto) {
        var o = {
          AccountTypeId: item.AccountTypeId,
          Description: item.Description,
        };
        list.push(o);
      }
    }

    // Update List
    C.cboRefinanceAccountType.RefreshFromCollection(list, "AccountTypeId", "Description");
  }
  
  // Refresh Promotions
  cboRefinanceAccountType_Change();
  
  // Update Summary
  if (e) {
    wbRefinanceSummary_Refresh();
  }
}

// ==========================
// cboRefinanceSecurityStmtId
// ==========================
function cboRefinanceSecurityStmtId_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Captions
  if (mSecurityStmtInformation) {
    if (C.cboRefinanceSecurityStmtId.Text() == mSecurityStmtInformation.SecurityStmtAId) {
      C.chkRefinanceSecurityItemsCopy.Caption("Copy Security Items from Security Statement '" + mSecurityStmtInformation.SecurityStmtBId + "' to Security Statement '" + mSecurityStmtInformation.SecurityStmtAId + "'?");
      C.chkRefinanceSecurityStmtDischarge.Caption("Discharge Security Statement '" + mSecurityStmtInformation.SecurityStmtBId + "'?");
    }
    else {
      C.chkRefinanceSecurityItemsCopy.Caption("Copy Security Items from Security Statement '" + mSecurityStmtInformation.SecurityStmtAId + "' to Security Statement '" + mSecurityStmtInformation.SecurityStmtBId + "'?");
      C.chkRefinanceSecurityStmtDischarge.Caption("Discharge Security Statement '" + mSecurityStmtInformation.SecurityStmtAId + "'?");
    }
  }
  
  // Refresh Security Summary
  RefreshSecuritySummary();
}

// =====================
// cboRefinanceToAccount
// =====================
function cboRefinanceToAccount_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Clear existing Security Information
  mSecurityStmtInformation = null;

  // Delayed refresh (500ms)
  if (mRefreshTimerRefinanceToAccount) {
    window.clearTimeout(mRefreshTimerRefinanceToAccount);
    mRefreshTimerRefinanceToAccount = null;
  }
  mRefreshTimerRefinanceToAccount = window.setTimeout(cboRefinanceToAccount_Change_Post, 500);
}

function cboRefinanceToAccount_Change_Post() {
  // Check selected Accounts Security Statements - this determines if there is an additional page to the wizard
  if (mRecord.AddonSecurityRegister &amp;&amp; C.cboRefinanceToAccount.Text()) {
    GetSecurityStmtInformation();
  }
  else if (e) {        
    // Refresh Summary
    wbRefinanceSummary_Refresh();
    
    // Update Buttons
    tabWizard_UpdateButtons();
  }
}

// ==================================
// Get Security Statement Information
// ==================================
function GetSecurityStmtInformation() {
  // Block UI
  widget.UI.Block("Getting Security Information, please wait...");
  
  // Clear existing Security Information
  mSecurityStmtInformation = null;
  
  // Params
  var params = {
    refinanceToAccountId: C.cboRefinanceToAccount.Text()
  }
  
  // Get Information
  widget.GetString("GetSecurityStmtInformation", params, 
    function(data) {
      // Parse
      if (data) mSecurityStmtInformation = JSON.parse(data);
      
      // Refresh Summary
      wbRefinanceSummary_Refresh();
      
      // Update Buttons
      tabWizard_UpdateButtons();
      
      // Unblock
      widget.UI.Unblock();
    }, 
    
    function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();
      
      // Error Message
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );
}

// =======================
// cboRefinanceAccountType
// =======================
function cboRefinanceAccountType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  var promotionValid = false;  

  // Reset Promotion
  if (e) {
    C.cboRefinanceAccountTypePromotion.Text("");
    C.cboRefinanceAccountTypePromotion.VisibleRow(false);
  }

  // Get Account Type
  var accountType = null;
  if (C.cboRefinanceAccountType.Text()) {
    for (var i = 0; i &lt; mRecord.AccountTypes.length; i++) {
      if (mRecord.AccountTypes[i].AccountTypeId == C.cboRefinanceAccountType.Text()) {
        accountType = mRecord.AccountTypes[i];
        break;
      }
    }
  }

  // Set Promotions
  if (accountType) {
    if (accountType.PromotionShow) {
      promotionValid = true;
      C.cboRefinanceAccountTypePromotion.RefreshFromCollection(accountType.Promotions, "PromotionId", "Description", "PromotionId,Description,DateStart,DateStop");
      C.cboRefinanceAccountTypePromotion.AllowBlank(accountType.PromotionAllowBlank);
      C.cboRefinanceAccountTypePromotion.VisibleRow(true);
    }
  }

  // Clear
  if (!promotionValid) {
    C.cboRefinanceAccountTypePromotion.Text("");
    C.cboRefinanceAccountTypePromotion.VisibleRow(false);
  }
  
  // Update Summary
  if (e) {
    wbRefinanceSummary_Refresh();
  }
}

// ================================
// cboRefinanceAccountTypePromotion
// ================================
function cboRefinanceAccountTypePromotion_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Summary
  wbRefinanceSummary_Refresh();
}

// ========================
// cboReinvestedAccountType
// ========================
function cboReinvestedAccountType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  var promotionValid = false;  

  // Reset Promotion
  if (e) {
    C.cboReinvestedAccountTypePromotion.Text("");
    C.cboReinvestedAccountTypePromotion.VisibleRow(false);
  }

  // Get Account Type
  var accountType = null;
  if (C.cboReinvestedAccountType.Text()) {
    for (var i = 0; i &lt; mRecord.AccountTypes.length; i++) {
      if (mRecord.AccountTypes[i].AccountTypeId == C.cboReinvestedAccountType.Text()) {
        accountType = mRecord.AccountTypes[i];
        break;
      }
    }
  }

  // Set Promotions
  if (accountType) {
    if (accountType.PromotionShow) {
      promotionValid = true;
      C.cboReinvestedAccountTypePromotion.RefreshFromCollection(accountType.Promotions, "PromotionId", "Description", "PromotionId,Description,DateStart,DateStop");
      C.cboReinvestedAccountTypePromotion.AllowBlank(accountType.PromotionAllowBlank);
      C.cboReinvestedAccountTypePromotion.VisibleRow(true);
    }
  }

  // Clear
  if (!promotionValid) {
    C.cboReinvestedAccountTypePromotion.Text("");
    C.cboReinvestedAccountTypePromotion.VisibleRow(false);
  }
}

// =============
// chkPaymentFee
// =============
function chkPaymentFee_Change(source, e) {
  PaymentControlsUpdate();
}

// =============
// numPaymentFee
// =============
function numPaymentFee_Change(source, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  PaymentControlsUpdate();
}

// ==========================
// Get Payment Method details
// ==========================
function GetPaymentData() {
  var params = CreateFinishParameters();

  widget.GetString("Form_PaymentMethod_Change", params,
    function (data) {
      if (data) {
        // Parse
        mRecord_PaymentData = JSON.parse(data);

        // Defaults
        C.chkPaymentFee.Value(mRecord_PaymentData.PaymentFeeCharge);

        PaymentControlsUpdate();
      }
    },
    function () {
      widget.UI.MsgBoxAlert(JSON.stringify(data));
    }
  );
}

// ===========
// pagePayment
// ===========
function pagePayment_Refresh() {
  C.numPaymentValue.Value(C.numBalanceDue.Value());

  C.cboPaymentTransactionType.RefreshFromStandardRange("TransactionTypes", mRecord_PaymentData.TransactionTypeFilter);

  if (mRecord.AccountClassIsDeposit) {
    // Deposits
    switch(mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()].CloseMethod) {
      case "Closed":
      case "EarlyRedemption":
        if (C.numBalanceDue.Value() &lt; 0) {
          C.lblPayment.Text("Please confirm the Payment value");
          C.numPaymentValue.Caption("AMOUNT DUE:");
          C.lblPaymentWithdrawalMethod.Text("Enter the Payment method and Banking details");
          C.apdPaymentDetailsIncoming.Visible(true);
          C.apdPaymentDetailsOutgoing.Visible(false);
        }
        else {
          C.lblPayment.Text("Please confirm the Redemption value");
          C.numPaymentValue.Caption("AMOUNT DUE:");
          C.lblPaymentWithdrawalMethod.Text("Enter the Withdrawal method and Banking details");
          C.apdPaymentDetailsIncoming.Visible(false);
          C.apdPaymentDetailsOutgoing.Visible(true);
        }
        break;
    }
  }
  else {
    // Loans/ Disbursements
    switch(mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()].CloseMethod) {
      case "Closed":
      case "EarlySettlement":
        if (C.numBalanceDue.Value() &lt; 0) {
          C.lblPayment.Text("Please confirm the Refund value");
          C.numPaymentValue.Caption("REFUND DUE");
          C.lblPaymentWithdrawalMethod.Text("Enter the REFUND method and Banking details");
          C.apdPaymentDetailsIncoming.Visible(false);
          C.apdPaymentDetailsOutgoing.Visible(true);
        }
        else {
          C.lblPayment.Text("Please confirm the Payment value");
          C.numPaymentValue.Caption("PAYMENT DUE");
          C.lblPaymentWithdrawalMethod.Text("Enter the Payment method and Banking details");
          C.apdPaymentDetailsIncoming.Visible(true);
          C.apdPaymentDetailsOutgoing.Visible(false);
        }
    }
  }

  // Other controls
  PaymentControlsUpdate();
}

function PaymentControlsUpdate() {
  // Update Payment controls
  if (mRecord_PaymentData.ShowPaymentFeeInfo) {
    if (C.chkPaymentFee.Value()) {
      C.numPaymentFee.Value(mRecord_PaymentData.PaymentFeeValue);
      C.numPaymentFee.ReadOnly(mRecord_PaymentData.PaymentFeeReadOnly);
      C.numNetPayment.Value(mRecord_AccountClose.BalanceDue + mRecord_PaymentData.PaymentFeeValue);
    }
    else {
      C.numPaymentFee.BlankTip(widget.FormatCurrency(mRecord_PaymentData.PaymentFeeValue, false));
      C.numPaymentFee.ValueIsBlank(true);
      C.numPaymentFee.ReadOnly(true);
      C.numNetPayment.Value(mRecord_AccountClose.BalanceDue);
    }
    C.numPaymentFee.VisibleRow(true);
    C.numNetPayment.VisibleRow(true);
  }
  else {
    C.numPaymentFee.VisibleRow(false);
    C.numNetPayment.VisibleRow(false);
  }
  
  // Reference &amp; Notes
  var closeMethod = mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()];
  if (closeMethod) {
    if (!C.txtPaymentNotes.Text()) C.txtPaymentNotes.Text(closeMethod.DefaultNotes);
    if (!C.txtPaymentReference.Text()) C.txtPaymentReference.Text(closeMethod.DefaultReference);
  }
}

// ============
// pageWriteOff
// ============
function pageWriteOff_Refresh() {
  C.numWriteOffValue.Value(C.numBalanceDue.Value());

  // Reference &amp; Notes
  var closeMethod = mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()];
  if (closeMethod) {
    if (!C.txtWriteOffNotes.Text()) C.txtWriteOffNotes.Text(closeMethod.DefaultNotes);
    if (!C.txtWriteOffReference.Text()) C.txtWriteOffReference.Text(closeMethod.DefaultReference);
  }

  // Other
  if (C.cboCloseMethod.ListIndex() != -1) {
    switch(mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()].CloseMethod) {
      case "BadDebtWriteOff":
        C.lblConfirmationWriteOff.Text("Please confirm the value to write off as a Bad Debt");
        C.numWriteOffValue.Caption("BAD DEBT:");
        break;

      case "Cancelled":
        C.lblConfirmationWriteOff.Text("Please confirm the value to write off as Cancelled");
        C.numWriteOffValue.Caption("CANCELLED:");
        break;
    }
  }
}

// =============
// pageRefinance
// =============
function pageRefinance_Refresh() {
  // Controls
  C.numRefinanceValue.Value(C.numBalanceDue.Value());
  
  C.cboRefinanceOption.Text(mRecord_AccountClose.RefinanceOption);
  C.cboRefinanceProductType.Text(mRecord.ProductTypeId);
  C.cboRefinanceAccountType.Text(mRecord.AccountTypeId);
  
  // Reference &amp; Notes
  var closeMethod = mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()];
  if (closeMethod) {
    if (!C.txtRefinanceNotes.Text()) C.txtRefinanceNotes.Text(closeMethod.DefaultNotes);
    if (!C.txtRefinanceReference.Text()) C.txtRefinanceReference.Text(closeMethod.DefaultReference);
  }
  
  // Update Controls
  cboRefinanceOption_Change();
  cboRefinanceProductType_Change();
  
  // Update Summary
  wbRefinanceSummary_Refresh();
}

// ============
// pageSecurity
// ============
function pageSecurity_Refresh() {
  // Block UI
  widget.UI.Block("Initialising, please wait...");

  // Reset
  C.lblSecurityStmts.VisibleRow(false);  
  C.cboSecurityStatementA.VisibleRow(false);
  C.cboSecurityStatementB.VisibleRow(false);
  C.cboSecurityStatementA.RefreshUnbound("", "");
  C.cboSecurityStatementB.RefreshUnbound("", "");
  C.lblSecurityOptions.VisibleRow(false);
  C.cboRefinanceSecurityStmtId.VisibleRow(false);
  C.chkRefinanceSecurityItemsCopy.VisibleRow(false);
  C.chkRefinanceSecurityStmtDischarge.VisibleRow(false);

  // Display full Security Statement information?
  if (mRecord.SecurityFullDetails &amp;&amp; mSecurityStmtInformation) {
    // Update Controls
    C.lblSecurityStmts.VisibleRow(true);    
  
    C.cboSecurityStatementA.Caption("Account " + mRecord.RecordId + ":");
    C.cboSecurityStatementB.Caption("Account " + C.cboRefinanceToAccount.Text() + ":");  
    
    C.cboSecurityStatementA.VisibleRow(true);
    C.cboSecurityStatementB.VisibleRow(true);
  
    // Update Security Statement A
    if (mSecurityStmtInformation.HasSecurityStmtA) {    
      C.cboSecurityStatementA.RefreshUnbound(mSecurityStmtInformation.SecurityStmtAId, mSecurityStmtInformation.SecurityStmtADescription + " (Status: " + mSecurityStmtInformation.SecurityStmtARegisterStatusText + ")");
    }    
    
    // Update Security Statement B
    if (mSecurityStmtInformation.HasSecurityStmtB) {    
      C.cboSecurityStatementB.RefreshUnbound(mSecurityStmtInformation.SecurityStmtBId, mSecurityStmtInformation.SecurityStmtBDescription + " (Status: " + mSecurityStmtInformation.SecurityStmtBRegisterStatusText + ")");
    }    
    
    // Both Security Statements present
    if (mSecurityStmtInformation.HasSecurityStmtA &amp;&amp; mSecurityStmtInformation.HasSecurityStmtB) {
      C.lblSecurityOptions.VisibleRow(true);
      
      if (mSecurityStmtInformation.SecurityStmtAIsRegistered &amp;&amp; mSecurityStmtInformation.SecurityStmtBIsRegistered) {
        // Both Statements are Registered
        C.cboRefinanceSecurityStmtId.ListFromCsvString(mSecurityStmtInformation.SecurityStmtList);
        
        C.cboRefinanceSecurityStmtId.VisibleRow(true);
        C.chkRefinanceSecurityItemsCopy.VisibleRow(true);
        C.chkRefinanceSecurityStmtDischarge.VisibleRow(true);
      }
      else if (mSecurityStmtInformation.SecurityStmtAIsRegistered &amp;&amp; !mSecurityStmtInformation.SecurityStmtBIsRegistered) {
        // Statement A is registered, Statement B is not
        C.chkRefinanceSecurityItemsCopy.Caption("Copy Security Items from Security Statement '" + mSecurityStmtInformation.SecurityStmtBId + "' to Registered Security Statement '" + mSecurityStmtInformation.SecurityStmtAId + "'?");
        C.chkRefinanceSecurityItemsCopy.VisibleRow(true);
      }
      else if (!mSecurityStmtInformation.SecurityStmtAIsRegistered &amp;&amp; mSecurityStmtInformation.SecurityStmtBIsRegistered) {
        // Statement B is registered, Statement A is not
        C.chkRefinanceSecurityItemsCopy.Caption("Copy Security Items from Security Statement '" + mSecurityStmtInformation.SecurityStmtAId + "' to Registered Security Statement '" + mSecurityStmtInformation.SecurityStmtBId + "'?");
        C.chkRefinanceSecurityItemsCopy.VisibleRow(true);
      }
      else if (mSecurityStmtInformation.SecurityStmtAIsNew) {
        // Statement A is New
        C.chkRefinanceSecurityItemsCopy.Caption("Copy Security Items from Security Statement '" + mSecurityStmtInformation.SecurityStmtAId + "' to Registered Security Statement '" + mSecurityStmtInformation.SecurityStmtBId + "'?");
        C.chkRefinanceSecurityItemsCopy.VisibleRow(true);
      }
    }
  }  
  
  // Update Controls
  cboRefinanceSecurityStmtId_Change();
  
  // Refresh Summary
  RefreshSecuritySummary();
}

// ===================================
// Get an updated Account Close object
// ===================================
function GetAccountClose() {
  widget.GetString("GetAccountClose", CreateFinishParameters(),
    function (data) {
      // Parse
      mRecord_AccountClose = JSON.parse(data);
      mRecord_SummaryItems = mRecord_AccountClose.SummaryItems;
      mRecord_PaymentData = mRecord_AccountClose.PaymentData;

      // Load Fields
      Fields_Load();

      // Update Control values

      // Refresh pages
      pageGeneral_Refresh();
      pageBalance_Refresh();
      pageWriteOff_Refresh();
      pageRefinance_Refresh();
      pagePayment_Refresh();
      pageSecurity_Refresh();

      // Other Controls
      gridSummaryItems_Refresh();
      Balances_Calculate(false);
    },
    function (data) {
      widget.UI.MsgBoxAlert(JSON.stringify(data));
    }
  );
}

// =====================
// Initial Account Close
// =====================
function GetInitialAccountClose() {
  // Create Parameters
  var params = {
    CloseDate: C.dateClose.Value(),
    CloseMethodText: C.cboCloseMethod.Text(),
    FuturePaymentsShow: C.chkFuturePaymentsShow.Value(),
    CloseNote: C.cboCloseNote.Text(),
  }

  // Delayed refresh
  if (mRefreshTimerInitialAccountClose) {
    window.clearTimeout(mRefreshTimerInitialAccountClose);
    mRefreshTimerInitialAccountClose = null;
  }

  // Refresh after 500ms
  mRefreshTimerInitialAccountClose = window.setTimeout(function () {
    // Initialise
    var originalCloseMethod = mRecord_AccountClose.CloseMethodText;

    // Fetch
    widget.GetString("GetInitialAccountClose", params,
      function (data) {
        if (data) {
          // Parse
          mRecord_AccountClose = JSON.parse(data);
          mRecord_AccountCloseInitial = mRecord_AccountClose;
          mRecord_SummaryItems = mRecord_AccountClose.SummaryItems;
          mRecord_PaymentData = mRecord_AccountClose.PaymentData;

          // Load Fields
          Fields_Load();

          // Defaults
          if (originalCloseMethod != C.cboCloseMethod.Text()) {
            // Only if Close Method has changed
            C.cboCloseNote.Text(mRecord_AccountClose.CloseNoteDefault);
          }
        }
      },
      function (data) {
        widget.UI.MsgBoxAlert(JSON.stringify(data));
      }
    );
  }, 500);
}

// =================
// Finish Parameters
// =================
function CreateFinishParameters() {
  // Initialise
  var closeMethod = mRecord.CloseMethodsData[C.cboCloseMethod.ListIndex()].CloseMethod;
  var params = {
    // General
    CloseDate: C.dateClose.Value(),
    FuturePaymentsShow: C.chkFuturePaymentsShow.Value(),
    CloseMethodText: C.cboCloseMethod.Text(),
    ClosePending: C.chkClosePending.Value(),
    ClosePendingReviewDate: C.dateClosePendingReview.Value(),
    CloseNote: C.cboCloseNote.Text(),
    PrintSummary: (mRecord_AccountClose.CanPrintSummary &amp;&amp; C.chkPrintSummary.Value()),

    // Summary Items
    SummaryItems: mRecord_SummaryItems,

    // Balances
    AccruedDefaultInterestCharge: C.chkAccruedDefaultInterestCharge.Value(),
    AccruedInterestCharge: C.chkAccruedInterestCharge.Value(),
    AccruedOtherInterestCharge: C.chkAccruedOtherInterestCharge.Value(),
    FeeChargeFee: C.chkFeeChargeFee.Value(),
    Other1Charge: C.chkOther1Charge.Value(),
    Other2Charge: C.chkOther2Charge.Value(),
    ResidualCreditResidual: C.chkResidualCreditResidual.Value(),
    UnpostedDefaultFeesCharge: C.chkUnpostedDefaultFeesCharge.Value(),
    UnpostedOverLimitFeesCharge: C.chkUnpostedOverLimitFeesCharge.Value(),
    UnpostedFacilityFeesCharge: C.chkUnpostedFacilityFeesCharge.Value(),
    UnpostedStandardTransactionsCharge: C.chkUnpostedStandardTransactionsCharge.Value(),

    AccruedDefaultInterest: C.numAccruedDefaultInterest.Value(),
    AccruedInterest: C.numAccruedInterest.Value(),
    AccruedOtherInterest : C.numAccruedOtherInterest.Value(),
    AdjustmentValue : C.numAdjustmentValue.Value(),
    BalanceCurrent : C.numBalanceCurrent.Value(),
    BalanceDue : C.numBalanceDue.Value(),
    BalanceNet : C.numBalanceNet.Value(),
    FeeValue : C.numFeeValue.Value(),
    LossValue : C.numLossValue.Value(),
    Other1Value : C.numOther1Value.Value(),
    Other2Value : C.numOther2Value.Value(),
    ResidualValue : C.numResidualValue.Value(),
    TotalCredits : C.numTotalCredits.Value(),
    UnpostedDefaultFees : C.numUnpostedDefaultFees.Value(),
    UnpostedOverLimitFees : C.numUnpostedOverLimitFees.Value(),
    UnpostedFacilityFees : C.numUnpostedFacilityFees.Value(),
    UnpostedStandardTransactions : C.numUnpostedStandardTransactions.Value(),
  };

  switch(closeMethod) {
    case "BadDebtWriteOff":
    case "Cancelled":
    case "WrittenOff":
      // Write Off
      params.TransactionReference = C.txtWriteOffReference.Text();
      params.TransactionNotes = C.txtWriteOffNotes.Text();
      break;

    case "Refinanced":
      // Refinanced
      params.TransactionReference = C.txtRefinanceReference.Text();
      params.TransactionNotes = C.txtRefinanceNotes.Text();            

      var RefinancedOption = C.cboRefinanceOption.ListIndex() == -1 ? "" : mRecord.RefinanceOptionList[C.cboRefinanceOption.ListIndex()].Code;
      params.RefinancedOption = RefinancedOption;
      switch (RefinancedOption) {
        case "NewAccount":
          params.RefinancedProductTypeId = C.cboRefinanceProductType.Text();
          params.RefinancedAccountTypeId = C.cboRefinanceAccountType.Text();
          params.RefinancedAccountTypePromotionId = C.cboRefinanceAccountTypePromotion.Text();
          break;

        case "ExistingAccount":
          params.RefinancedToAccountId = C.cboRefinanceToAccount.Text();
          params.RefinanceIntoMainSecurityStmtIsFromRefinancedAccountSecurityStmtId = C.cboRefinanceSecurityStmtId.Text();
          params.RefinanceIntoCopySecurityStmtItems = C.chkRefinanceSecurityItemsCopy.Value();
          params.RefinanceIntoDischargeSecurityStmt = C.chkRefinanceSecurityStmtDischarge.Value();
          break;
      }
      break;

    case "Reinvested":
      // Reinvested
      params.TransactionReference = C.txtReinvestedReference.Text();
      params.TransactionNotes = C.txtReinvestedNotes.Text();      

      var ReinvestedOption = C.cboReinvestedOption.ListIndex() == -1 ? "" : mRecord.RefinanceOptionList[C.cboReinvestedOption.ListIndex()].Code;
      params.ReinvestedOption = ReinvestedOption;
      switch (ReinvestedOption) {
        case "NewAccount":
          params.ReinvestedProductTypeId = C.cboReinvestedProductType.Text();
          params.ReinvestedAccountTypeId = C.cboReinvestedAccountType.Text();
          params.ReinvestedAccountTypePromotionId = C.cboReinvestedAccountTypePromotion.Text();
          break;

        case "ExistingAccount":
          params.ReinvestedToAccountId = C.cboReinvestedToAccount.Text();
          break;
      }
      break;

    case "Closed":
    case "EarlyRedemption":
    case "EarlySettlement":
      // Payment
      params.TransactionTypeId = C.cboPaymentTransactionType.Text();
      params.TransactionReference = C.txtPaymentReference.Text();
      params.TransactionNotes = C.txtPaymentNotes.Text();
      params.PaymentFee = C.numPaymentFee.Value();
      params.PaymentFeeCharge = C.chkPaymentFee.Value();
      if (C.apdPaymentDetailsIncoming.Visible()) {
        params.BankingDetailsIncomingJson = C.apdPaymentDetailsIncoming.ToBankingDetailsJson();
        params.CashRegisterId = C.apdPaymentDetailsIncoming.CashRegisterId();
      }
      if (C.apdPaymentDetailsOutgoing.Visible()) {
        params.BankingDetailsOutgoingJson = C.apdPaymentDetailsOutgoing.ToBankingDetailsJson();
        params.CashRegisterId = C.apdPaymentDetailsOutgoing.CashRegisterId();
      }
      break;
  }

  return params;
}

// =====================
// Show Account Schedule
// =====================
function ShowSchedule() {
  // Create Parameters
  var params = CreateFinishParameters();

  // Get Schedule
  widget.GetString("GetAccountSchedule", params,
    function(data) {
      // Show Schedule
      widget.UI.Forms.ShowAccountSchedule({scheduleJson: data, gotoWhatIf: true, headingSummary: "Account Close - " + C.cboCloseMethod.Text() });
    },

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

// =========================
// Update Permission Warning
// =========================
function UpdatePermissionsWarning() {
  var message = "";
  if (mRecord.CanClose &amp;&amp; mRecord.CanClosePending) {
    // Do nothing
  }
  else {
    if (C.chkClosePending.Value() &amp;&amp; !mRecord.CanClosePending) {
      message = "You do not have Permission to update the status of this Account to &lt;b&gt;Closed (Pending)&lt;/b&gt;."
    }
    else if (!C.chkClosePending.Value() &amp;&amp; !mRecord.CanClose) {
      message = "You do not have Permission to &lt;b&gt;Close&lt;/b&gt; this Account."
    }
  }  
  
  // Warnings are required - update message and display
  if (message &amp;&amp; message.length &gt; 0) {
    C.trPermissionWarning.show();
    C.divPermissionWarning.html(message + "&lt;/br&gt;&lt;/br&gt;You may still use this wizard, but you will not be able to finish the process.");
    C.divPermissionWarning.show();
  }
  else {
    C.trPermissionWarning.hide();
    C.divPermissionWarning.hide();
  }
}

// ==================
// wbRefinanceSummary
// ==================
function wbRefinanceSummary_Refresh() {
  // Params
  var params = CreateFinishParameters();
  
  // Get Summary
  widget.GetString("GetRefinanceSummary", params, 
    function(data) {
      C.wbRefinanceSummary.SetContent(data, false);
    }, 
    
    function(errorMessage) {
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );
}

// ===========================================
// Refresh Security Summary (with small delay)
// ===========================================
function RefreshSecuritySummary(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Refresh
  if (e) {
    // Delayed refresh (500ms)
    if (mRefreshTimerSecuritySummary) {
      window.clearTimeout(mRefreshTimerSecuritySummary);
      mRefreshTimerSecuritySummary = null;
    }
    mRefreshTimerSecuritySummary = window.setTimeout(wbSecuritySummary_Refresh, 500);
  }
  else {
    wbSecuritySummary_Refresh();
  }
}

// =================
// wbSecuritySummary
// =================
function wbSecuritySummary_Refresh() {
  // Params
  var params = CreateFinishParameters();
  
  // Get Summary
  widget.GetString("GetSecuritySummary", params, 
    function(data) {
      C.wbSecuritySummary.SetContent(data, false);
      
      // Unblock
      widget.UI.Unblock();
    }, 
    
    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();
      
      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>WVLDbaRpx02-ZZ7LQn3Ojg</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1024</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</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>If you do not specify a Default Transaction Type, the Transaction Type selection will be shown regardless of the settings specified below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="EmailAllowMainClient" type="Boolean">
            <BlankTip />
            <Caption>Allow Emailing to Main Account Client?</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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="EmailAllowBroker" type="Boolean">
            <BlankTip />
            <Caption>Allow Emailing to Broker?</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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="EmailAllowDealer" type="Boolean">
            <BlankTip />
            <Caption>Allow Emailing to Dealer?</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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="EmailAllowOtherClients" type="Boolean">
            <BlankTip />
            <Caption>Allow Emailing to Other Account Clients?</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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ReadOnly" 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="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</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="CloseDate" type="Date">
            <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>
            <IncludeTime>false</IncludeTime>
            <MaxValue />
            <MinValue />
          </Parameter>
          <Parameter name="CloseMethod" 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>NotClosed,Closed,EarlySettlement,WrittenOff,BadDebtWriteOff,Refinanced,Matured,Reinvested,EarlyRedemption,Cancelled</List>
            <LimitToList>false</LimitToList>
            <MaxLength>25</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ChargeAndWriteOff" 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="WriteOff" 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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>