<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-07T04:23:10.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-11-18T20:40:56.0030000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-07T04:22:54.2300000</UpdatedUtcDate>
    <ScriptId>APR</ScriptId>
    <Description>Account Payment</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountPayment
Option Explicit On
Option Strict On

' #################################################################
' Account Payment Received wizard HTML Widget
'
' Version: 1.17 (07/08/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.12  10/08/2021  ISS                Updated
'    1.13  11/04/2022  ISS      J028437   Zepto (Split) improvements
'    1.14  22/12/2022  ISS      J029509   New Transaction Type Permission Keys
'          13/01/2022  ISS      J030238   Updated Account Financial control to use AccountIncomingPaymentDetails
'          27/01/2023  ISS      J030146   Updated Initialise Parameters for AccountIncomingPaymentDetails control
'    1.15  02/10/2023  ISS      J031947   Added 'Don't adjust Overdue?' checkbox on Allocations page
'    1.16  30/01/2024  ISS      J032818   Updated Permission Keys
'    1.17  07/08/2024  ISS      J032513   Allocation page now takes Fee into consideration for the total amount
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountPayment"

' Common Parameters
Private mAccountId 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")
  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 "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, requestInfo, returnValue)

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

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

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

    Case "Form_Payment_Change"
      ' Get updated form information based on Payment Date or Value changing
      Main = Form_Payment_Change(parametersJson, returnValue)

    Case "GetAccountSchedule"
      ' Get Account Schedule for the button next to the Payment Date
      Main = GetAccountSchedule(parametersJson, returnValue)

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

End Function

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

  Dim AccountPayment As finAccountPayment
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Payment
  If Success Then
    Success = CreateAccountPayment(WizardFinishParameters, AccountPayment)
  End If

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

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

  If Success Then
    ' General Properties
    FormInitialisationInfo = New FormInitialisationInfo()
    FormInitialisationInfoUpdate(AccountPayment, 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 Account Schedule for the button next to the Payment Date
''' &lt;/summary&gt;
Public Function GetAccountSchedule(parametersJson As String,
                                    ByRef response As String) As Boolean

  Dim AccountPayment As finAccountPayment
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Payment
  If Success Then
    Success = CreateAccountPayment(WizardFinishParameters, AccountPayment)
  End If

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

  ' Get Schedule
  If Success Then
    response = AccountPayment.Calculation.Schedule.ToHtmlWidgetJsonString()
  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 AccountPayment As finAccountPayment
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Payment
  If Success Then
    If CreateAccountPayment(WizardFinishParameters, AccountPayment) Then
      Success = AccountPayment.Calculate()
    Else
      Success = False
    End If
  End If

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

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  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 AccountPayment As finAccountPayment
  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 Not finBL.CurrentUser.Permissions.Allow("Account.Payment") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to process an Account Payment.")
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  End If

  ' Create Account Payment object
  If Success Then
    Success = CreateAccountPayment(Nothing, AccountPayment)

    ' Update defaults
    Select Case AccountPayment.Account.AccountClass
      Case isefinAccountClass.Deposit
        If Len(mCombinedParameters.GetString("DefaultDepositTransactionTypeId")) &lt;&gt; 0 Then
          AccountPayment.TransactionTypeIdUpdate(mCombinedParameters.GetString("DefaultDepositTransactionTypeId"))
        End If
      Case Else
        If Len(mCombinedParameters.GetString("DefaultLoanTransactionTypeId")) &lt;&gt; 0 Then
          AccountPayment.TransactionTypeIdUpdate(mCombinedParameters.GetString("DefaultLoanTransactionTypeId"))
        End If
    End Select
    If mCombinedParameters.GetCurrency("PaymentValue") &lt;&gt; 0 Then
      AccountPayment.PaymentValue =  mCombinedParameters.GetCurrency("PaymentValue")
    End If
  End If

    ' Validate Transaction Type
  If Success Then
    If finBL.TransactionTypes.GetDataView(dv, "", False, AccountPayment.TransactionTypeDataViewFilter(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
        AccountPayment.TransactionTypeIdUpdate(finBL.Database.GetFieldString(dv(0)!TransactionTypeId))
      ElseIf AccountPayment.TransactionTypePk &lt;&gt; 0 Then
        ' Check Transaction Type is valid
        Found = False
        For i = 0 To dv.Count - 1
          If AccountPayment.TransactionTypePk = finBL.Database.GetFieldInteger(dv(i)!Pk) Then
            Found = True
            Exit For
          End If
        Next
        If Not Found Then
          AccountPayment.TransactionTypeIdUpdate("")
        End If
      End If
    End If
  End If

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

    ' Other Properties
    With FormInitialisationInfo
      ' Lists
      .AccountTransactionPaymentAllocationMethodList = finBL.Enums.isefinAccountTransactionPaymentAllocationMethod_ToCodeDescriptionList().ToJsonObject()

      ' List Filters
      .TransactionTypesFilter = AccountPayment.TransactionTypeDataViewFilter(True)

      ' Configuration
      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

      If .CanManuallyAllocate Then
        .ShowManualPayment = mCombinedParameters.GetString("ShowManualPayment")
        If Len(.ShowManualPayment) = 0 Then .ShowManualPayment = "Advanced"
      Else
        .ShowManualPayment = "False"
      End If

      Select AccountPayment.Account.AccountClass
        Case isefinAccountClass.Deposit
          .ShowAllocationMethod = "False"
        Case Else
          .ShowAllocationMethod = mCombinedParameters.GetString("ShowAllocationMethod")
          If Len(.ShowAllocationMethod) = 0 Then .ShowAllocationMethod = "True"
          Select Case AccountPayment.Account.Calculation.OptionPaymentAllocationMethod
            Case isefinAccountPaymentAllocationMethod.FeesAndInterestOnly, isefinAccountPaymentAllocationMethod.InterestOnly
              If .ShowAllocationMethod = "False" Then .ShowAllocationMethod = "True"
            Case Else
              .ShowAllocationMethod = "False"
          End Select
      End Select
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Gets 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
  wizardFinishParameters = Nothing

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

  Return Success

End Function

Private Sub FormInitialisationInfoUpdate(accountPayment As finAccountPayment,
                                         formInitialisationInfo As FormInitialisationInfo)

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

    ' General
    .TransactionTypeId = accountPayment.TransactionTypeId
    .PaymentDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(accountPayment.PaymentDate)
    .PaymentValue = accountPayment.PaymentValueResolved
    .AllocationMethodPaymentText = accountPayment.AllocationMethodPaymentText
    .Reference = accountPayment.TransactionReference
    .Notes = accountPayment.TransactionNotes
    .PaymentFeeValue = accountPayment.PaymentFeeValue
    .PaymentFeeValueResolved = accountPayment.PaymentFeeValueResolved
    .PaymentFeeCharge = accountPayment.PaymentFeeCharge
    .PrintReceipt = accountPayment.PrintReceipt
    .OverdueHold = accountPayment.OverdueHold

    ' Account Summary
    .AccountSummaryHtml = finBL.SummaryPageFunctions.AccountPaymentSummary(False, AccountPayment, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))

    ' Other Configuration
    .CanChangePaymentFee = accountPayment.PaymentFeeAllowChange
    Select AccountPayment.Account.AccountClass
      Case isefinAccountClass.Deposit
        .CanManuallyAllocate = False
      Case Else
        .CanManuallyAllocate = finBL.CurrentUser.Permissions.Allow("Account.Payment.ManualAllocation")
    End Select
    .SupportsOverdue = accountPayment.Account.SupportsOverdue
    .CanPrintReceipt = Len(accountPayment.GetDocumentId(True)) &lt;&gt; 0
    .PaymentDetailsSmartLookup = mCombinedParameters.GetBoolean("PaymentDetailsSmartLookup", True)
    .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    .ShowCashRegister = (finBL.Settings.AddOns.BankingAdvanced AndAlso finBL.CashRegisters.Count &lt;&gt; 0)
  End With

End Sub

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

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  AccountPayment = finBL.CreateAccountPayment()

  ' Update
  If Success Then
    With AccountPayment
      ' Load Account
      Success = .AccountLoad(mAccountId)

      ' Update
      If Success AndAlso parameters IsNot Nothing Then
        ' Banking Details
        If Success Then
          Success = .BankingDetails.FromHtmlWidgetJsonString(parameters.BankingDetailsJson)
        End If

        ' General
        If Success Then
          .AllocationMethodPaymentText = parameters.AllocationMethodPaymentText
          .CashRegisterId = parameters.CashRegisterId
          .PaymentDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.PaymentDate)
          .PaymentValue = parameters.PaymentValue
          .PaymentFeeCharge = parameters.PaymentFeeCharge
          .PaymentFeeValue = parameters.PaymentFeeValue
          .TransactionTypeId = parameters.TransactionTypeId

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

          ' Set after TransactionTypeId since this updates the values
          .TransactionReference = parameters.Reference
          .TransactionNotes = parameters.Notes
          .PrintReceipt = parameters.PrintReceipt
        Else
          Success = False
        End If
      End If
    End With
  End If

  Return Success

End Function

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

  Dim AccountPayment As finAccountPayment
  Dim BankInterfaceRequestMessage As String
  Dim BankInterfaceRequestSent As Boolean
  Dim ReceiptDocumentId As String
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Payment object
  If Success Then
    Success = CreateAccountPayment(WizardFinishParameters, AccountPayment)
  End If

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

  ' Print Receipt?
  If Success Then
    If AccountPayment.PrintReceipt Then
      ReceiptDocumentId = AccountPayment.GetDocumentId()
    Else
      ReceiptDocumentId = ""
    End If
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(BankInterfaceRequestMessage, BankInterfaceRequestSent, AccountPayment.BankTransactionPk, ReceiptDocumentId, 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 AccountPayment As finAccountPayment
  Dim Balance As Decimal
  Dim InvestmentPending As Decimal
  Dim List As ISList
  Dim strTemp As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Account Payment object
  If Success Then
    Success = CreateAccountPayment(WizardFinishParameters, AccountPayment)
  End If

  If Success Then
    Select Case AccountPayment.Account.AccountClass
      Case isefinAccountClass.Deposit
        ' Check Investment
        If AccountPayment.TransactionType IsNot Nothing AndAlso AccountPayment.TransactionType.ElementType = isefinElementType.Investment Then
          ' Find Investment Pending after Payment
          AccountPayment.Account.GetInvestmentDetails(0, 0, InvestmentPending)
          InvestmentPending -= AccountPayment.PaymentValue

          If InvestmentPending &gt; 0 Then
            ConfirmList.Add("Investment is UNDERPAID.")
          ElseIf InvestmentPending &lt; 0 Then
            ConfirmList.Add("Investment is OVERPAID.")
          End If
        End If

      Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
        ' Credit Balance Warning
        If AccountPayment.Calculate Then
          Balance = AccountPayment.Calculation.Schedule.GetBalance(AccountPayment.PaymentDate)

          If Balance &lt; 0 Then
            ConfirmList.Add("This will OVERPAY the Loan Account and place the Account in CREDIT.")
          End If
        Else
          ConfirmList.Add("Could not calculate Loan Account Balance.")
        End If

        ' Check for early partial payment
        If AccountPayment.Account.AccountType.PaymentEarlyPartialRepaymentWarning Then
          AccountPayment.Account.GetBalanceOverdue(Balance, AccountPayment.PaymentDate)

          If AccountPayment.PaymentValue &gt; Balance Then
            ConfirmList.Add("This Loan Account does not allow partial early payments.")
          End If
        End If
    End Select

    ' Validate Banking Details
    If Not AccountPayment.BankingDetails.IsValidForTransaction(List, AccountPayment.PaymentDate) Then
      For Each strTemp In List
        ConfirmList.Add(strTemp)
      Next
    End If
  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 AllocationMethodPaymentText As String
  Public BankingDetailsJson As String
  Public Notes As String
  Public OverdueHold As Boolean
  Public PaymentDate As Date
  Public PaymentFeeCharge As Boolean
  Public PaymentFeeValue As Decimal
  Public PaymentFeeValueResolved As Decimal
  Public PaymentValue As Decimal
  Public PrintReceipt As Boolean
  Public Reference As String
  Public TransactionTypeId As String

  ' Account Summary
  Public AccountSummaryHtml As String

  ' Lists
  Public AccountTransactionPaymentAllocationMethodList As Object

  ' List Filters
  Public TransactionTypesFilter As String
  
  ' Configuration  
  Public CanChangePaymentFee As Boolean
  Public CanManuallyAllocate As Boolean
  Public CanPrintReceipt As Boolean
  Public PaymentDetailsSmartLookup As Boolean
  Public PromptOnCommit As Boolean
  Public ShowAllocationMethod As String
  Public ShowCashRegister As Boolean
  Public ShowManualPayment As String
  Public ShowTransactionType As String
  Public SupportsOverdue As Boolean

End Class


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

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

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

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

  End Sub

End Class


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

  ' General
  Public AllocationMethodPaymentText As String
  Public BankingDetailsJson As String
  Public CashRegisterId As String
  Public Notes As String
  Public PaymentValue As Decimal
  Public PaymentFeeCharge As Boolean
  Public PaymentFeeValue As Decimal
  Public PaymentDate As Date
  Public PrintReceipt As Boolean
  Public Reference As String
  Public TransactionTypeId As String

  ' 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
  
  Public OverdueHold As Boolean

  ' 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 ReceiptDocumentId As String
  Public Warning As String

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

    Me.BankInterfaceRequestMessage = bankInterfaceRequestMessage
    Me.BankInterfaceRequestSent = bankInterfaceRequestSent
    Me.BankTransactionPk = bankTransactionPk
    Me.ReceiptDocumentId = receiptDocumentId
    Me.Warning = warning

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountPayment".</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" tooltipText="Enter details of the Payment being made."&gt;Payment Received&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"&gt;
      &lt;table class="is-form" style="height:100%"&gt;

        &lt;tr&gt;&lt;td&gt;
          &lt;!-- Chrome sizing issue (May-2018) requires use of a sub-table --&gt;
          &lt;table class="is-form"&gt;
            &lt;colgroup&gt;
              &lt;col style="width:10em" /&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="lblPaymentDetails"&gt;Payment 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="datePaymentDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="datePaymentDate"/&gt; &lt;button id="cmdSchedule" class="is-button small" icon="Schedule"&gt;Schedule&lt;/button&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="numPaymentValue"&gt;Payment:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="numPaymentValue"/&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 id="trAllocationMethod"&gt;
              &lt;th&gt;&lt;label for="cboAllocationMethod"&gt;Allocation:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboAllocationMethod"/&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblTransactionDetails"&gt;Transaction details&lt;/label&gt;&lt;/th&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="chkPrintReceipt"&gt;Print Receipt:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="chkPrintReceipt" type="checkbox" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPaymentMethod"&gt;Payment Method&lt;/label&gt;&lt;/th&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;tr style="display:none"&gt;
              &lt;th&gt;&lt;label for="numTotalPayment"&gt;Net&amp;nbsp;Payment:&lt;/label&gt;&lt;/th&gt;
              &lt;td colspan="2"&gt;&lt;input id="numTotalPayment"/&gt;&lt;label id="lblPaymentFeeMessage" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/td&gt;&lt;/tr&gt;

        &lt;tr style="height:100%"&gt;
          &lt;td colspan="2" style="height:100%; padding-top:8px"&gt;&lt;div id="wbAccountSummary" class="is-dock-fill"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&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(mPaymentAllocations.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(mPaymentAllocations.NewPrincipalNIB, true, false)" ng-class="mPaymentAllocations.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(mPaymentAllocations.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(mPaymentAllocations.NewPrincipalIB, true, false)" ng-class="mPaymentAllocations.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(mPaymentAllocations.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(mPaymentAllocations.NewInterest, true, false)" ng-class="mPaymentAllocations.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(mPaymentAllocations.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(mPaymentAllocations.NewFeeNIB, true, false)" ng-class="mPaymentAllocations.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(mPaymentAllocations.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(mPaymentAllocations.NewFeeIB, true, false)" ng-class="mPaymentAllocations.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(mPaymentAllocations.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(mPaymentAllocations.TotalBalance, true, false)"&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mPaymentAllocations.TotalAllocations, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mPaymentAllocations.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;tr&gt;
          &lt;th colspan="2" style="padding-top: 8px !important"&gt;&lt;label id="lblAllocationOtherOptions"&gt;Other options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkDoNotAdjustOverdue" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;
    &lt;span class="is-info-text wizard-footer" style="display:none"&gt;You will be prompted to print a receipt upon finishing.&lt;/span&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;

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

  lblPaymentDetails: null,
  trTransactionType: null,
  cboTransactionType: null,
  datePaymentDate: null,
  numPaymentValue: null,
  lblTransactionDetails: null,
  txtReference: null,
  txtNotes: null,
  chkPrintReceipt: null,
  trManualAllocation: null,
  chkManualAllocation: null,
  trAllocationMethod: null,
  cboAllocationMethod: null,

  lblPaymentMethodDetails: null,
  apdPaymentDetails: null,

  numPaymentFeeValue: null,
  chkPaymentFeeCharge: null,
  numTotalPayment: null,
  lblPaymentFeeMessage: null,

  wbAccountSummary: null,

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

// Form
var frmMain;
var tabWizard;

// Other
var mValueData;
var mAllocationFinishParameters;
var mPaymentAllocations;

// 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 mCompact = false;
var mHasAdvancedOptions = false;
var mRefreshTimer;

// ==========
// Initialise
// ==========
$(function () {
  // Mobile optimisations
  var currencyWidth = "20em";
  $(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.lblPaymentDetails = widget.UI.Label("lblPaymentDetails", {});
  C.trTransactionType = $("#trTransactionType");
  C.cboTransactionType = widget.UI.DBCombo("cboTransactionType", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

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

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

    onChange: chkManualAllocation_Change,
  });
  C.numPaymentValue = widget.UI.NumberBox("numPaymentValue", {
    allowBlank: false,
    blankIfZero: true,
    minValue: 0,
    maxValue: 999999999999,

    onChange: numPaymentValue_Change,
  });
  C.lblTransactionDetails = widget.UI.Label("lblTransactionDetails", {});
  C.txtReference = widget.UI.TextBox("txtReference", {
    maxLength: 20
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 4,
    maxLength: 255
  });
  C.chkPrintReceipt = widget.UI.CheckBox("chkPrintReceipt", {
    caption: "Print Receipt?",
  });
  C.trAllocationMethod = $("#trAllocationMethod");
  C.cboAllocationMethod = widget.UI.ComboBox("cboAllocationMethod", {
    allowBlank: false,

    onChange: cboAllocationMethod_Change,
  });

  C.lblPaymentMethod = widget.UI.Label("lblPaymentMethod", {});
  C.apdPaymentDetails = widget.UI.AccountIncomingPaymentDetails("apdPaymentDetails", {
    hideSplitAddButton: true,
    paymentEntry: true,
    resolveReference: true,

    onPaymentMethodChange: apdPaymentDetails_PaymentMethodChange,
  });

  C.numPaymentFeeValue = widget.UI.NumberBox("numPaymentFeeValue", {
    allowBlank: false,
    minValue: 0,
    maxValue: 999999999999,

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

    onChange: numPaymentFeeValue_Change,
  });
  C.numTotalPayment = widget.UI.NumberBox("numTotalPayment", {
    autoReadOnly: false,
    allowBlank: true,
    readOnly: true,
    minValue: 0,
    maxValue: 999999999999,
  });
  C.lblPaymentFeeMessage = widget.UI.Label("lblPaymentFeeMessage", {
    style: "information"
  });

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

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

  C.lblAllocationOtherOptions = widget.UI.Label("lblAllocationOtherOptions", {});
  C.chkDoNotAdjustOverdue = widget.UI.CheckBox("chkDoNotAdjustOverdue", {
    caption: "Don't adjust Overdue?",
  });

  // Grids

  // Create Widget form
  // NOTE: Hide by default for a cleaner startup
  frmMain = new widget.UI.Form("frmMain", { captionWidth: "9em", textboxWidth: "20em", 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() { AllocatePayment("PNIB"); });
  cmdAllocatePib.click(function() { AllocatePayment("PIB"); });
  cmdAllocateI.click(function() { AllocatePayment("I"); });
  cmdAllocateFnib.click(function() { AllocatePayment("FNIB"); });
  cmdAllocateFib.click(function() { AllocatePayment("FIB"); });

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

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  C.numPaymentFeeValue.ReadOnly(true);
  C.chkPaymentFeeCharge.Value(true);
  C.lblPaymentFeeMessage.Visible(false);

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mAllocationFinishParameters = 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.datePaymentDate.Value(mRecord.PaymentDate);
    C.numPaymentValue.Value(mRecord.PaymentValue);
    C.txtReference.Text(mRecord.Reference);
    C.txtNotes.Text(mRecord.Notes);
    C.chkPrintReceipt.Value(mRecord.PrintReceipt);
    C.cboAllocationMethod.Text(mRecord.AllocationMethodPaymentText);

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

    C.wbAccountSummary.SetContent(mRecord.AccountSummaryHtml, false);
    
    // Allocation
    C.chkDoNotAdjustOverdue.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() {
  // Information Lists

  // Lists
  if (mRecord) {
    C.cboTransactionType.RefreshFromStandardRange("TransactionTypes", mRecord.TransactionTypesFilter);
    C.cboAllocationMethod.ListFromCollection(mRecord.AccountTransactionPaymentAllocationMethodList, "Description");
  }

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

    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.ShowManualPayment.toUpperCase()) {
      case "TRUE":
        C.chkManualAllocation.VisibleRow(true);
        break;
      case "FALSE":
        C.chkManualAllocation.VisibleRow(false);
        break;
      case "ADVANCED":
        C.trManualAllocation.addClass("advanced");
        break;
    }

    switch(mRecord.ShowAllocationMethod.toUpperCase()) {
      case "TRUE":
        C.cboAllocationMethod.VisibleRow(true);
        break;
      case "FALSE":
        C.cboAllocationMethod.VisibleRow(false);
        break;
      case "ADVANCED":
        C.trAllocationMethod.addClass("advanced");
        break;
    }

    chkManualAllocation_Change();
    cboAllocationMethod_Change();
    apdPaymentDetails_PaymentMethodChange();
  }

  // Check for Advanced options
  mHasAdvancedOptions = false;
  if (mRecord) {
    if (mRecord.ShowTransactionType.toUpperCase() == "ADVANCED") mHasAdvancedOptions = true;
    if (mRecord.ShowManualPayment.toUpperCase() == "ADVANCED") mHasAdvancedOptions = true;
    if (mRecord.ShowAllocationMethod.toUpperCase() == "ADVANCED") mHasAdvancedOptions = true;
  }

  // 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

  // Mobile optimisations
  if(window.innerWidth &lt; 500) {
    // Collapse first column since it does not require data-entry
    var e = $("#pageAllocations&gt; table col");
    $(e[1]).css({width:""});
  }
  else {
    var e = $("#pageAllocations &gt; table col");
    $(e[1]).css({width:"15em"});
  }

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

  // Exceptions
  if (C.chkManualAllocation.Value() &amp;&amp; tabIndex == 0) {
    cmdNext.prop("disabled", false);
  }
  else {
    cmdNext.prop("disabled", true);
  }

  // Finish Button
  if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

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

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

      default:
        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(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter details of the Payment being made to Account '" + mRecord.RecordId + "', " + mRecord.RecordDescription + ".");
      }
      else {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter details of the Payment being made.");
      }
      break;

    case "Allocation":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter allocation details for a Payment of " + widget.FormatCurrency(C.numTotalPayment.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.numTotalPayment.Value() != mPaymentAllocations.TotalAllocations) {
          Ok = false;
          widget.UI.MsgBoxAlert("The total value allocated does not equal the Payment 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 Payment";
      var message = "";
      var payment = C.numPaymentValue.Value();
      var fee = 0;
      if (C.chkPaymentFeeCharge.Value() &amp;&amp; mRecord.PaymentFeeValueResolved != 0) {
        fee = mRecord.PaymentFeeValueResolved;
      }
      if (fee) {
        message = "Are you sure you want to make a payment of " + widget.FormatCurrency(payment, true) + "?\n\nNOTE: A payment fee of " + widget.FormatCurrency(fee, true) + " will be added for a total Payment of " + widget.FormatCurrency(payment + fee, true) + ".";
      }
      else {
        message = "Are you sure you want to make a payment of " + widget.FormatCurrency(payment, true) + "?";
      }

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

function CreateFinishParameters() {
  var params = {
    // General
    TransactionTypeId: C.cboTransactionType.Text(),
    PaymentDate: C.datePaymentDate.Value(),
    PaymentValue: C.numPaymentValue.Value(),
    PaymentFeeCharge: C.chkPaymentFeeCharge.Value(),
    PaymentFeeValue: C.numPaymentFeeValue.Value(),
    Reference: C.txtReference.Text(),
    Notes: C.txtNotes.Text(),
    PrintReceipt: C.chkPrintReceipt.Value(),
    AllocationMethodPaymentText: C.cboAllocationMethod.Text(),

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

    // Allocation
    ManualAllocation: C.chkManualAllocation.Value(),
    ManualAllocationPnib: C.numPnibAllocated.Value(),
    ManualAllocationPib: C.numPibAllocated.Value(),
    ManualAllocationI: C.numIAllocated.Value(),
    ManualAllocationFnib: C.numFnibAllocated.Value(),
    ManualAllocationFib: C.numFibAllocated.Value(),
    
    OverdueHold: C.chkDoNotAdjustOverdue.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 Payment 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 Receipt?
  if(data.ReceiptDocumentId) {
    // Print via Application Shortcut
    widget.ExecuteApplicationShortcutUrl("app://Document?id=" + encodeURI(data.ReceiptDocumentId) + "&amp;BankTransactionPk=" + data.BankTransactionPk);
  }

  // Close Form
  widget.Close();

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

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Controls
  if (mRecord) {
    C.chkPrintReceipt.VisibleRow(mRecord.CanPrintReceipt);
    C.numPaymentFeeValue.ReadOnly(!mRecord.CanChangePaymentFee);

    numTotalPayment_Refresh();
  }

  cmdSchedule.prop("disabled", (!C.cboTransactionType.Text() || C.datePaymentDate.Value() == null || C.numPaymentValue.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();
}

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

  // Supports Overdue?
  C.lblAllocationOtherOptions.VisibleRow(mRecord.SupportsOverdue);
  C.chkDoNotAdjustOverdue.VisibleRow(mRecord.SupportsOverdue);

  // 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) mPaymentAllocations = JSON.parse(data);

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

  // Calculate
  UpdateTotals();

  // Update Finish Parameters
  mAllocationFinishParameters = CreateFinishParameters();

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

// ==============================
// Automatically Allocate Payment
// ==============================
function AutoAllocatePayment() {
  // Reset
  AllocatePayment("");

  // Payment Value
  var tmpDec = C.numTotalPayment.Value();

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

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

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

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

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

  // Update Totals
  UpdateTotals();
}

// ================
// Allocate Payment
// ================
function AllocatePayment(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.numTotalPayment.Value());
      break;

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

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

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

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

  // Update Totals
  UpdateTotals();
}

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

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

    // Allocation Remaining
    mPaymentAllocations.TotalRemaining = (C.numTotalPayment.Value() - mPaymentAllocations.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);
  numTotalPayment_Refresh();

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

    widget.GetString("Form_Payment_Change", params,
      function(data) {
        Form_Payment_Change(data);
      },
      Payment_Change_Fail);
  }
}

// ===================
// chkManualAllocation
// ===================
function chkManualAllocation_Change(sender, e) {
  // Update Controls
  C.cboAllocationMethod.VisibleRow(!C.chkManualAllocation.Value() &amp;&amp; mRecord.ShowAllocationMethod.toUpperCase() != "FALSE");

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

  // Update Buttons
  tabWizard_UpdateButtons();
}

// ===================
// cboAllocationMethod
// ===================
function cboAllocationMethod_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

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

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

  // Calculate
  UpdateTotals();
}

// ===============
// numPaymentValue
// ===============
function numPaymentValue_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

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

// ===============
// datePaymentDate
// ===============
function datePaymentDate_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;

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

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

  // Show/Hide Fee
  C.numPaymentFeeValue.VisibleRow(C.apdPaymentDetails.SelectedPaymentMethodHasFee());
  C.numTotalPayment.Visible(C.apdPaymentDetails.SelectedPaymentMethodIsDirectDebit() &amp;&amp; C.apdPaymentDetails.SelectedPaymentMethodHasFee());

  // Dynamically remove heading. Row may still be required for information label
  if(C.numTotalPayment.Visible()) {
    C.numTotalPayment.Caption("Net Payment:");
  }
  else {
    C.numTotalPayment.Caption("");
  }

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

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

  if ((C.datePaymentDate.Value() &amp;&amp; C.numPaymentValue.Value()) || forcePaymentFeeRecalculate) {
    // Delayed refresh
    if (mRefreshTimer) {
      window.clearTimeout(mRefreshTimer);
      mRefreshTimer = null;
    }

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

      widget.GetString("Form_Payment_Change", params,
        function(data) {
          Form_Payment_Change(data);
        }
      ,
      Payment_Change_Fail);
    }, 500);
  }
  else {
    C.wbAccountSummary.Clear();
  }
}

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

    // Update mRecord
    mRecord.AccountSummaryHtml = o.AccountSummaryHtml;
    mRecord.CanChangePaymentFee = o.CanChangePaymentFee;
    mRecord.CanPrintReceipt = o.CanPrintReceipt;
    mRecord.Notes = o.Notes;
    mRecord.PaymentFeeValue = o.PaymentFeeValue;
    mRecord.PaymentFeeValueResolved = o.PaymentFeeValueResolved;
    mRecord.PaymentValue = o.PaymentValue;
    mRecord.PrintReceipt = o.PrintReceipt;
    mRecord.Reference = o.Reference;

    // Update Controls
    C.txtReference.Text(mRecord.Reference);
    C.txtNotes.Text(mRecord.Notes);
    C.chkPrintReceipt.Value(mRecord.PrintReceipt);
    C.numPaymentFeeValue.Value(mRecord.PaymentFeeValue);

    pageGeneral_Refresh();

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

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

// =============
// numTotalPayment
// =============
function numTotalPayment_Refresh() {
  if(mRecord) {
    // Total Payment
    C.numTotalPayment.Value(mRecord.PaymentValue);

    // Payment Fee Message
    if(mRecord.PaymentFeeValue == mRecord.PaymentFeeValueResolved || !C.apdPaymentDetails.SelectedPaymentMethodHasFee() || !C.chkPaymentFeeCharge.Value()) {
      C.lblPaymentFeeMessage.Visible(false);
      C.numTotalPayment.VisibleRow(C.numTotalPayment.Visible());
    }
    else {
      C.lblPaymentFeeMessage.Text("Fee will be reduced to " + widget.FormatCurrency(mRecord.PaymentFeeValueResolved, true, false));
      C.lblPaymentFeeMessage.Visible(true);
      C.numTotalPayment.VisibleRow(true);
    }
  }
  else {
    // Total Payment
    C.numTotalPayment.Value(0);

    // Payment Fee Message
    C.lblPaymentFeeMessage.Visible(false);
  }
}

// =====================
// 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: "Payment Received" });
    },

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

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>UPzIGKc1oEOVVq-UUA7xag</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="DefaultLoanTransactionTypeId" type="Range">
            <BlankTip />
            <Caption>Default Transaction Type (Loan):</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="DefaultDepositTransactionTypeId" type="Range">
            <BlankTip />
            <Caption>Default Transaction Type (Deposit):</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="ShowManualPayment" 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="ShowAllocationMethod" 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>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="PaymentDetailsSmartLookup" type="Boolean">
            <BlankTip />
            <Caption>Pre-populate Payment Details when changing the Payment Method?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" 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="PaymentValue" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>Currency</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>