<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-02T02:16:45.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-07-19T23:23:02.1100000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-02T02:16:03.1600000</UpdatedUtcDate>
    <ScriptId>WITHDRAWAL</ScriptId>
    <Description>Account Withdrawal</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountWithdrawal
Option Explicit On
Option Strict On

' #################################################################
' Account Withdrawal wizard HTML Widget
'
' Version: 1.15 (02/08/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.09  28/07/2021  ISS                Updated
'    1.10  13/01/2022  ISS      J028131   Fixed incorrect validation
'    1.11  29/03/2022  ISS      J028163   Added Payment Arrangement option "3. Adjust Regular Payment to maintain current Maturity Date?"
'          19/04/2022  ISS      J028261   Added Allocation functionality
'    1.12  15/09/2022  ISS      J029356   Added ExecuteCommit Warning
'    1.13  22/12/2022  ISS      J029509   New Transaction Type Permission Keys
'          27/01/2023  ISS      J030146   Updated Initialise Parameters for AccountOutgoingPaymentDetails control
'    1.14  04/09/2023  ISS      J031864   Added Permission Key to exclude "None" Disbursement Payee Type
'                               J031952   Disbursement Payee Type not set to Limit to List.
'    1.15  02/08/2024  ISS      J032833   Summary page is now refreshed when the fee value is changed
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountWithdrawal"

' Common Parameters
Private mAccountId As String
Private mIsRefund As Boolean
Private mWithdrawalOrRefund As String

' 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")
    mIsRefund = .GetBoolean("IsRefund")
    If mIsRefund Then mWithdrawalOrRefund = "Refund" Else mWithdrawalOrRefund = "Withdrawal"
  End With

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return initial HTML content (excluding html and body tags)
      returnValue = ScriptInfo.TemplateText

    Case "CalculatePaymentArrangement"
      ' Calculate Payment Arrangement
      Main = CalculatePaymentArrangement(parametersJson, returnValue)

    Case "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, requestInfo, returnValue)

    Case "GetAllocations"
      ' Get Allocations
      Main = GetAllocations(parametersJson, returnValue)

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

    Case "GetPaymentArrangementOptions"
      ' Get Payment Arrangement Options
      Main = GetPaymentArrangementOptions(parametersJson, returnValue)

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

    Case "Form_Withdrawal_Change"
      ' Get updated form information based on the properties changing
      Main = Form_Withdrawal_Change(parametersJson, returnValue)

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

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

End Function

''' &lt;summary&gt;
'''  Calculate Payment Arrangement and return summary.
''' &lt;/summary&gt;
Private Function CalculatePaymentArrangement(parametersJson As String,
                                             ByRef returnValue As String) As Boolean

  Dim AccountWithdrawal As finAccountWithdrawal
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get Account Withdrawal
  If Success Then
    If CreateAccountWithdrawal(WizardFinishParameters, AccountWithdrawal) Then
      Success = AccountWithdrawal.Calculate()
    Else
      Success = False
    End If
  End If

  ' Get Summary
  If Success Then
    returnValue = finBL.SummaryPageFunctions.AccountWithdrawalSummary(False, AccountWithdrawal, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY, "PaymentArrangement"))
  Else
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message, finBL.Error.Details)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get updated form information based on Withdrawal properties changing.
''' &lt;/summary&gt;
Public Function Form_Withdrawal_Change(parametersJson As String,
                                       ByRef response As String) As Boolean

  Dim AccountWithdrawal As finAccountWithdrawal
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Withdrawal
  If Success Then
    Success = CreateAccountWithdrawal(WizardFinishParameters, AccountWithdrawal)
  End If

  ' Update Transaction Type?
  If Success AndAlso WizardFinishParameters.TransactionTypeChanged Then
    AccountWithdrawal.TransactionTypeIdUpdate(WizardFinishParameters.TransactionTypeId)
  End If

  ' Recalculate Payment Fee?
  If Success AndAlso WizardFinishParameters.RecalculatePaymentFee Then
    Success = AccountWithdrawal.PaymentFeeCalculate(False)
  End If

  If Success Then
    ' General Properties
    FormInitialisationInfo = New FormInitialisationInfo()
    FormInitialisationInfoUpdate(AccountWithdrawal, WizardFinishParameters, FormInitialisationInfo)

    ' Other Properties
    With FormInitialisationInfo
    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 Payment Allocations.
''' &lt;/summary&gt;
Private Function GetAllocations(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim AccountWithdrawal As finAccountWithdrawal
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Withdrawal
  If Success Then
    If CreateAccountWithdrawal(WizardFinishParameters, AccountWithdrawal) Then
      Success = AccountWithdrawal.Calculate()
    Else
      Success = False
    End If
  End If

  If Success Then
    Data = New With {
      .AllocationFeeIB = AccountWithdrawal.AllocationFeeIB,
      .AllocationFeeNIB = AccountWithdrawal.AllocationFeeNIB,
      .AllocationInterest = AccountWithdrawal.AllocationInterest,
      .AllocationPrincipalIB = AccountWithdrawal.AllocationPrincipalIB,
      .AllocationPrincipalNIB = AccountWithdrawal.AllocationPrincipalNIB,
      .BalanceFeeIB = AccountWithdrawal.BalanceFeeIB,
      .BalanceFeeNIB = AccountWithdrawal.BalanceFeeNIB,
      .BalanceInterest = AccountWithdrawal.BalanceInterest,
      .BalancePrincipalIB = AccountWithdrawal.BalancePrincipalIB,
      .BalancePrincipalNIB = AccountWithdrawal.BalancePrincipalNIB
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account Schedule for the button next to the Withdrawal Date
''' &lt;/summary&gt;
Public Function GetAccountSchedule(parametersJson As String,
                                    ByRef response As String) As Boolean

  Dim AccountWithdrawal As finAccountWithdrawal
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Withdrawal
  If Success Then
    Success = CreateAccountWithdrawal(WizardFinishParameters, AccountWithdrawal)
  End If

  ' Calculate
  If Success Then
    Success = AccountWithdrawal.Calculate()
  End If

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

  Return Success

End Function

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

  Dim AccountWithdrawal As finAccountWithdrawal
  Dim dv As DataView
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Found As Boolean
  Dim i As Integer
  Dim Success As Boolean

  ' 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 Account.")
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  Else
    If mIsRefund Then
      If Not finBL.CurrentUser.Permissions.Allow("Account.Refund") Then
        Success = False
        finBL.Error.ErrorBegin("You do not have permission to process an Account Refund.")
      End If
    Else
      If Not finBL.CurrentUser.Permissions.Allow("Account.Withdrawal") Then
        Success = False
        finBL.Error.ErrorBegin("You do not have permission to process an Account Withdrawal.")
      End If
    End If
  End If

  ' Create Account Withdrawal object
  If Success Then
    Success = CreateAccountWithdrawal(Nothing, AccountWithdrawal)
  End If

  ' Update default Transaction Type
  If Success Then
    If Len(mCombinedParameters.GetString("DefaultTransactionTypeId")) &lt;&gt; 0 Then
      AccountWithdrawal.TransactionTypeIdUpdate(mCombinedParameters.GetString("DefaultTransactionTypeId"))
    End If
  End If

  ' Validate Account
  If Success Then
    If Not mIsRefund AndAlso Not AccountWithdrawal.Account.AccountType.OptionAllowWithdrawals Then
      Success = False
      finBL.Error.ErrorBegin("This Account Type does not allow Withdrawals.")
    ElseIf Not mIsRefund AndAlso AccountWithdrawal.Account.SuspendWithdrawals Then
      Success = False
      finBL.Error.ErrorBegin("Withdrawals are Suspended for this Account.")
    End If
  End If

  ' Validate Transaction Type
  If Success Then
    If finBL.TransactionTypes.GetDataView(dv, "", False, AccountWithdrawal.TransactionTypeDataViewFilter(mIsRefund, True)) Then
      If dv.Count = 0 Then
        Success = False
        finBL.Error.ErrorBegin("There are no valid Transaction Types.")
      ElseIf dv.Count = 1 Then
        ' Only one Transaction Type - so use this regardless
        AccountWithdrawal.TransactionTypeIdUpdate(finBL.Database.GetFieldString(dv(0)!TransactionTypeId))
      ElseIf AccountWithdrawal.TransactionTypePk &lt;&gt; 0 Then
        ' Check Transaction Type is valid
        Found = False
        For i = 0 To dv.Count - 1
          If AccountWithdrawal.TransactionTypePk = finBL.Database.GetFieldInteger(dv(i)!Pk) Then
            Found = True
            Exit For
          End If
        Next
        If Not Found Then
          AccountWithdrawal.TransactionTypeIdUpdate("")
        End If
      End If
    End If
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    FormInitialisationInfoUpdate(AccountWithdrawal, Nothing, FormInitialisationInfo)

    ' Other Properties
    With FormInitialisationInfo
      ' General
      .RecordId = AccountWithdrawal.Account.AccountId
      .RecordDescription = AccountWithdrawal.Account.Name

      ' Lists
      .PayeeNameList = finBL.AccountFunctions.GetByWhomList(AccountWithdrawal.Account, True, True)
      .PayeeTypeList = finBL.Enums.isefinDisbursementPayeeType_GetList(finBL.CurrentUser.Permissions.Allow("Account.Withdrawal.DisbursePayeeTypeNone"), True, False)
      
      ' List Filters
      .ExternalPartiesBrokerFilter = finBL.ExternalParties.GetDataViewFilter_SupportsDisbursements(isefinExternalPartyType.Broker)
      .ExternalPartiesInsurerFilter = finBL.ExternalParties.GetDataViewFilter_SupportsDisbursements(isefinExternalPartyType.Insurer)
      .ExternalPartiesDealerFilter = finBL.ExternalParties.GetDataViewFilter_SupportsDisbursements(isefinExternalPartyType.Dealer)
      .ExternalPartiesOtherFilter = finBL.ExternalParties.GetDataViewFilter_SupportsDisbursements(isefinExternalPartyType.Other)
      .TransactionTypesFilter = AccountWithdrawal.TransactionTypeDataViewFilter(mIsRefund, True)

      ' Configuration
      .CanChangeOverdueHold = finBL.CurrentUser.Permissions.Allow("Account.Withdrawal.HoldOverdueUpdate")
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Deserialise 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

  ' Deserialise
  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;
'''  Get Payment Arrangement Options.
''' &lt;/summary&gt;
Private Function GetPaymentArrangementOptions(parametersJson As String,
                                              ByRef returnValue As String) As Boolean

  Dim AccountWithdrawal As finAccountWithdrawal
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Get Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get Withdrawal and Calculate
  If Success Then
    If CreateAccountWithdrawal(WizardFinishParameters, AccountWithdrawal) Then
      Success = AccountWithdrawal.Calculate()
    Else
      Success = False
    End If
  End If

  ' Has Final Payment?
  If Success Then
    Data = New With {
      .HasFinalPayment = (AccountWithdrawal.Calculation.PaymentFinalDate &lt;&gt; Nothing),
      .IsAdjustRegularPaymentMaturityAvailable = AccountWithdrawal.IsAdjustRegularPaymentMaturityAvailable()
    }
  End If

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

  Return Success

End Function

Private Sub FormInitialisationInfoUpdate(accountWithdrawal As finAccountWithdrawal,
                                         wizardFinishParameters As WizardFinishParameters,
                                         formInitialisationInfo As FormInitialisationInfo)

  ' Get Initialisation Info
  With formInitialisationInfo
    ' Record
    .RecordId = AccountWithdrawal.Account.AccountId
    .RecordDescription = AccountWithdrawal.Account.Name

    ' General
    .TransactionTypeId = accountWithdrawal.TransactionTypeId
    .WithdrawalDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(accountWithdrawal.WithdrawalDate)
    .WithdrawalValue = accountWithdrawal.WithdrawalValue
    .CanManuallyAllocate = (accountWithdrawal.TransactionTypePk &lt;&gt; 0 AndAlso accountWithdrawal.CanManuallyAllocate())
    .FeeValue = accountWithdrawal.FeeValue
    .FeeCharge = accountWithdrawal.FeeCharge
    .Reference = accountWithdrawal.TransactionReference
    .RegularPaymentAdjustmentType = accountWithdrawal.RegularPaymentAdjustmentType.ToString()
    .RegularPaymentNew = accountWithdrawal.RegularPaymentNew
    .Notes = accountWithdrawal.TransactionNotes
    .OverdueHold = accountWithdrawal.RegularPaymentOverdueHold
    If accountWithdrawal.DisbursementPayeeType = isefinDisbursementPayeeType.None Then
      If finBL.CurrentUser.Permissions.Allow("Account.Withdrawal.DisbursePayeeTypeNone") Then
        .PayeeTypeText = accountWithdrawal.DisbursementPayeeTypeText
      Else
        .PayeeTypeText = ""
      End If  
    Else
      .PayeeTypeText = accountWithdrawal.DisbursementPayeeTypeText
    End If  
    .PayeeName = accountWithdrawal.DisbursementPayeeName
    .PaymentFeeValue = accountWithdrawal.PaymentFeeValue
    .PaymentFeeCharge = accountWithdrawal.PaymentFeeCharge
    .PrintAdvice = accountWithdrawal.PrintAdvice

    ' Account Summary
    .AccountSummaryHtml = finBL.SummaryPageFunctions.AccountWithdrawalSummary(False, AccountWithdrawal, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY, mWithdrawalOrRefund))

    ' Advanced
    .ShowManualAllocation = mCombinedParameters.GetString("ShowManualAllocation")
    If Not .CanManuallyAllocate Then
      .ShowManualAllocation = "False"
    End If

    If Len(.TransactionTypeId) = 0 Then
      ' Must allow entry of Transaction Type
      .ShowTransactionType = "True"
    Else
      .ShowTransactionType = mCombinedParameters.GetString("ShowTransactionType")
      If Len(.ShowTransactionType) = 0 Then .ShowTransactionType = "Advanced"
    End If

    ' Other Configuration
    .CanChangeFee = accountWithdrawal.FeeAllowChange
    .CanChangePaymentFee = accountWithdrawal.PaymentFeeAllowChange
    .CanPrintAdvice = Len(AccountWithdrawal.GetDocumentId(True)) &lt;&gt; 0
    .IsRefund = mIsRefund
    .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    .ShowCashRegister = (finBL.Settings.AddOns.BankingAdvanced AndAlso finBL.CashRegisters.Count &lt;&gt; 0)
    If mIsRefund OrElse AccountWithdrawal.Account.AccountClass = isefinAccountClass.Disbursement OrElse AccountWithdrawal.TransactionTypePk = 0 Then
      .ShowDisbursement = False
    ElseIf finBL.Settings.AddOns.Disbursements AndAlso finBL.TransactionTypes.ItemByPk(AccountWithdrawal.TransactionTypePk).Element.DisbursementType = isefinDisbursementType.Payout Then
      .ShowDisbursement = True
    Else
      .ShowDisbursement = False
    End If
    .ShowPaymentArrangementPage = (finBL.CurrentUser.Permissions.Allow("Account.PaymentArrangementAdd") AndAlso accountWithdrawal.RegularPaymentAdjustmentAllow)
    .WithdrawalOrRefund = mWithdrawalOrRefund
  End With

End Sub

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

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountWithdrawal = finBL.CreateAccountWithdrawal()

  ' Update
  With accountWithdrawal
    ' Load Account
    Success = .AccountLoad(mAccountId, Not mIsRefund)

    ' Update
    If Success AndAlso parameters IsNot Nothing Then
      ' General
      .TransactionTypeId = parameters.TransactionTypeId
      .CashRegisterId = parameters.CashRegisterId
      .WithdrawalDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.WithdrawalDate)
      .WithdrawalValue = parameters.WithdrawalValue
      .FeeCharge = parameters.FeeCharge
      .FeeValue = parameters.FeeValue

      ' Set after TransactionTypeId since this updates the values
      .TransactionReference = parameters.Reference
      .TransactionNotes = parameters.Notes
      .PrintAdvice = parameters.PrintAdvice

      .DisbursementPayeeTypeText = parameters.PayeeType
      .DisbursementPayeeName = parameters.PayeeName
      .DisbursementExternalPartyId = parameters.ExternalPartyId

      ' Banking details
      Success = .BankingDetails.FromHtmlWidgetJsonString(parameters.BankingDetailsJson)
      If Success AndAlso (parameters.PaymentFeeValue &gt; 0) Then
        .PaymentFeeCharge = parameters.PaymentFeeCharge
        .PaymentFeeValue = parameters.PaymentFeeValue
      End If

      ' Payment Arrangement
      If Success AndAlso Len(parameters.RegularPaymentAdjustmentType) &lt;&gt; 0 Then
        .RegularPaymentAdjustmentType = DirectCast([Enum].Parse(GetType(isefinAccountWithdrawalRegularPaymentAdjustmentType), parameters.RegularPaymentAdjustmentType), isefinAccountWithdrawalRegularPaymentAdjustmentType)
        .RegularPaymentOverdueHold = parameters.HoldOverdueValue

        If parameters.RegularPaymentNew &gt; 0 Then
          .RegularPaymentNew = parameters.RegularPaymentNew
        End If
      End If

      ' Manual Allocations
      .AllocationManual = parameters.ManualAllocation
      If .AllocationManual Then
        .AllocationFeeIB = parameters.ManualAllocationFib
        .AllocationFeeNIB = parameters.ManualAllocationFnib
        .AllocationInterest = parameters.ManualAllocationI
        .AllocationPrincipalIB = parameters.ManualAllocationPib
        .AllocationPrincipalNIB = parameters.ManualAllocationPnib
      End If
    End If
  End With

  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;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim AccountWithdrawal As finAccountWithdrawal
  Dim BankInterfaceRequestMessage As String
  Dim BankInterfaceRequestSent As Boolean
  Dim Success As Boolean
  Dim Warning As String
  Dim WarningWorkflow As String
  Dim WithdrawalAdviceDocumentId As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Withdrawal object
  If Success Then
    Success = CreateAccountWithdrawal(WizardFinishParameters, AccountWithdrawal)
  End If

  ' Execute
  If Success Then
    Success = AccountWithdrawal.ExecuteCommit(BankInterfaceRequestSent, BankInterfaceRequestMessage, Warning)
  End If

  ' Print Advice?
  If Success Then
    If AccountWithdrawal.PrintAdvice Then
      WithdrawalAdviceDocumentId = AccountWithdrawal.GetDocumentId()
    Else
      WithdrawalAdviceDocumentId = ""
    End If
  End If

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

  ' Finalise
  If Success Then
    If Len(WarningWorkflow) &lt;&gt; 0 Then
      If Len(Warning) = 0 Then
        Warning = WarningWorkflow
      Else
        Warning &amp;= vbNewLine &amp; vbNewLine &amp; WarningWorkflow
      End If
    End If  
      
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(BankInterfaceRequestMessage, BankInterfaceRequestSent, AccountWithdrawal.BankTransactionPk, WithdrawalAdviceDocumentId, Warning), returnValue)
  End If

  Return Success

End Function

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

  Dim ConfirmList As New List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
      If WizardValidate_General(parametersJson, ConfirmList) Then
        Data = ConfirmList
      Else
        Success = False
      End If
  End Select

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

  Return Success

End Function

Private Function WizardValidate_General(parametersJson As String,
                                        ByRef confirmList As List(Of String)) As Boolean

  Dim AccountWithdrawal As finAccountWithdrawal
  Dim AvailableCredit1 As Decimal
  Dim AvailableCredit2 As Decimal
  Dim AvailableCredit3 As Decimal
  Dim BankingDetailsWarnings As ISList
  Dim s As String
  Dim Success As Boolean
  Dim TotalValue As Decimal
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise ByRef
  confirmList = New List(Of String)()

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Withdrawal object
  If Success Then
    Success = CreateAccountWithdrawal(WizardFinishParameters, AccountWithdrawal)
  End If

  ' Check Credit Limits
  ' NOTE: if the user has permission to go over the credit limit they will be prompted to confirm, else the transfer will be rejected in the Finish method.
  If Success Then
    With AccountWithdrawal
      If  .Account.AccountType.CreditLimitCount &gt; 0 Then
        ' Get Credit Limits
        Success = .Account.GetAvailableCredit(.WithdrawalDate, True, AvailableCredit1, AvailableCredit2, AvailableCredit3)

        If Success Then
          ' Total Value Resolved
          TotalValue = .WithdrawalValueResolved + .FeeValueResolved

          If finBL.CurrentUser.Permissions.Allow("Account." &amp; mWithdrawalOrRefund &amp; ".OverCreditLimit") Then
            ' User has permission to go over the Credit Limit
            If TotalValue &gt; AvailableCredit1 Then
              confirmList.Add(String.Format("{0} will exceed '{1}'.", mWithdrawalOrRefund, .Account.AccountType.CreditLimit1DescriptionResolved))
            End If
            If .Account.AccountType.CreditLimitCount &gt; 1 AndAlso TotalValue &gt; AvailableCredit2 Then
              confirmList.Add(String.Format("{0} will exceed '{1}'.", mWithdrawalOrRefund,.Account.AccountType.CreditLimit2DescriptionResolved))
            End If
            If .Account.AccountType.CreditLimitCount &gt; 2 AndAlso TotalValue &gt; AvailableCredit3 Then
              confirmList.Add(String.Format("{0} will exceed '{1}'.", mWithdrawalOrRefund,.Account.AccountType.CreditLimit3DescriptionResolved))
            End If
          Else
            ' Cannot exceed Credit Limit
            If TotalValue &gt; AvailableCredit1 Then
              Success = False
              finBL.Error.ErrorBeginFormat("You do not have permission to create this {0}.", mWithdrawalOrRefund)
              finBL.Error.ErrorExtendFormat("{0} will exceed '{1}'.", mWithdrawalOrRefund, .Account.AccountType.CreditLimit1DescriptionResolved)
            ElseIf .Account.AccountType.CreditLimitCount &gt; 1 AndAlso TotalValue &gt; AvailableCredit2 Then
              Success = False
              finBL.Error.ErrorBeginFormat("You do not have permission to create this {0}.", mWithdrawalOrRefund)
              finBL.Error.ErrorExtendFormat("{0} will exceed '{1}'.", mWithdrawalOrRefund,.Account.AccountType.CreditLimit2DescriptionResolved)
            ElseIf .Account.AccountType.CreditLimitCount &gt; 2 AndAlso TotalValue &gt; AvailableCredit3 Then
              Success = False
              finBL.Error.ErrorBeginFormat("You do not have permission to create this {0}.", mWithdrawalOrRefund)
              finBL.Error.ErrorExtendFormat("{0} will exceed '{1}'.", mWithdrawalOrRefund,.Account.AccountType.CreditLimit3DescriptionResolved)
            End If
          End If
        End If

        ' Banking Information
        If Not .BankingDetails.IsValidForTransaction(BankingDetailsWarnings) Then
          For Each s In BankingDetailsWarnings
            confirmList.Add(s)
          Next
        End If
      End If
    End With
  End If

  Return Success

End Function

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

  ' Record
  Public RecordId As String
  Public RecordDescription As String

  ' Details
  Public BankingDetailsJson As String
  Public CanManuallyAllocate As Boolean
  Public FeeCharge As Boolean
  Public FeeValue As Decimal
  Public Notes As String
  Public OverdueHold As Boolean
  Public PayeeName As String
  Public PayeeTypeText As String
  Public PaymentFeeCharge As Boolean
  Public PaymentFeeValue As Decimal
  Public PrintAdvice As Boolean
  Public Reference As String
  Public RegularPaymentAdjustmentType As String
  Public RegularPaymentNew As Decimal
  Public TransactionTypeId As String
  Public WithdrawalDate As Date
  Public WithdrawalValue As Decimal

  ' Account Summary
  Public AccountSummaryHtml As String

  ' Lists
  Public PayeeNameList As Object
  Public PayeeTypeList As Object

  ' List Filters
  Public ExternalPartiesBrokerFilter As String
  Public ExternalPartiesInsurerFilter As String
  Public ExternalPartiesDealerFilter As String
  Public ExternalPartiesOtherFilter As String
  Public TransactionTypesFilter As String

  ' Configuration
  Public CanChangeFee As Boolean
  Public CanChangeOverdueHold As Boolean
  Public CanChangePaymentFee As Boolean
  Public CanPrintAdvice As Boolean
  Public IsRefund As Boolean
  Public PromptOnCommit As Boolean
  Public ShowCashRegister As Boolean
  Public ShowDisbursement As Boolean
  Public ShowPaymentArrangementPage As Boolean
  Public ShowTransactionType As String
  Public ShowManualAllocation As String
  Public WithdrawalOrRefund 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

  ' Details
  Public BankingDetailsJson As String
  Public CashRegisterId As String
  Public ExternalPartyId As String
  Public FeeCharge As Boolean
  Public FeeValue As Decimal
  Public Notes As String
  Public PayeeName As String
  Public PayeeType As String
  Public PayeeTypeText As String
  Public PaymentFeeCharge As Boolean
  Public PaymentFeeValue As Decimal
  Public PrintAdvice As Boolean
  Public Reference As String
  Public TransactionTypeId As String
  Public WithdrawalDate As Date
  Public WithdrawalValue As Decimal

  ' Payment Arrangement
  Public HoldOverdueValue As Boolean
  Public RegularPaymentAdjustmentType As String
  Public RegularPaymentNew As Decimal

  ' Manual Allocations
  Public ManualAllocation As Boolean
  Public ManualAllocationPnib As Decimal
  Public ManualAllocationPib As Decimal
  Public ManualAllocationI As Decimal
  Public ManualAllocationFnib As Decimal
  Public ManualAllocationFib As Decimal

  ' Unrelated to Finish
  Public RecalculatePaymentFee As Boolean
  Public TransactionTypeChanged As Boolean

End Class


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

  ' General
  Public BankInterfaceRequestMessage As String
  Public BankInterfaceRequestSent As Boolean
  Public BankTransactionPk As Integer
  Public Warning As String
  Public WithdrawalAdviceDocumentId As String

  Public Sub New(bankInterfaceRequestMessage As String,
                 bankInterfaceRequestSent As Boolean,
                 bankTransactionPk As Integer,
                 withdrawalAdviceDocumentId As String,
                 warning As String)

    Me.BankInterfaceRequestMessage = bankInterfaceRequestMessage
    Me.BankInterfaceRequestSent = bankInterfaceRequestSent
    Me.BankTransactionPk = bankTransactionPk
    Me.Warning = warning
    Me.WithdrawalAdviceDocumentId = withdrawalAdviceDocumentId

  End Sub

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

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

NOTE: This also supports Refunds by setting the IsRefund parameter to True.

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;!-- HTML Widget Styles --&gt;
  &lt;style type="text/less"&gt;
    #tblManualAllocation {
      border-collapse:collapse;
      border-radius:4px;
      margin:4px 0 8px 4px;

      td, th {
        padding:4px;
      }

      thead {
        td {
          background-color:#F0F0F0;
          font-weight:bold;
          text-align:right;
        }
      }

      tbody {
        th {
          text-align:left;
        }

        td:nth-child(2), td:last-child {
          min-width:6em;
          text-align:right;
        }

        tr:nth-child(even) {
          background-color:#FAFAFA;
        }

        tr:last-child {
          td:nth-child(3) {
            text-align:right;
            padding-right:8px;
          }
        }
      }

      tfoot {
        background-color:#FFE5BF;
        color:#000080;
        font-weight:bold;

        th {
          text-align:left;
        }

        td {
          text-align:right;
        }

        tr:last-child {
          td:nth-child(3) {
            padding-right:8px;
          }
        }
      }
    }

    .negative-allocation {
      color:red;
    }

    label.is-label-information {
      display:inline-block;
      margin-left:4px;
    }
  &lt;/style&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"&gt;Withdrawal&lt;/li&gt;
        &lt;li tabId="PaymentArrangement" tooltipText="Enter any adjustments to future Regular Payments."&gt;Payment Arrangement&lt;/li&gt;
        &lt;li tabId="Allocation"&gt;Manual Allocation&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" style="display:flex;flex-direction:column"&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="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="lblTransactionDetails"&gt;Withdrawal details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr id="trTransactionType"&gt;
          &lt;th&gt;&lt;label for="cboTransactionType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="cboTransactionType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateWithdrawalDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="dateWithdrawalDate"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numWithdrawalValue"&gt;Withdrawal:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;
            &lt;input id="numWithdrawalValue"/&gt;
            &lt;button id="cmdSchedule" class="is-button small" icon="Schedule"&gt;Schedule&lt;/button&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trManualAllocation"&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="chkManualAllocation" type="checkbox" /&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 colspan="2"&gt;&lt;input id="numFeeValue"/&gt; &lt;input id="chkFeeCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtReference"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtNotes"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="chkPrintAdvice"&gt;Print Advice:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="chkPrintAdvice" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPaymentMethod"&gt;Withdrawal Method&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr class="trDisbursement"&gt;
          &lt;th&gt;&lt;label for="cboPayeeType"&gt;Disburse:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="cboPayeeType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr class="trDisbursement"&gt;
          &lt;th&gt;&lt;label for="cboExternalParty"&gt;External:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="cboExternalParty"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr class="trDisbursement"&gt;
          &lt;th&gt;&lt;label for="cboPayeeName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="cboPayeeName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tbody id="apdPaymentDetails"&gt;&lt;/tbody&gt;
        &lt;tr style="display:none"&gt;
          &lt;th&gt;&lt;label for="numPaymentFeeValue"&gt;Payment&amp;nbsp;Fee:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="numPaymentFeeValue"/&gt; &lt;input id="chkPaymentFeeCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;

      &lt;!-- Summary --&gt;
      &lt;div id="wbAccountSummary" style="flex-grow:1"&gt;&lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Payment Arrangement --&gt;
    &lt;div id="pagePaymentArrangement" style="display:flex;flex-direction:column"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:6em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAdjustRegularPayments"&gt;Adjust future Regular Payments?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="rblArrangementOptions"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numRegularPaymentNew"&gt;Payment:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numRegularPaymentNew" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOptions"&gt;Options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkHoldOverdueValue" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSummary"&gt;Summary&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;

      &lt;!-- Summary --&gt;
      &lt;div id="wbPaymentArrangementSummary" style="flex-grow:1"&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Allocation --&gt;
    &lt;div id="pageAllocation"&gt;
      &lt;table id="tblManualAllocation"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em;"/&gt;
          &lt;col style="width:10em;"/&gt;
          &lt;col /&gt;
          &lt;col style="width:1em;"/&gt;
          &lt;col style="width:10em;"/&gt;
        &lt;/colgroup&gt;

        &lt;thead&gt;
          &lt;tr&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td style="text-align:center"&gt;+/-&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td&gt;New&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Principal NIB:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.BalancePrincipalNIB, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numPnibAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocatePnib" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.NewPrincipalNIB, true, false)" ng-class="mWithdrawalAllocations.NewPrincipalNIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Principal:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.BalancePrincipalIB, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numPibAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocatePib" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.NewPrincipalIB, true, false)" ng-class="mWithdrawalAllocations.NewPrincipalIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Interest:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.BalanceInterest, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numIAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocateI" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.NewInterest, true, false)" ng-class="mWithdrawalAllocations.NewInterest &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Fees NIB:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.BalanceFeeNIB, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numFnibAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocateFnib" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.NewFeeNIB, true, false)" ng-class="mWithdrawalAllocations.NewFeeNIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Fees:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.BalanceFeeIB, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numFibAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocateFib" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.NewFeeIB, true, false)" ng-class="mWithdrawalAllocations.NewFeeIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Remaining:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td ng-bind-html="widget.FormatCurrency(mWithdrawalAllocations.TotalRemaining, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tfoot&gt;
          &lt;tr&gt;
            &lt;th&gt;Totals:&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.TotalBalance, true, false)"&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.TotalAllocations, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mWithdrawalAllocations.TotalNew, true, false)"&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tfoot&gt;
      &lt;/table&gt;

      &lt;table class="is-form"&gt;
        &lt;tr&gt;
          &lt;td colspan="4"&gt;
            &lt;button id="cmdAllocationSchedule" class="is-button icon" icon="Schedule"&gt;Schedule&lt;/button&gt;
            &lt;button id="cmdAutoAllocate" class="is-button icon" icon="Account_BalanceAdjust"&gt;Auto-Allocate&lt;/button&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

    &lt;button id="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 mLastFinishParameters;

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

  lblTransactionDetails: null,
  trTransactionType: null,
  cboTransactionType: null,
  dateWithdrawalDate: null,
  numWithdrawalValue: null,
  trManualAllocation: null,
  chkManualAllocation: null,
  numFeeValue: null,
  chkFeeCharge: null,
  txtReference: null,
  txtNotes: null,
  chkPrintAdvice: null,

  lblPaymentMethod: null,
  cboPayeeType: null,
  cboExternalParty: null,
  cboPayeeName: null,
  apdPaymentDetails: null,
  numPaymentFeeValue: null,
  chkPaymentFeeCharge: null,

  wbAccountSummary: null,

  // Payment Arrangement
  lblAdjustRegularPayments: null,
  rblArrangementOptions: null,
  numRegularPaymentNew: null,
  lblOptions: null,
  chkHoldOverdueValue: null,
  lblSummary: null,

  wbPaymentArrangementSummary: null,

  // Allocation
  tblManualAllocation: null,
  numPnibAllocated: null,
  numPibAllocated: null,
  numIAllocated: null,
  numFnibAllocated: null,
  numFibAllocated: null,
}

// Form
var frmMain;
var tabWizard;

// Other
var mValueData;

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

var cmdAdvanced;
var cmdSchedule;
var cmdAllocatePnib;
var cmdAllocatePib;
var cmdAllocateI;
var cmdAllocateFnib;
var cmdAllocateFib;
var cmdAllocationSchedule;
var cmdAutoAllocate;

// Other
var mAdvancedVisible = false;
var mAllocationFinishParameters;
var mCompact = false;
var mHasAdvancedOptions = false;
var mWithdrawalAllocations;
var mSummaryCache = {};
var mRefreshTimer;
var mRefreshTimerPaymentArrangement;

// ==========
// 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.lblTransactionDetails = widget.UI.Label("lblTransactionDetails", {});
  C.trTransactionType = $("#trTransactionType");
  C.cboTransactionType = widget.UI.DBCombo("cboTransactionType", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

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

    onChange: dateWithdrawalDate_Change,
  });
  C.numWithdrawalValue = widget.UI.NumberBox("numWithdrawalValue", {
    allowBlank: false,
    blankIfZero: true,
    minValue: 0.01,
    maxValue: 999999999999,

    onChange: numWithdrawalValue_Change,
  });
  C.trManualAllocation = $("#trManualAllocation");
  C.chkManualAllocation = widget.UI.CheckBox("chkManualAllocation", {
    caption: "Allocate Withdrawal Manually?",

    onChange: chkManualAllocation_Change,
  });
  C.numFeeValue = widget.UI.NumberBox("numFeeValue", {
    blankIfZero: false,
    readOnly: true,
    minValue: 0,
    maxValue: 999999999,
    
    onChange: numFeeValue_Change,
  });
  C.chkFeeCharge = widget.UI.CheckBox("chkFeeCharge", {
    caption: "Charge Fee?",

    onChange: chkFeeCharge_Change,
  });
  C.txtReference = widget.UI.TextBox("txtReference", {
    maxLength: 20,
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });
  C.chkPrintAdvice = widget.UI.CheckBox("chkPrintAdvice", {
    caption: "Print Advice?",
  });

  C.lblPaymentMethod = widget.UI.Label("lblPaymentMethod", {});
  C.cboPayeeType = widget.UI.ComboBox("cboPayeeType", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    onChange: cboPayeeType_Change,
  });
  C.cboExternalParty = widget.UI.DBCombo("cboExternalParty", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.cboPayeeName = widget.UI.DBCombo("cboPayeeName", {
    allowBlank: false,
    maxLength: 50,
  });

  C.apdPaymentDetails = widget.UI.AccountOutgoingPaymentDetails("apdPaymentDetails", {
    onPaymentMethodChange: apdPaymentDetails_PaymentMethodChange,
  });
  C.numPaymentFeeValue = widget.UI.NumberBox("numPaymentFeeValue", {
    minValue: 0,
    maxValue: 999999999,
    autoReadOnly: false,
    readOnly: true,

    onChange: numPaymentFeeValue_Change,
  });
  C.chkPaymentFeeCharge = widget.UI.CheckBox("chkPaymentFeeCharge", {
    caption: "Charge Fee?",

    onChange: numPaymentFeeValue_Change,
  });

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

  //   Payment Arrangement
  C.lblAdjustRegularPayments = widget.UI.Label("lblAdjustRegularPayments", {});

  var list = [];
  list.push({ caption: "1. Hold current Regular Payment (Final Payment date may change)?", value: "None" });
  list.push({ caption: "2. Adjust Regular Payment to maintain current Final Date?", value: "AdjustRegularPayment" });
  list.push({ caption: "3. Adjust Regular Payment to maintain current Maturity Date?", value: "AdjustRegularPaymentMaturity" });
  list.push({ caption: "4. Override Regular Payment?", value: "OverrideRegularPayment" });
  C.rblArrangementOptions = widget.UI.RadioButtonList("rblArrangementOptions", {
    allowBlank: false,
    layout: "vertical",
    list: list,

    onChange: rblArrangementOptions_Change,
  });

  C.numRegularPaymentNew = widget.UI.NumberBox("numRegularPaymentNew", {
    allowBlank: false,
    width: "7em",

    onChange: numRegularPaymentNew_Change
  });

  C.lblOptions = widget.UI.Label("lblOptions", {});
  C.chkHoldOverdueValue = widget.UI.CheckBox("chkHoldOverdueValue", {
    caption: "Hold Overdue Value?",
    captionWrap: true,

    onChange: wbPaymentArrangementSummary_Refresh,
  });
  C.lblSummary = widget.UI.Label("lblSummary", {});

  C.wbPaymentArrangementSummary = widget.UI.PreviewPane("wbPaymentArrangementSummary", {});

  //   Allocation
  C.tblManualAllocation = $("#tblManualAllocation");
  C.numPnibAllocated = widget.UI.NumberBox("numPnibAllocated", {
    blankIfZero: true,

    onChange: numAllocated_Change
  });
  C.numPibAllocated = widget.UI.NumberBox("numPibAllocated", {
    blankIfZero: true,

    onChange: numAllocated_Change
  });
  C.numIAllocated = widget.UI.NumberBox("numIAllocated", {
    blankIfZero: true,

    onChange: numAllocated_Change
  });
  C.numFnibAllocated = widget.UI.NumberBox("numFnibAllocated", {
    blankIfZero: true,

    onChange: numAllocated_Change
  });
  C.numFibAllocated = widget.UI.NumberBox("numFibAllocated", {
    blankIfZero: true,

    onChange: numAllocated_Change
  });

  // 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"); });

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(function () {
    // Toggle Advanced
    mAdvancedVisible = !mAdvancedVisible;
    Form_Resize();
    pageGeneral_Refresh();
  });

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

  cmdAllocatePnib = $("#cmdAllocatePnib");
  cmdAllocatePib = $("#cmdAllocatePib");
  cmdAllocateI = $("#cmdAllocateI");
  cmdAllocateFnib = $("#cmdAllocateFnib");
  cmdAllocateFib = $("#cmdAllocateFib");
  cmdAllocatePnib.click(function() { AllocateWithdrawal("PNIB"); });
  cmdAllocatePib.click(function() { AllocateWithdrawal("PIB"); });
  cmdAllocateI.click(function() { AllocateWithdrawal("I"); });
  cmdAllocateFnib.click(function() { AllocateWithdrawal("FNIB"); });
  cmdAllocateFib.click(function() { AllocateWithdrawal("FIB"); });

  cmdAllocationSchedule = $("#cmdAllocationSchedule");
  cmdAllocationSchedule.click(ShowSchedule);
  cmdAutoAllocate = $("#cmdAutoAllocate");
  cmdAutoAllocate.click(AutoAllocateWithdrawal);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  mSummaryCache = {};

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mLastFinishParameters = 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);
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboRecord.RefreshUnbound(mRecord.RecordId, mRecord.RecordDescription);

    C.cboTransactionType.Text(mRecord.TransactionTypeId);
    C.dateWithdrawalDate.Value(mRecord.WithdrawalDate);
    C.numWithdrawalValue.Value(mRecord.WithdrawalValue);
    C.numFeeValue.Value(mRecord.FeeValue);
    C.chkFeeCharge.Value(mRecord.FeeCharge);
    C.txtReference.Text(mRecord.Reference);
    C.txtNotes.Text(mRecord.Notes);
    C.chkPrintAdvice.Value(mRecord.PrintAdvice);

    C.cboPayeeType.Text(mRecord.PayeeTypeText);
    C.cboPayeeName.Text(mRecord.PayeeName);
    C.numPaymentFeeValue.Value(mRecord.PaymentFeeValue);
    C.chkPaymentFeeCharge.Value(mRecord.PaymentFeeCharge);

    C.apdPaymentDetails.ShowCashRegister(mRecord.ShowCashRegister);
    C.apdPaymentDetails.Initialise(mRecord.RecordId, {
      applyDefaultPaymentMethod: true,
      applyDefaultCashRegister: true,
      isWithdrawal: true,
    });

    C.wbAccountSummary.SetContent(mRecord.AccountSummaryHtml, false);

    // Payment Arrangement
    C.rblArrangementOptions.Value(mRecord.RegularPaymentAdjustmentType);
    C.numRegularPaymentNew.Value(mRecord.RegularPaymentNew);
    C.chkHoldOverdueValue.Value(mRecord.OverdueHold);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // 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) {
    if (mRecord.IsRefund) {
      widget.SetHeading("Account Refund");
    }
    else {
      widget.SetHeading("Account Withdrawal");
    }
  }

  // Information Lists

  // Lists
  if (mRecord) {
    C.cboTransactionType.RefreshFromStandardRange("TransactionTypes", mRecord.TransactionTypesFilter);
    C.cboPayeeType.ListFromCsvString(mRecord.PayeeTypeList);
    C.cboPayeeName.ListFromCsvString(mRecord.PayeeNameList);
    C.cboExternalParty.RefreshFromStandardRange("ExternalParties", mRecord.ExternalPartiesDealerFilter);
  }

  // Controls
  if (mRecord) {
    // General
    C.chkManualAllocation.Caption("Allocate " + mRecord.WithdrawalOrRefund + " Manually?");
    C.numFeeValue.ReadOnly(!mRecord.CanChangeFee);
    C.numWithdrawalValue.Caption(mRecord.WithdrawalOrRefund + ":");
    C.lblTransactionDetails.Text(mRecord.WithdrawalOrRefund + " details");
    C.lblPaymentMethod.Text(mRecord.WithdrawalOrRefund + " method");

    C.chkHoldOverdueValue.ReadOnly(!mRecord.CanChangeOverdueHold);

    pageGeneral_Refresh();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Compact (this form can get quite long vertically so make the most of the space)?
  if (mHasAdvancedOptions &amp;&amp; mAdvancedVisible || C.cboTransactionType.VisibleRow()) {
    mCompact = window.innerHeight &lt; 880;
  }
  else {
    mCompact = window.innerHeight &lt; 980;
  }
  if (mCompact) {
    C.lblAccount.VisibleRow(false);
    C.cboRecord.VisibleRow(false);
  }
  else {
    C.lblAccount.VisibleRow(true);
    C.cboRecord.VisibleRow(true);
  }
  if (mRecord) tabWizard_Refresh_UpdateHeading();

  // General

  // Tab
  tabWizard_Resize();

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

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

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

  // Exceptions
  var finalPage = "General";
  if (mRecord.CanManuallyAllocate &amp;&amp; C.chkManualAllocation.Value()) {
    finalPage = "Allocation";
  }
  else if (mRecord.ShowPaymentArrangementPage) {
    finalPage = "PaymentArrangement";
  }

  if (tabWizard.SelectedTabId() == finalPage) {
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
  }

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.numWithdrawalValue.WidthResizeFromParent();
      C.txtReference.WidthResizeFromParent();
      C.txtNotes.ResizeFromParent();
      C.numPaymentFeeValue.WidthResizeFromParent();
      C.cboPayeeName.WidthResizeFromParent();
      C.wbAccountSummary.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;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "PaymentArrangement":
          found = mRecord.ShowPaymentArrangementPage;
          break;

        case "Allocation":
          found = (C.chkManualAllocation.Value() &amp;&amp; mRecord.CanManuallyAllocate);
          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 "PaymentArrangement":
        pagePaymentArrangement_Refresh();
        break;

      case "Allocation":
        pageAllocation_Refresh();
        break;
    }
  }

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

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

  // Tweak fields

  // Update Heading
  tabWizard_Refresh_UpdateHeading();

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

  // Resize Wizard
  tabWizard_Resize();

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

function tabWizard_Refresh_UpdateHeading() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      if (mCompact) {
        frmMain.RefreshHeading(mRecord.WithdrawalOrRefund, "Enter details of the " + mRecord.WithdrawalOrRefund + " being made from Account '" + mRecord.RecordId + "', " + mRecord.RecordDescription + ".");
      }
      else {
        frmMain.RefreshHeading(mRecord.WithdrawalOrRefund, "Enter details of the " + mRecord.WithdrawalOrRefund + " being made.");
      }
      break;

    case "Allocation":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter allocation details for a " + mRecord.WithdrawalOrRefund + " of " + widget.FormatCurrency(C.numWithdrawalValue.Value(), true) + " to Account '" + mRecord.RecordId + "', " + mRecord.RecordDescription + ".");
      break;

    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // Has Server-side validation
        break;

      case "Allocation":
        if (C.numWithdrawalValue.Value() != mWithdrawalAllocations.TotalAllocations) {
          Ok = false;
          widget.UI.MsgBoxAlert("The total value allocated does not equal the " + mRecord.WithdrawalOrRefund + " value.");
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        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":
        // General
        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;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mRecord.PromptOnCommit) {
      // Confirm
      var heading = "Make " + mRecord.WithdrawalOrRefund;
      var message = "";
      var feeString = "";

      // Fee Note
      if (C.chkFeeCharge.Value() &amp;&amp; C.numFeeValue.Value() != 0) {
        feeString = "\n\nNOTE: The Account will be charged a " + mRecord.WithdrawalOrRefund.toLowerCase() + " fee of " + widget.FormatCurrency(C.numFeeValue.Value(), true);
        if (C.chkPaymentFeeCharge.Value() &amp;&amp; C.numPaymentFeeValue.Value() != 0) {
          feeString += " and a payment fee of " + widget.FormatCurrency(C.numPaymentFeeValue.Value(), true) + ".";
        }
        else {
          feeString += ".";
        }
      }
      else if (C.chkPaymentFeeCharge.Value() &amp;&amp; C.numPaymentFeeValue.Value() != 0) {
        feeString = "\n\nNOTE: The Account will be charged a payment fee of " + widget.FormatCurrency(C.numPaymentFeeValue.Value(), true);
      }

      message = "Are you sure you want to " + (mRecord.IsRefund ? "refund " : "make a withdrawal of ") + widget.FormatCurrency(C.numWithdrawalValue.Value(), true) + "?" + feeString;

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

// =================
// Finish Parameters
// =================
function CreateFinishParameters() {
  var params = {
    // General
    TransactionTypeId: C.cboTransactionType.Text(),
    WithdrawalDate: C.dateWithdrawalDate.Value(),
    WithdrawalValue: C.numWithdrawalValue.Value(),
    FeeCharge: C.chkFeeCharge.Value(),
    FeeValue: C.numFeeValue.Value(),
    Reference: C.txtReference.Text(),
    Notes: C.txtNotes.Text(),
    PrintAdvice: C.chkPrintAdvice.Value(),

    PayeeType: C.cboPayeeType.Text(),
    PayeeName: C.cboPayeeName.Text(),
    ExternalPartyId: C.cboExternalParty.Text(),

    BankingDetailsJson: C.apdPaymentDetails.ToBankingDetailsJson(),
    CashRegisterId: C.apdPaymentDetails.CashRegisterId(),

    PaymentFeeCharge: C.chkPaymentFeeCharge.Value(),
    PaymentFeeValue: C.numPaymentFeeValue.Value(),
  };

  // Payment Arrangement
  if (mRecord.ShowPaymentArrangementPage) {
    params.RegularPaymentAdjustmentType = C.rblArrangementOptions.Value();
    params.HoldOverdueValue = C.chkHoldOverdueValue.Value();

    if (C.rblArrangementOptions.Value() == "OverrideRegularPayment") {
      params.RegularPaymentNew = C.numRegularPaymentNew.Value();
    }
  }

  // Allocations
  if (mRecord.CanManuallyAllocate) {
    params.ManualAllocation = C.chkManualAllocation.Value();
    params.ManualAllocationPnib = C.numPnibAllocated.Value();
    params.ManualAllocationPib = C.numPibAllocated.Value();
    params.ManualAllocationI = C.numIAllocated.Value();
    params.ManualAllocationFnib = C.numFnibAllocated.Value();
    params.ManualAllocationFib = C.numFibAllocated.Value();
  }

  return params;
}

function Form_ExecuteAction_FinishPost() {
  // 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 " + mRecord.WithdrawalOrRefund.toLowerCase() + " was successfully added 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) {
  // Print Advice?
  if(data.WithdrawalAdviceDocumentId) {
    // Print via Application Shortcut
    widget.ExecuteApplicationShortcutUrl("app://Document?id=" + encodeURI(data.WithdrawalAdviceDocumentId) + "&amp;BankTransactionPk=" + data.BankTransactionPk);
  }

  // Close Form
  widget.Close();

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

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Check for Advanced options
  mHasAdvancedOptions = false;
  if (mRecord) {
    if (mRecord.ShowTransactionType.toUpperCase() == "ADVANCED" || mRecord.ShowManualAllocation.toUpperCase() == "ADVANCED") mHasAdvancedOptions = true;
  }

  // Controls
  if (mRecord) {
    // Reset Advanced
    C.trTransactionType.removeClass("advanced");
    C.cboTransactionType.VisibleRow(true);
    C.trManualAllocation.removeClass("advanced");
    C.chkManualAllocation.VisibleRow(true);

    switch(mRecord.ShowTransactionType.toUpperCase()) {
      case "TRUE":
        C.cboTransactionType.VisibleRow(true);
        break;

      case "FALSE":
        C.cboTransactionType.VisibleRow(false);
        break;

      case "ADVANCED":
        C.trTransactionType.addClass("advanced");
        break;
    }
    switch(mRecord.ShowManualAllocation.toUpperCase()) {
      case "TRUE":
        C.chkManualAllocation.VisibleRow(true);
        break;

      case "FALSE":
        C.chkManualAllocation.VisibleRow(false);
        break;

      case "ADVANCED":
        C.trManualAllocation.addClass("advanced");
        break;
    }

    C.chkManualAllocation.Visible(mRecord.CanManuallyAllocate);
    C.numFeeValue.ReadOnly(!mRecord.CanChangeFee || !C.chkFeeCharge.Value());
    C.chkPrintAdvice.VisibleRow(mRecord.CanPrintAdvice);
    C.numPaymentFeeValue.ReadOnly(!mRecord.CanChangePaymentFee || !C.chkPaymentFeeCharge.Value());

    if (mRecord.ShowDisbursement) {
      $(".trDisbursement").show();

      var PayeeType = C.cboPayeeType.Text().toUpperCase();

      C.cboPayeeName.VisibleRow(PayeeType == "ACCOUNT");

      switch (PayeeType) {
        case "ACCOUNT":
          C.cboExternalParty.VisibleRow(false);
          C.apdPaymentDetails.Visible(true);
          break;

        case "BROKER":
          C.cboExternalParty.Text("");
          C.cboExternalParty.Caption("Broker:");
          C.cboExternalParty.RefreshFromStandardRange("ExternalParties", mRecord.ExternalPartiesBrokerFilter);
          C.cboExternalParty.VisibleRow(true);
          C.apdPaymentDetails.Visible(false);
          break;

        case "DEALER":
          C.cboExternalParty.Text("");
          C.cboExternalParty.Caption("Dealer:");
          C.cboExternalParty.RefreshFromStandardRange("ExternalParties", mRecord.ExternalPartiesDealerFilter);
          C.cboExternalParty.VisibleRow(true);
          C.apdPaymentDetails.Visible(false);
          break;

        case "INSURER":
          C.cboExternalParty.Text("");
          C.cboExternalParty.Caption("Insurer:");
          C.cboExternalParty.RefreshFromStandardRange("ExternalParties", mRecord.ExternalPartiesInsurerFilter);
          C.cboExternalParty.VisibleRow(true);
          C.apdPaymentDetails.Visible(false);
          break;

        case "OTHER":
          C.cboExternalParty.Text("");
          C.cboExternalParty.Caption("Other:");
          C.cboExternalParty.RefreshFromStandardRange("ExternalParties", mRecord.ExternalPartiesOtherFilter);
          C.cboExternalParty.VisibleRow(true);
          C.apdPaymentDetails.Visible(false);
          break;

        case "NONE":
          C.cboExternalParty.RefreshFromStandardRange("ExternalParties", mRecord.ExternalPartiesOtherFilter);
          C.cboExternalParty.VisibleRow(false);
          C.apdPaymentDetails.Visible(true);
          break;

        default:
          C.cboExternalParty.VisibleRow(false);
          C.apdPaymentDetails.Visible(false);
          break;
      }
    } else {
      $(".trDisbursement").hide();
      C.apdPaymentDetails.Visible(true);
    }
  }

  // Schedule Button availale?
  cmdSchedule.prop("disabled", !C.cboTransactionType.Text() || !C.dateWithdrawalDate.Value() || C.numWithdrawalValue.Value() &lt;= 0);

  // Advanced Button visible?
  if (mRecord &amp;&amp; !mHasAdvancedOptions) {
    // Hide button
    cmdAdvanced.hide();

    // Remove advanced section styling for everything
    $("tr").removeClass("advanced");
  }
  else if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }

  // Resize
  tabWizard_Resize();
}

// ======================
// pagePaymentArrangement
// ======================
function pagePaymentArrangement_Refresh() {
  // Calculate if a Final Payment Date is present
  var params = CreateFinishParameters();

  if (!mLastFinishParameters || JSON.stringify(params) != mLastFinishParameters) {
    // Block UI
    widget.UI.Block("Initialising, please wait...");

    // Cache Parameters
    mLastFinishParameters = JSON.stringify(params);

    // Get Options
    widget.GetString("GetPaymentArrangementOptions", params, pagePaymentArrangement_Refresh_Done, function(errorMessage) {
      // Unblock
      widget.UI.Unblock();

      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }
}

function pagePaymentArrangement_Refresh_Done(data) {
  if (data) {
    data = JSON.parse(data);

    // Adjust Regular Payment updates
    if (!data.HasFinalPayment &amp;&amp; C.rblArrangementOptions.Value() == "AdjustRegularPayment") {
      C.rblArrangementOptions.Value("None");
    }
    C.rblArrangementOptions.ItemEnabled("AdjustRegularPayment", data.HasFinalPayment);

    // Maintain Maturity Date
    if (!data.IsAdjustRegularPaymentMaturityAvailable &amp;&amp; C.rblArrangementOptions.Value() == "AdjustRegularPaymentMaturity") {
      C.rblArrangementOptions.Value("None");
    }
    C.rblArrangementOptions.ItemEnabled("AdjustRegularPaymentMaturity", data.IsAdjustRegularPaymentMaturityAvailable);
  }

  // Update Controls
  rblArrangementOptions_Change();

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

// ======================
// pageAllocation_Refresh
// ======================
function pageAllocation_Refresh() {
  mWithdrawalAllocations = null;

  // Params
  var params = CreateFinishParameters();

  // Refresh default allocations if required
  if (JSON.stringify(mAllocationFinishParameters) != JSON.stringify(params)) {
    // Block UI
    widget.UI.Block("Initialising, please wait...");

    // Get Allocations
    widget.GetString("GetAllocations", params, pageAllocation_Refresh_Done, function(errorMessage) {
      // Unblock
      widget.UI.Unblock();

      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }
}

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

  // Controls
  if (mWithdrawalAllocations) {
    C.numPnibAllocated.Value(mWithdrawalAllocations.AllocationPrincipalNIB);
    C.numPibAllocated.Value(mWithdrawalAllocations.AllocationPrincipalIB);
    C.numIAllocated.Value(mWithdrawalAllocations.AllocationInterest);
    C.numFnibAllocated.Value(mWithdrawalAllocations.AllocationFeeNIB);
    C.numFibAllocated.Value(mWithdrawalAllocations.AllocationFeeIB);
  }

  // Calculate
  UpdateTotals();

  // Update Finish Parameters
  mAllocationFinishParameters = CreateFinishParameters();

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

// ================
// Allocate Payment
// ================
function AllocateWithdrawal(allocation) {
  // Reset
  C.numPnibAllocated.Value(0);
  C.numPibAllocated.Value(0);
  C.numIAllocated.Value(0);
  C.numFnibAllocated.Value(0);
  C.numFibAllocated.Value(0);

  // Allocate
  switch(allocation) {
    case "PNIB":
      C.numPnibAllocated.Value(C.numWithdrawalValue.Value());
      break;

    case "PIB":
      C.numPibAllocated.Value(C.numWithdrawalValue.Value());
      break;

    case "I":
      C.numIAllocated.Value(C.numWithdrawalValue.Value());
      break;

    case "FNIB":
      C.numFnibAllocated.Value(C.numWithdrawalValue.Value());
      break;

    case "FIB":
      C.numFibAllocated.Value(C.numWithdrawalValue.Value());
      break;
  }

  // Update Totals
  UpdateTotals();
}

// =================================
// Automatically Allocate Withdrawal
// =================================
function AutoAllocateWithdrawal() {
  // Reset
  AllocateWithdrawal("");

  // Withdrawal Value
  var tmpDec = C.numWithdrawalValue.Value();

  if (mWithdrawalAllocations) {
    // Fees IB
    if (mWithdrawalAllocations.BalanceFeeIB &gt; 0) {
      if (mWithdrawalAllocations.BalanceFeeIB &gt;= tmpDec) {
        C.numFibAllocated.Value(tmpDec);
        tmpDec = 0;
      }
      else {
        C.numFibAllocated.Value(mWithdrawalAllocations.BalanceFeeIB);
        tmpDec -= mWithdrawalAllocations.BalanceFeeIB;
      }
    }

    // Fees NIB
    if (tmpDec != 0 &amp;&amp; mWithdrawalAllocations.BalanceFeeNIB &gt; 0) {
      if (mWithdrawalAllocations.BalanceFeeNIB &gt;= tmpDec) {
        C.numFnibAllocated.Value(tmpDec);
        tmpDec = 0;
      }
      else {
        C.numFnibAllocated.Value(mWithdrawalAllocations.BalanceFeeNIB);
        tmpDec -= mWithdrawalAllocations.BalanceFeeNIB;
      }
    }

    // Interest
    if (tmpDec != 0 &amp;&amp; mWithdrawalAllocations.BalanceInterest &gt; 0) {
      if (mWithdrawalAllocations.BalanceInterest &gt;= tmpDec) {
        C.numIAllocated.Value(tmpDec);
        tmpDec = 0;
      }
      else {
        C.numIAllocated.Value(mWithdrawalAllocations.BalanceInterest);
        tmpDec -= mWithdrawalAllocations.BalanceInterest;
      }
    }

    // Principal IB
    if (tmpDec != 0 &amp;&amp; mWithdrawalAllocations.BalancePrincipalIB &gt; 0) {
      if (mWithdrawalAllocations.BalancePrincipalIB &gt;= tmpDec) {
        C.numPibAllocated.Value(tmpDec);
        tmpDec = 0;
      }
      else {
        C.numPibAllocated.Value(mWithdrawalAllocations.BalancePrincipalIB);
        tmpDec -= mWithdrawalAllocations.BalancePrincipalIB;
      }
    }

    // Principal NIB
    if (tmpDec != 0 &amp;&amp; mWithdrawalAllocations.BalancePrincipalNIB &gt; 0) {
      if (mWithdrawalAllocations.BalancePrincipalNIB &gt;= tmpDec) {
        C.numPnibAllocated.Value(tmpDec);
        tmpDec = 0;
      }
      else {
        C.numPnibAllocated.Value(mWithdrawalAllocations.BalancePrincipalNIB);
        tmpDec -= mWithdrawalAllocations.BalancePrincipalNIB;
      }
    }
  }

  // Update Totals
  UpdateTotals();
}

// ========================
// Update Allocation Totals
// ========================
function UpdateTotals() {
  if (mWithdrawalAllocations) {
    // New Column
    mWithdrawalAllocations.NewPrincipalNIB = (mWithdrawalAllocations.BalancePrincipalNIB - C.numPnibAllocated.Value());
    mWithdrawalAllocations.NewPrincipalIB = (mWithdrawalAllocations.BalancePrincipalIB - C.numPibAllocated.Value());
    mWithdrawalAllocations.NewInterest = (mWithdrawalAllocations.BalanceInterest - C.numIAllocated.Value());
    mWithdrawalAllocations.NewFeeNIB = (mWithdrawalAllocations.BalanceFeeNIB - C.numFnibAllocated.Value());
    mWithdrawalAllocations.NewFeeIB = (mWithdrawalAllocations.BalanceFeeIB - C.numFibAllocated.Value());

    // Totals
    mWithdrawalAllocations.TotalBalance = (mWithdrawalAllocations.BalancePrincipalNIB + mWithdrawalAllocations.BalancePrincipalIB + mWithdrawalAllocations.BalanceInterest + mWithdrawalAllocations.BalanceFeeNIB + mWithdrawalAllocations.BalanceFeeIB);
    mWithdrawalAllocations.TotalAllocations = (C.numPnibAllocated.Value() + C.numPibAllocated.Value() + C.numIAllocated.Value() + C.numFnibAllocated.Value() + C.numFibAllocated.Value());
    mWithdrawalAllocations.TotalNew = (mWithdrawalAllocations.NewPrincipalNIB + mWithdrawalAllocations.NewPrincipalIB + mWithdrawalAllocations.NewInterest + mWithdrawalAllocations.NewFeeNIB + mWithdrawalAllocations.NewFeeIB);

    // Allocation Remaining
    mWithdrawalAllocations.TotalRemaining = (C.numWithdrawalValue.Value() - mWithdrawalAllocations.TotalAllocations);
  }

  // Evaluate
  widget.UI.Evaluate(C.tblManualAllocation);
}

// ==================
// cboTransactionType
// ==================
function cboTransactionType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Controls
  C.wbAccountSummary.Clear();
  cmdSchedule.prop("disabled", true);

  // Refresh Form
  if (C.cboTransactionType.Text()) {
    var params = CreateFinishParameters();
    params.RecalculatePaymentFee = true;
    params.TransactionTypeChanged = true;

    widget.GetString("Form_Withdrawal_Change", params,
      function(data) {
        Withdrawal_Change_Done(data);
      },
      Withdrawal_Change_Fail);
  }
  else {
    // No Transaction Type selected - tidy up Manual Allocation (handling will differ depending on Advanced status)
    mRecord.CanManuallyAllocate = false;
    mRecord.ShowManualAllocation = "False";
    C.chkManualAllocation.Value(false);
    
    // Refresh page
    pageGeneral_Refresh();
  }
}

// ============
// cboPayeeType
// ============
function cboPayeeType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  pageGeneral_Refresh();
}

// ===================
// chkManualAllocation
// ===================
function chkManualAllocation_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Buttons
  tabWizard_UpdateButtons();
}

// ===========
// numFeeValue
// ===========
function numFeeValue_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  if (e &amp;&amp; C.chkFeeCharge.Value() &amp;&amp; C.numWithdrawalValue.Value() != 0) {
    wbAccountSummary_Refresh(false);
  }
}

// ============
// chkFeeCharge
// ============
function chkFeeCharge_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  C.numFeeValue.ReadOnly(!mRecord.CanChangeFee || !C.chkFeeCharge.Value());

  // Refresh Summary
  if (e &amp;&amp; C.numWithdrawalValue.Value() != 0) wbAccountSummary_Refresh(false);
}

// ============
// numAllocated
// ============
function numAllocated_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Calculate
  UpdateTotals();
}

// ====================
// numRegularPaymentNew
// ====================
function numRegularPaymentNew_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Refresh Summary
  wbPaymentArrangementSummary_Refresh();
}

// ==================
// numWithdrawalValue
// ==================
function numWithdrawalValue_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Refresh Summary
  if (e) wbAccountSummary_Refresh(true);
}

// ===========
// dateWithdrawalDate
// ===========
function dateWithdrawalDate_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Refresh Summary
  if (e) wbAccountSummary_Refresh(false);
}

// ==================
// numPaymentFeeValue
// ==================
function numPaymentFeeValue_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  C.numPaymentFeeValue.ReadOnly(!mRecord.CanChangePaymentFee || !C.chkPaymentFeeCharge.Value());

  // Refresh Summary
  if (e) wbAccountSummary_Refresh(false);
}

// =====================
// rblArrangementOptions
// =====================
function rblArrangementOptions_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Payment Value
  C.numRegularPaymentNew.VisibleRow(C.rblArrangementOptions.Value() == "OverrideRegularPayment");

  // Refresh Summary
  wbPaymentArrangementSummary_Refresh();
}

// =================
// apdPaymentDetails
// =================
function apdPaymentDetails_PaymentMethodChange(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Show/Hide Fee
  C.numPaymentFeeValue.VisibleRow(C.apdPaymentDetails.SelectedPaymentMethodHasFee());
  C.numPaymentFeeValue.Value(mRecord.PaymentFeeValue);

  // Refresh Summary
  // NOTE: We need to recalculate the Payment Fee since this is based on the Payment Method
  if (e) wbAccountSummary_Refresh(true);
}

// ================
// wbAccountSummary
// ================
function wbAccountSummary_Refresh(recalculatePaymentFee) {
  // Update Controls
  C.wbAccountSummary.Clear();
  cmdSchedule.prop("disabled", true);

  if (C.dateWithdrawalDate.Value() &amp;&amp; C.numWithdrawalValue.Value()) {
    if (mRefreshTimer) {
      window.clearTimeout(mRefreshTimer);
      mRefreshTimer = null;
    }

    // Refresh after 500ms
    mRefreshTimer = window.setTimeout(function () {
      var params = CreateFinishParameters();
      params.RecalculatePaymentFee = recalculatePaymentFee || C.numFeeValue.ReadOnly();

      widget.GetString("Form_Withdrawal_Change", params,
        function(data) {
          Withdrawal_Change_Done(data);
        }
      ,
      Withdrawal_Change_Fail);
    }, 500);
  }
  else {
    C.wbAccountSummary.Clear();
  }
}

function Withdrawal_Change_Done(data) {
  if (data) {
    // Parse
    var o = JSON.parse(data);

    // Update mRecord
    mRecord.AccountSummaryHtml = o.AccountSummaryHtml;
    mRecord.CanChangeFee = o.CanChangeFee;
    mRecord.CanChangePaymentFee = o.CanChangePaymentFee;
    mRecord.CanManuallyAllocate = o.CanManuallyAllocate;
    mRecord.CanPrintAdvice = o.CanPrintAdvice;
    mRecord.FeeValue = o.FeeValue;
    mRecord.Notes = o.Notes;
    mRecord.PaymentFeeValue = o.PaymentFeeValue;
    mRecord.PrintAdvice = o.PrintAdvice;
    mRecord.Reference = o.Reference;
    mRecord.ShowDisbursement = o.ShowDisbursement;
    mRecord.ShowPaymentArrangementPage = o.ShowPaymentArrangementPage;
    mRecord.ShowManualAllocation = o.ShowManualAllocation;

    // Don't update the Transaction Type - this may cause a previously non-advanced option jump to advanced and disappear. This appears very disjointed for the User
    //mRecord.ShowTransactionType = o.ShowTransactionType;

    // Update Controls
    C.numFeeValue.Value(mRecord.FeeValue);
    C.txtReference.Text(mRecord.Reference);
    C.txtNotes.Text(mRecord.Notes);
    C.numPaymentFeeValue.Value(mRecord.PaymentFeeValue);
    C.chkPrintAdvice.Value(mRecord.PrintAdvice);

    // Refresh Page
    pageGeneral_Refresh();

    // Update Buttons
    tabWizard_UpdateButtons();

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

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

// =====================
// 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: mRecord.WithdrawalOrRefund });
    },

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

// ===========================
// wbPaymentArrangementSummary
// ===========================
function wbPaymentArrangementSummary_Refresh() {
  // Update Controls
  C.wbPaymentArrangementSummary.Clear();

  // Clear Timer
  if (mRefreshTimerPaymentArrangement) {
    window.clearTimeout(mRefreshTimerPaymentArrangement);
    mRefreshTimerPaymentArrangement = null;
  }

  // Parameters
  var params = CreateFinishParameters();

  // Create Cache Key
  // NOTE: We cache the summary since it may be quite time-consuming
  var cacheKey = JSON.stringify(params);

  // Use Cache?
  var html = mSummaryCache[cacheKey];
  if (html) {
    C.wbPaymentArrangementSummary.SetContent(html, false);
  }
  else {
    // Refresh after 500ms
    mRefreshTimerPaymentArrangement = window.setTimeout(function () {
      // Calculate
      widget.GetString("CalculatePaymentArrangement", params, function(data) {
        C.wbPaymentArrangementSummary.SetContent(data, false);

        // Cache
        mSummaryCache[cacheKey] = data;
      });
    }, 500);
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>b-3-ZZHZiEqZGyqhEhsrvg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</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="DefaultTransactionTypeId" type="Range">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>TransactionTypes</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="ShowTransactionType" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowManualAllocation" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>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="IsRefund" 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>