<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-02T04:19:02.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-04-15T00:35:25.2300000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-02T04:18:41.9300000</UpdatedUtcDate>
    <ScriptId>BANKENTRY</ScriptId>
    <Description>Bank Entry</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_BankEntry
Option Explicit On
Option Strict On

' #################################################################
' Bank Entry wizard
'
' Version: 1.10 (02/08/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.05  14/09/2021  ISS      J027381   Inactive Payment Methods
'          13/10/2021  ISS      J027518   Serialization error
'          18/10/2021  ISS      J027583   Editing Batch ID issue
'          18/10/2021  ISS      J027587   Unable to delete Batch
'          20/10/2021  ISS      J027605   Bank Sort Code review
'    1.06  08/12/2021  ISS      J027840   Spelling Correction
'    1.07  29/03/2022  ISS      J028521   Typo in parameter
'          26/04/2022  ISS      J028499   Bank Account disabled for imported Batch
'    1.08  08/09/2023  ISS      J031940   Fixed not being able to delete lines for imported batches
'                                         Fixed being able to incorrectly add new lines for imported batches
'    1.09  25/06/2024  ISS      J033780   Fixed Grid Summary refreshing issues
'    1.10  02/08/2024  ISS      J033826   Added 'Update Match' column
' #################################################################

' Constants
Private Const FORM_KEY As String = "BankEntry"

' Common Parameters
Private mBatchId As String
Private mBatchUnlockPolicy As String
Private mGridsShowBanking As Boolean
Private mGridsShowElement As Boolean
Private mTransactionLoadCountPrompt As Integer

' 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
    mBatchId = .GetString("BatchId")
    mBatchUnlockPolicy = .GetString("BatchUnlockPolicy")
    mGridsShowBanking = .GetBoolean("GridsShowBanking")
    mGridsShowElement = .GetBoolean("GridsShowElement")
    mTransactionLoadCountPrompt = .GetInteger("TransactionLoadCountPrompt")
  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 "DeleteBatch"
      ' Delete Batch
      Main = DeleteBatch(returnValue)

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

    Case "GetAccountDetails"
      ' Get Account Details
      Main = GetAccountDetails(returnValue)

    Case "GetBatchInfo"
      ' Get Batch Information
      Main = GetBatchInfo(returnValue)

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

    Case "GetTransactionPreview"
      ' Get Transaction Preview
      Main = GetTransactionPreview(returnValue)

    Case "NewBatch"
      ' Create a New Batch
      Main = NewBatch(returnValue)

    Case "RefreshBatch"
      ' Refresh Batch
      Main = RefreshBatch(parametersJson, returnValue)

    Case "SaveBatch"
      ' Save Batch
      Main = SaveBatch(parametersJson, returnValue)

    Case "UnlockBatch"
      ' Unlock Batch
      Main = UnlockBatch(returnValue)

    Case "WizardValidate"
      ' Validates the Tax Period being closed
      Main = WizardValidate(parametersJson, returnValue)

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

End Function

''' &lt;summary&gt;
'''  Builds a finBatchBank object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateBatchBank(parameters As WizardFinishParameters,
                                 ByRef batchBank As finBatchBank) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  batchBank = finBL.CreateBatchBank()

  ' Update
  If Success Then
    If parameters IsNot Nothing Then
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Commit Bank Batch.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        ByRef returnValue As String) As Boolean

  Dim BatchBank As finBatchBank
  Dim BatchBankTransaction As finBatchBankTransaction
  Dim BatchPk As Integer
  Dim IsLocked As Boolean
  Dim LockDetails As ISLockRO
  Dim Success As Boolean
  Dim WizardFinishDetails As WizardFinishDetails

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    BatchPk = .GetInteger("BatchPk")
  End With

  ' Validate

  ' Release Lock
  If Success Then
    If finBL.Database.LockCheck("Batch", CStr(BatchPk), IsLocked, LockDetails) Then
      If IsLocked Then
        If LockDetails.CreatedUserPk = finBL.CurrentUser.UserPk Then
          ' Unlock
          Success = finBL.Database.LockClear(LockDetails.Pk, True)
        Else
          Success = False
          finBL.Error.ErrorBegin("This Bank Batch is locked by another User.")
        End If
      End If
    Else
      Success = False
    End If
  End If

  ' Commit Batch
  If Success Then
    BatchBank = finBL.CreateBatchBank(True)
    If BatchBank.LoadPk(batchPk) Then
      ' Commit
      If BatchBank.ExecuteCommit(True) Then
        ' Create Finish Details
        WizardFinishDetails = New WizardFinishDetails(finBL, BatchBank)

        ' Record Commit Status
        For Each BatchBankTransaction In BatchBank.Transactions
          WizardFinishDetails.AddCommitStatus(BatchBankTransaction)
        Next

        ' Remove Committed (and blank) Transactions
        BatchBank.RemoveCommitted(True)

        ' Close Batch (also releases Lock)
        If Not BatchBank.HasUncommittedTransactions() Then
          If Not batchBank.StatusClose() Then
            WizardFinishDetails.Warning = "Bank Batch was successfully committed but failed to close."
          End If
        End If
      Else
        Success = False
      End If
    Else
      Success = False
    End If
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Delete Batch.
''' &lt;/summary&gt;
Public Function DeleteBatch(ByRef returnValue As String) As Boolean

  Dim BatchBank As finBatchBank
  Dim BatchPk As Integer
  Dim IsLocked As Boolean
  Dim LockDetails As ISLockRO
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    BatchPk = .GetInteger("BatchPk")
  End With

  ' Validate

  ' Release Lock
  If Success Then
    If finBL.Database.LockCheck("Batch", CStr(BatchPk), IsLocked, LockDetails) Then
      If IsLocked Then
        If finBL.CurrentUser.IsAdministrator OrElse LockDetails.CreatedUserPk = finBL.CurrentUser.UserPk Then
          ' Unlock
          Success = finBL.Database.LockClear(LockDetails.Pk, True)
        Else
          Success = False
          finBL.Error.ErrorBegin("This Bank Batch is locked by another User.")
        End If
      End If
    Else
      Success = False
    End If
  End If

  ' Delete Batch
  If Success Then
    BatchBank = finBL.CreateBatchBank(True)
    If BatchBank.LoadPk(batchPk) Then
      ' Delete
      Success = BatchBank.Delete()
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  New Batch.
''' &lt;/summary&gt;
Public Function NewBatch(ByRef returnValue As String) As Boolean

  Dim BankAccountId As String
  Dim BatchBank As finBatchBank
  Dim BatchId As String
  Dim obj As Object
  Dim Success As Boolean
  Dim TransactionTypeId As String

  ' Assume Success
  Success = True

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

  ' Validate
  If Success Then
  End If

  ' Create Batch
  If Success Then
    BatchBank = finBL.CreateBatchBank(False)
    With BatchBank
      .BankAccountId = BankAccountId
      .BatchId = BatchId
      .TransactionTypeId = TransactionTypeId

      ' Source
      .SourceSet(isefinTransactionSource.BankEntry)

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

  ' Get Details of new Batch
  If Success Then
    obj = New With {
      .BatchId = BatchBank.BatchId,
      .BatchPk = BatchBank.Pk
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Refresh Batch.
''' &lt;/summary&gt;
Public Function RefreshBatch(parametersJson As String,
                             ByRef returnValue As String) As Boolean

  Dim BatchBank As finBatchBank
  Dim BatchDetails As BatchDetails
  Dim BatchPk As Integer
  Dim IncludeTransactions As Boolean
  Dim obj As Object
  Dim Success As Boolean
  Dim Transaction As finBatchBankTransaction
  Dim Transactions As List(Of BatchBankTransaction)

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    BatchPk = .GetInteger("BatchPk")
    IncludeTransactions = .GetBoolean("IncludeTransactions")
  End With

  ' Load Bank Batch
  If Success Then
    BatchBank = finBL.CreateBatchBank(False)
    Success = BatchBank.LoadPk(BatchPk)
  End If

  ' Validate
  If Success Then
  End If

  ' Get Batch Details
  If Success Then
    BatchDetails = New BatchDetails(finBL, batchBank)

    ' Transactions?
    If IncludeTransactions Then
      Transactions = New List(Of BatchBankTransaction)

      For Each Transaction In BatchBank.Transactions
        Transactions.Add(New BatchBankTransaction(finBL, Transaction))
      Next
    End If

    obj = New With {
      .BatchDetails = BatchDetails,
      .Transactions = Transactions
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Save Batch.
''' &lt;/summary&gt;
Public Function SaveBatch(parametersJson As String,
                          ByRef returnValue As String) As Boolean

  Dim BatchBank As finBatchBank
  Dim BatchBankTransaction As finBatchBankTransaction
  Dim BatchDetails As BatchDetails
  Dim Count As Integer
  Dim i As Integer
  Dim IsLocked As Boolean
  Dim ListOrder As List(Of Object)
  Dim LockDetails As ISLockRO
  Dim obj As Object
  Dim Success As Boolean
  Dim Transaction As BatchBankTransaction
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise
  ListOrder = New List(Of Object)

  ' Create a lockable Bank Batch object
  ' NOTE: Working with Locks and Bank Batches cannot be done within a Database Transaction
  BatchBank = finBL.CreateBatchBank(True)

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

    ' Shortcuts
    BatchDetails = WizardFinishParameters.BatchDetails
  Else
    Success = False
  End If

  ' Validate

  ' Release Lock
  If Success Then
    If finBL.Database.LockCheck("Batch", CStr(BatchDetails.BatchPk), IsLocked, LockDetails) Then
      If IsLocked Then
        If LockDetails.CreatedUserPk = finBL.CurrentUser.UserPk Then
          ' Unlock
          Success = finBL.Database.LockClear(LockDetails.Pk, True)
        Else
          Success = False
          finBL.Error.ErrorBegin("This Bank Batch is locked by another User.")
        End If
      Else
        Success = False
        finBL.Error.ErrorBegin("This Bank Batch is not locked and cannot be updated.")
      End If
    Else
      Success = False
    End If
  End If

  ' Load and Lock
  If Success Then
    Success = BatchBank.LoadPk(BatchDetails.BatchPk)
  End If

  ' Update
  If Success Then
    ' General
    With BatchBank
      .BatchId = BatchDetails.BatchId
      If Not .Imported Then
        .BankAccountId = BatchDetails.BankAccountId
      End If
      .BatchTotal = BatchDetails.BatchTotal
      .CashRegisterId = BatchDetails.CashRegisterId
      .Notes = BatchDetails.Notes
      .TransactionTypeId = BatchDetails.TransactionTypeId
    End With

    ' Transactions
    If WizardFinishParameters.Transactions IsNot Nothing Then
      For Each Transaction In WizardFinishParameters.Transactions
        If Transaction.OrigIndex &lt; 0 Then
          ' Create and Add New
          BatchBankTransaction = BatchBank.Transactions.CreateBatchBankTransaction()
          BatchBank.Transactions.Add(BatchBankTransaction)
        ElseIf Transaction.OrigIndex &gt;= BatchBank.Transactions.Count Then
          ' Invalid!
          Success = False
          finBL.Error.ErrorBeginFormat("No Transaction with an index of {0} was found in this Bank Batch.", Transaction.OrigIndex)
          Exit For
        Else
          ' Existing
          BatchBankTransaction = BatchBank.Transactions(Transaction.OrigIndex)
        End If

        ' Record for Re-Order later
        ListOrder.Add(BatchBankTransaction)

        ' Update
        If Not SaveBatch_UpdateTransaction(BatchBankTransaction, Transaction) Then
          Success = False
          Exit For
        End If
      Next

      ' Remove Deleted (i.e., any without a tag)
      If Success Then
        For i = BatchBank.Transactions.Count - 1 To 0 Step -1
          If BatchBank.Transactions(i).Tag Is Nothing Then
            BatchBank.Transactions.RemoveAt(i)
          End If
        Next
      End If

      ' Order
      If Success AndAlso Not BatchBank.Imported Then
        BatchBank.Transactions.Rearrange(ListOrder)
      End If
    End If
  End If

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

  ' Move Unallocated to Suspense?
  If Success AndAlso WizardFinishParameters.MoveUnallocatedToSuspense Then
    Count = BatchBank.Transactions.Count
    If BatchBank.MoveUnallocatedToSuspense() Then
      Count -= BatchBank.Transactions.Count
    Else
      Success = False
    End If
  End If

  ' Get Details
  If Success Then
    obj = New With {
      .BatchId = BatchBank.BatchId,
      .BatchPk = BatchBank.Pk,
      .MovedToSuspense = Count,
      .CountTransactions = BatchBank.Transactions.Count
    }
  End If

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

  Return Success

End Function

Private Function SaveBatch_UpdateTransaction(batchBankTransaction As finBatchBankTransaction,
                                             transaction As BatchBankTransaction) As Boolean

  Dim BatchBankTransactionItem As finBatchBankTransactionItem
  Dim i As Integer
  Dim ListOrder As List(Of Object)
  Dim Split As BatchBankTransactionSplit
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  ListOrder = New List(Of Object)

  ' Update Transaction
  With batchBankTransaction
    With .BankingDetails
      .AccountSortCode = transaction.AccountSortCode
      .AccountName = transaction.BankAccountName
      .AccountNumber = transaction.BankAccountNumber
      .BankBranchName = transaction.BankBranchName
      .BankNameShort = transaction.BankNameShort
      If Len(.CardExpiryDate) = 0 Then
        .CardExpiryDate = Nothing
      Else
        .CardExpiryDate = finBL.HtmlWidgetUtilities.CardExpiryDateFromString(transaction.CardExpiryDate)
      End If
      .CardSecurityCode = transaction.CardSecurityCode
      .PaymentMethodId = transaction.PaymentMethodId
      .Reference = transaction.BankReference
    End With

    .Reference = transaction.Reference
    .Date = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(transaction.Date)
    .Notes = transaction.Notes
    .UpdateBankMatch = transaction.UpdateAccountBankMatch

    ' Tag original index
    .Tag = transaction.OrigIndex
  End With

  ' Update Splits
  For Each Split In transaction.Splits
    If Split.OrigIndex &lt; 0 Then
      ' Create and Add New
      BatchBankTransactionItem = batchBankTransaction.TransactionItems.CreateBatchBankTransactionItem()
      batchBankTransaction.TransactionItems.Add(BatchBankTransactionItem)
    ElseIf Split.OrigIndex &gt;= batchBankTransaction.TransactionItems.Count Then
      ' Invalid!
      Success = False
      finBL.Error.ErrorBeginFormat("No Split with an index of {0} was found in Transaction {1}.", Split.OrigIndex, batchBankTransaction.Parent.IndexOf(batchBankTransaction))
      Exit For
    Else
      ' Existing
      BatchBankTransactionItem = batchBankTransaction.TransactionItems(Split.OrigIndex)
    End If

    ' Record for Re-Order later
    ListOrder.Add(BatchBankTransactionItem)

    ' Update
    If Not SaveBatch_UpdateSplit(BatchBankTransactionItem, Split) Then
      Success = False
      Exit For
    End If
  Next

  ' Remove Deleted (i.e., any without a tag)
  If Success Then
    For i = batchBankTransaction.TransactionItems.Count - 1 To 0 Step -1
      If batchBankTransaction.TransactionItems(i).Tag Is Nothing Then
        batchBankTransaction.TransactionItems.RemoveAt(i)
      End If
    Next
  End If

  ' Order
  If Success Then
    batchBankTransaction.TransactionItems.Rearrange(ListOrder)
  End If

  Return Success

End Function

Private Function SaveBatch_UpdateSplit(batchBankTransactionItem As finBatchBankTransactionItem,
                                       split As BatchBankTransactionSplit) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Update Transaction Item
  With batchBankTransactionItem
    If .AccountIdSet(split.AccountId) Then
      .ElementId = split.ElementId
      .Notes = split.Notes
      .Value = split.Value

      ' Tag original index
      .Tag = split.OrigIndex
    Else
      Success = False
    End If
  End With

  Return Success

End Function

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

  Dim BankAccount As finBankAccountRO
  Dim DataRow As datarow
  Dim dt As DataTable
  Dim Element As finElementRO
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim PaymentMethod As finPaymentMethodRO
  Dim Success As Boolean
  Dim TransactionType As finTransactionTypeRO

  ' Assume Success
  Success = True

  ' Validate
  Success = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)

  ' Get Bank Batches
  If Success Then
    Success = finBL.BatchFunctions.GetBankBatchListAsDataTable(dt)
  End If

  If Success Then
    ' Form Initialisation Info
    If Success Then
      FormInitialisationInfo = New FormInitialisationInfo()
      With FormInitialisationInfo
        ' General
        .BatchId = mBatchId
        .DefaultTransactionDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())

        ' Lists
        For Each DataRow In dt.Rows
          .BatchList.Add(New BatchListItem(finBL.Database.GetFieldString(DataRow!BatchId),
                                           finBL.Database.GetFieldString(DataRow!Notes),
                                           finBL.FormatDateTimeLong(finBL.Database.GetFieldDate(DataRow!Date)),
                                           finBL.Database.GetFieldString(DataRow!User),
                                           finBL.Database.GetFieldString(DataRow!TransactionTypeId)))
        Next

        ' Configuration
        .BankAccountsSqlWhere = finBL.BankAccounts.GetDataViewFilter_AllowBankEntry()
        .CountryCode = finBL.CountryCode
        .GridsShowBanking = mGridsShowBanking
        .GridsShowElement = mGridsShowElement
        .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
        .ReadOnly = finBL.Database.IsReadOnly
        .ShowCashRegister = (finBL.Settings.AddOns.BankingAdvanced AndAlso (finBL.BankAccounts.IsCashRegisterRequired OrElse finBL.CashRegisters.Count &lt;&gt; 0))
        .SupportsBankSortCode = finBL.CurrentCountry.SupportsBankSortCode
        .TerminologyBankSortCode = finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode)
        .TransactionLoadCountPrompt = mTransactionLoadCountPrompt
        .TransactionTypesSqlWhere = finBL.TransactionTypes.GetDataViewFilter_AllowBankEntry()

        ' Global Collections
        For Each BankAccount In finBL.BankAccounts
          If BankAccount.Active Then
            .BankAccounts.Add(New BankAccountDetails(finBL, BankAccount))
          End If
        Next
        For Each Element In finBL.Elements
          If Element.Active Then
            .Elements.Add(New ElementDetails(finBL, Element))
          End If
        Next
        For Each PaymentMethod In finBL.PaymentMethods
          If PaymentMethod.Active Then
            .PaymentMethods.Add(New PaymentMethodDetails(finBL, PaymentMethod))
          End If
        Next
        For Each TransactionType In finBL.TransactionTypes
          If TransactionType.Active Then
            .TransactionTypes.Add(New TransactionTypeDetails(finBL, TransactionType))
          End If
        Next
      End With

      ' Serialise
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, returnValue)
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validates the Tax Period being closed.
''' &lt;/summary&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim BatchBank As finBatchBank
  Dim BatchId As String
  Dim BatchPk As Integer
  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
  Dim Transaction As finBatchBankTransaction

  ' 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
  If Success Then
    Select Case PageId
      Case "General"
        ' Get Parameters
        With mCombinedParameters
          BatchId = .GetString("BatchId")
        End With

        ' Create a lockable Bank Batch object
        BatchBank = finBL.CreateBatchBank(True)

        ' Load and Lock
        If Success Then
          Success = BatchBank.Load(BatchId)
        End If

        ' Return Batch Details (excluding any transactions)
        If Success Then
          Data = New BatchDetails(finBL, batchBank)
        End If

      Case "Details"
        ' Get Parameters
        ' NOTE: Only the General page uses Batch Id in case the User has updated it
        With mCombinedParameters
          BatchPk = .GetInteger("BatchPk")
        End With

        ' Create a Bank Batch object
        BatchBank = finBL.CreateBatchBank(False)

        ' Load
        If Success Then
          Success = BatchBank.LoadPk(BatchPk)
        End If

        ' Validate Lock
        If Success Then
          'TODO:
        End If

        ' Return Batch Transactions
        If Success Then
          Data = New List(Of BatchBankTransaction)

          With DirectCast(Data, List(Of BatchBankTransaction))
            For Each Transaction In BatchBank.Transactions
              .Add(New BatchBankTransaction(finBL, Transaction))
            Next
          End With
        End If

    End Select
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account Details (for displaying read-only in grids).
''' &lt;/summary&gt;
Public Function GetAccountDetails(ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountId As String
  Dim obj As Object
  Dim Success As Boolean
  Dim TransactionDate As Date
  Dim Warning As String

  ' Assume Success
  Success = True

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

  ' Validate

  ' Load Account
  If Success Then
    Account = finBL.CreateAccount()
    If Account.Load(AccountId) Then
      ' Warnings (basic only)
      If Account.Status = isefinAccountStatus.Closed Then
        Warning = "Account is 'Closed'."
      ElseIf TransactionDate &lt; Account.DateOpened Then
        Warning = "Transaction is dated prior to Account being 'Open'."
      End If
    Else
      Warning = finBL.Error.Message()
    End If
  End If

  ' Get Account Details
  If Success Then
    obj = New With {
      .AccountId = Account.AccountId,
      .AccountName = Account.Name,
      .Balance = Account.Balance,
      .BalanceOverdue = Account.BalanceOverdue,
      .BalanceOverdueC = Account.BalanceOverdueContractual,
      .Warning = Warning
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Batch Infoormation (for displaying below Batch Id dropdown).
''' &lt;/summary&gt;
Public Function GetBatchInfo(ByRef returnValue As String) As Boolean

  Dim AutoPostWithholdingTax As Boolean
  Dim BankAccountId As String
  Dim BatchId As String
  Dim BatchPk As Integer
  Dim BatchTotal As Decimal
  Dim CanUnlock As Boolean
  Dim CashRegisterId As String
  Dim DisbursementType As isefinDisbursementType
  Dim DisbursementPayeeType As isefinDisbursementPayeeType
  Dim DisbursementExternalPartyPk As Integer
  Dim IsLocked As Boolean
  Dim LockDetails As ISLockRO
  Dim Notes As String
  Dim obj As Object
  Dim Success As Boolean
  Dim TransactionTypeId As String

  ' Assume Success
  Success = True

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

  ' Validate

  ' Get Batch Details
  If Success Then
    Success = finBL.BatchFunctions.GetBatchDetails(BatchId, TransactionTypeId, BatchTotal, Notes, BankAccountId, CashRegisterId, AutoPostWithholdingTax, DisbursementType, DisbursementPayeeType, DisbursementExternalPartyPk, BatchPk)
  End If

  ' Get Lock Details
  If Success Then
    If finBL.Database.LockCheck("Batch", CStr(BatchPk), IsLocked, LockDetails) Then
      ' Can Unlock Batch?
      If IsLocked Then
        Select Case UCase(mBatchUnlockPolicy)
          Case "ADMINISTRATOR ONLY"
            CanUnlock = finBL.CurrentUser.IsAdministrator
          Case "ADMINISTRATOR PLUS BATCH USER"
            CanUnlock = finBL.CurrentUser.IsAdministrator OrElse finBL.CurrentUser.UserPk = LockDetails.CreatedUserPk
          Case "ANY USER"
            CanUnlock = True
          Case Else
            CanUnlock = False
        End Select
      End If
    Else
      Success = False
    End If
  End If

  ' Finalise
  If Success Then
    obj = New With {
      .BatchId = BatchId,
      .BatchPk = BatchPk,
      .TransactionTypeId = TransactionTypeId,
      .TransactionTypeDescription = finBL.TransactionTypes.GetRecordDescription(TransactionTypeId),
      .BankAccountId = BankAccountId,
      .BankAccountDescription = finBL.BankAccounts.GetRecordDescription(BankAccountId),
      .CashRegisterId = CashRegisterId,
      .CashRegisterDescription = finBL.CashRegisters.GetRecordDescription(CashRegisterId),
      .IsLocked = IsLocked,
      .LockedByUserId = If(IsLocked, LockDetails.CreatedUserId, ""),
      .LockedByUserName = If(IsLocked,LockDetails.CreatedUserName, ""),
      .LockedDate = If(IsLocked,finBL.FormatDateTimeLong(finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(LockDetails.CreatedUtcDate)), ""),
      .CanUnlock = CanUnlock
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Transaction Preview.
''' &lt;/summary&gt;
Public Function GetTransactionPreview(ByRef returnValue As String) As Boolean

  Dim ImportDetails As BatchBankTransactionImportDetails
  Dim ImportDetailsJson As String
  Dim obj As Object
  Dim PaymentMethodId As String
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim SummaryTablesImport As ISSummaryTables
  Dim TransactionDate As Date
  Dim UpdateAccountBankMatch As Boolean
  Dim BatchBankTransaction As finBatchBankTransaction

  ' NOTE: This preview is performed without the overhead of loading the Bank Batch and does not use the SummaryPage2_BatchBank_TransactionSummary Script

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    PaymentMethodId = .GetString("PaymentMethodId")
    TransactionDate = .GetDatabaseDateFromJsonUtcDate("TransactionDate")
    UpdateAccountBankMatch = .GetBoolean("UpdateAccountBankMatch")
    ImportDetailsJson = .GetString("ImportDetails")
    If Len(ImportDetailsJson) &lt;&gt; 0 Then
      If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(ImportDetailsJson, GetType(BatchBankTransactionImportDetails), obj) Then
        ImportDetails = DirectCast(obj, BatchBankTransactionImportDetails)
      Else
        ' Ignore
      End If
    End If
  End With

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables.Add("Main", SummaryTable)

  ' General
  With SummaryTable
    .TableClass = iseSummaryTableClass.Information

    .Columns.AddText(10).NoBreakChars = 20
    .Columns.AddText()

    With .Rows
      .AddCaptionDate("Date:", TransactionDate)
      .AddCaptionCodeDescription("Payment Method:", PaymentMethodId, finBL.PaymentMethods)
    End With
  End With

  ' Import Details
  If ImportDetails IsNot Nothing Then
    ' Convert to a Batch Bank Transaction so we can use Standard Summary Block
    BatchBankTransaction = ImportDetails.CreateBatchBankTransaction(finBL)
    With BatchBankTransaction
      .UpdateBankMatch = UpdateAccountBankMatch
    End With
    
    SummaryTablesImport = finBL.SummaryPageStandardBlocks.BatchBankTransaction_ImportedTransaction(ScriptInfo, BatchBankTransaction)
    If SummaryTablesImport.Count &lt;&gt; 0 Then SummaryTablesImport.ItemByIndex(0).Caption = "Imported Transaction"
    SummaryTables.AppendSummaryTables(SummaryTablesImport)
  End If

  ' Create Preview
  returnValue = finBL.Utilities.GetHtmlFromSummaryTables(SummaryTables,,,, ScriptInfo.Target, "Summary")

  Return Success

End Function

''' &lt;summary&gt;
'''  Unlock Batch.
''' &lt;/summary&gt;
Public Function UnlockBatch(ByRef returnValue As String) As Boolean

  Dim BatchPk As Integer
  Dim CanUnlock As Boolean
  Dim IsCurrentBatch As Boolean
  Dim IsLocked As Boolean
  Dim LockDetails As ISLockRO
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    BatchPk = .GetInteger("BatchPk")
    IsCurrentBatch = .GetBoolean("IsCurrentBatch")
  End With

  ' Validate

  ' Get Lock Details
  If Success Then
    If finBL.Database.LockCheck("Batch", CStr(BatchPk), IsLocked, LockDetails) Then
      ' Can Unlock Batch?
      If IsLocked Then
        If IsCurrentBatch Then
          ' Must always be able to unlock the Batch you're currently working on
          CanUnlock = True
        Else
          Select Case UCase(mBatchUnlockPolicy)
            Case "ADMINISTRATOR ONLY"
              CanUnlock = finBL.CurrentUser.IsAdministrator
            Case "ADMINISTRATOR PLUS BATCH USER"
              CanUnlock = finBL.CurrentUser.IsAdministrator OrElse finBL.CurrentUser.UserPk = LockDetails.CreatedUserPk
            Case "ANY USER"
              CanUnlock = True
            Case Else
              CanUnlock = False
          End Select
        End If

        ' Validate
        If Not CanUnlock Then
          Success = False
          finBL.Error.ErrorBeginFormat("You do not have permission to unlock this Bank Batch. This form's Unlock Policy is '{0}'.", mBatchUnlockPolicy)
        End If
      End If
    End If
  End If

  ' Unlock
  If Success AndAlso IsLocked Then
    Success = finBL.Database.LockClear(LockDetails.Pk, True)
  End If

  Return Success

End Function



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

  ' General
  Public BatchId As String
  Public DefaultTransactionDate As Date

  ' Lists
  Public BatchList As New List(Of BatchListItem)

  ' Configuration
  Public BankAccountsSqlWhere As String
  Public CountryCode As String
  Public GridsShowBanking As Boolean
  Public GridsShowElement As Boolean
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean
  Public ShowCashRegister As Boolean
  Public SupportsBankSortCode As Boolean
  Public TerminologyBankSortCode As String
  Public TransactionLoadCountPrompt As Integer
  Public TransactionTypesSqlWhere As String

  ' Global Collections
  Public BankAccounts As New List(Of BankAccountDetails)
  Public Elements As New List(Of ElementDetails)
  Public PaymentMethods As New List(Of PaymentMethodDetails)
  Public TransactionTypes As New List(Of TransactionTypeDetails)

End Class



''' &lt;summary&gt;
'''  Batch List Item for dropdown.
''' &lt;/summary&gt;
Public Class BatchListItem

  Public BatchId As String
  Public CreatedDate As String
  Public CreatedUserId As String
  Public Notes As String
  Public TransactionTypeId As String

  Public Sub New(batchId As String,
                 notes As String,
                 createdDate As String,
                 createdUserId As String,
                 transactionTypeId As String)

    With Me
      .BatchId = batchId
      .Notes = notes
      .CreatedDate = createdDate
      .CreatedUserId = createdUserId
      .TransactionTypeId = transactionTypeId
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Batch Details for editing and displaying basic information.
''' &lt;/summary&gt;
Public Class BatchDetails

  Public BatchId As String
  Public BatchPk As Integer
  Public BankAccountId As String
  Public BatchTotal As Decimal
  Public CashRegisterId As String
  Public CreatedDate As String
  Public CreatedUserId As String
  Public Notes As String
  Public Pk As Integer
  Public TransactionTypeId As String

  ' Information
  Public Imported As Boolean
  Public TransactionCount As Integer

  Public Sub New()
    ' For desrialisation
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 batchBank As finBatchBank)

    With batchBank
      Me.BatchId = .BatchId
      Me.BatchPk = .Pk
      Me.BankAccountId = .BankAccountId
      Me.BatchTotal = .BatchTotal
      Me.CashRegisterId = .CashRegisterId
      Me.Notes = .Notes
      Me.TransactionTypeId = .TransactionTypeId

      ' Information
      Me.Imported = .Imported
      Me.TransactionCount = .Transactions.Count
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Bank Batch Transaction.
''' &lt;/summary&gt;
Public Class BatchBankTransaction

  ' Properties
  Public [Date] As Date?
  Public AccountSortCode As String
  Public BankAccountName As String
  Public BankAccountNumber As String
  Public BankBranchName As String
  Public BankNameShort As String
  Public BankReference As String
  Public CardExpiryDate As String
  Public CardSecurityCode As String
  Public ImportedMatch As String
  Public Notes As String
  Public PaymentMethodId As String
  Public Reference As String
  Public UpdateAccountBankMatch As Boolean

  ' Other
  Public OrigIndex As Integer

  ' Splits
  Public Splits As New List(Of BatchBankTransactionSplit)

  ' Read-Only Properties and Information
  Public ImportDetails As BatchBankTransactionImportDetails

  Public Sub New()
    ' For desrialisation
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 transaction As finBatchBankTransaction)

    Dim TransactionItem As finBatchBankTransactionItem

    ' NOTE: For simplicity, everything editable that can be is done via the Splits collection

    With transaction
      ' Properties
      With .BankingDetails
        Me.AccountSortCode = .AccountSortCode
        Me.BankAccountName = .AccountName
        Me.BankAccountNumber = .AccountNumber
        Me.BankBranchName = .BankBranchName
        Me.BankNameShort = .BankNameShort
        Me.BankReference = .Reference
        Me.CardExpiryDate = finBL.HtmlWidgetUtilities.CardExpiryDateToString(.CardExpiryDate)
        Me.CardSecurityCode = .CardSecurityCode
        Me.PaymentMethodId = .PaymentMethodId
      End With

      Me.Date = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.Date)
      Me.Notes = .Notes
      Me.Reference = .Reference
      
      Me.ImportedMatch = .ImportedMatch
      Me.UpdateAccountBankMatch = .UpdateBankMatch

      ' Other
      Me.OrigIndex = transaction.Parent.IndexOf(transaction)

      ' Read-Only Properties and Information
      If transaction.Parent.Parent.Imported Then
        Me.ImportDetails = New BatchBankTransactionImportDetails(finBL, transaction)
      End If

      ' Splits
      For Each TransactionItem In .TransactionItems
        Me.Splits.Add(New BatchBankTransactionSplit(finBL, TransactionItem))
      Next
    End With

  End Sub

  ' Prevent Serialisation for Not Applicable Properties
  Public Function ShouldSerializeAccountSortCode() As Boolean
    Return Len(Me.AccountSortCode) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeBankAccountName() As Boolean
    Return Len(Me.BankAccountName) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeBankAccountNumber() As Boolean
    Return Len(Me.BankAccountNumber) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeBankBranchName() As Boolean
    Return Len(Me.BankBranchName) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeBankNameShort() As Boolean
    Return Len(Me.BankNameShort) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeBankReference() As Boolean
    Return Len(Me.BankReference) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeCardSecurityCode() As Boolean
    Return Len(Me.CardSecurityCode) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeImportDetails() As Boolean
    Return Me.ImportDetails IsNot Nothing
  End Function

  Public Function ShouldSerializeNotes() As Boolean
    Return Len(Me.Notes) &lt;&gt; 0
  End Function

End Class



''' &lt;summary&gt;
'''  Batch Transaction Import Details.
''' &lt;/summary&gt;
Public Class BatchBankTransactionImportDetails

  Public Code As String
  Public [Date] As Date
  Public DishonourReason As String
  Public Match As String
  Public MatchAlternate As String
  Public OtherPartyBankAccountSortCode As String
  Public OtherPartyBankAccountNumber As String
  Public OtherPartyName As String
  Public Particulars As String
  Public Reference As String
  Public Source As String
  Public SourceDescription As String
  Public TransactionCode As String
  Public UpdateBankMatch As Boolean
  Public Value As Decimal

  Public Sub New()
    ' For desrialisation
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 transaction As finBatchBankTransaction)

    With transaction
      Me.Code = .ImportedCode
      Me.Date = .ImportedDate
      Me.DishonourReason = .ImportedDishonourReason
      Me.Match = .ImportedMatch
      Me.MatchAlternate = .ImportedMatchAlternate
      Me.OtherPartyBankAccountSortCode = .ImportedOtherPartyBankAccountSortCodeForDisplay
      Me.OtherPartyBankAccountNumber = .ImportedOtherPartyBankAccountNumberForDisplay
      Me.OtherPartyName = .ImportedOtherPartyName
      Me.Particulars = .ImportedParticulars
      Me.Reference = .ImportedReference
      Me.Source = .ImportedSource
      Me.SourceDescription = .ImportedSourceDescription
      Me.TransactionCode = .ImportedTransactionCode
      Me.UpdateBankMatch = .UpdateBankMatch
      Me.Value = .ImportedValue
    End With

  End Sub

  Public Function CreateBatchBankTransaction(finBL As ISfinSupport) As finBatchBankTransaction

    Dim BatchBankTransaction As finBatchBankTransaction

    ' Initialise
    BatchBankTransaction = finBL.CreateBatchBank().Transactions.CreateBatchBankTransaction()

    ' Update with Import Details (so we can use Summary Page Standard Blocks to view)
    With BatchBankTransaction
      .ImportedCode = Me.Code
      .ImportedDate = Me.Date
      .ImportedDishonourReason = Me.DishonourReason
      .ImportedMatch = Me.Match
      .ImportedMatchAlternate = Me.MatchAlternate
      .ImportedOtherPartyBankAccountSortCode = Me.OtherPartyBankAccountSortCode
      .ImportedOtherPartyBankAccountNumber = Me.OtherPartyBankAccountNumber
      .ImportedOtherPartyName = Me.OtherPartyName
      .ImportedParticulars = Me.Particulars
      .ImportedReference = Me.Reference
      .ImportedSource = Me.Source
      .ImportedSourceDescription = Me.SourceDescription
      .ImportedTransactionCode = Me.TransactionCode
      .ImportedValue = Me.Value
      .UpdateBankMatch = Me.UpdateBankMatch
    End With

    Return BatchBankTransaction

  End Function

  ' Prevent Serialisation for Not Applicable Properties
  Public Function ShouldSerializeCode() As Boolean
    Return Len(Me.Code) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeDishonourReason() As Boolean
    Return Len(Me.DishonourReason) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeMatch() As Boolean
    Return Len(Me.Match) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeMatchAlternate() As Boolean
    Return Len(Me.MatchAlternate) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeOtherPartyBankAccountSortCode() As Boolean
    Return Len(Me.OtherPartyBankAccountSortCode) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeOtherPartyBankAccountNumber() As Boolean
    Return Len(Me.OtherPartyBankAccountNumber) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeOtherPartyName() As Boolean
    Return Len(Me.OtherPartyName) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeParticulars() As Boolean
    Return Len(Me.Particulars) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeReference() As Boolean
    Return Len(Me.Reference) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeSource() As Boolean
    Return Len(Me.Source) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeSourceDescription() As Boolean
    Return Len(Me.SourceDescription) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeTransactionCode() As Boolean
    Return Len(Me.TransactionCode) &lt;&gt; 0
  End Function

End Class



''' &lt;summary&gt;
'''  Batch Transaction Split.
''' &lt;/summary&gt;
Public Class BatchBankTransactionSplit

  ' Properties
  Public AccountId As String
  Public ElementId As String
  Public Notes As String
  Public Value As Decimal

  ' Other
  Public OrigIndex As Integer

  ' Read-Only Properties
  Public AccountName As String
  Public Balance As Decimal?
  Public BalanceOverdue As Decimal?
  Public BalanceOverdueC As Decimal?
  Public Info As String
  Public Warning As String

  Public Sub New()
    ' For desrialisation
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 transactionItem As finBatchBankTransactionItem)

    Dim strTemp As String

    With transactionItem
      ' Properties
      Me.AccountId = .AccountId
      Me.ElementId = .ElementId
      Me.Notes = .Notes
      Me.Value = .Value

      ' Other
      Me.OrigIndex = transactionItem.Parent.IndexOf(transactionItem)

      ' Read-Only Properties
      Me.AccountName = .AccountName
      Me.Balance = .AccountBalance
      Me.BalanceOverdue = .AccountBalanceOverdue
      Me.BalanceOverdueC = .AccountBalanceOverdueContractual
      Me.Warning = .AccountWarningMessage(strTemp)
      Me.Info = strTemp
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Global Collection: Bank Accounts.
''' &lt;/summary&gt;
Public Class BankAccountDetails

  ' Properties
  Public BankAccountId As String

  Public CashRegisterAllowBlank As Boolean
  Public PaymentMethodsIncomingListTag As String
  Public PaymentMethodsOutgoingListTag As String

  Public Sub New(finBL As ISfinSupport,
                 bankAccount As finBankAccountRO)

    With bankAccount
      Me.BankAccountId = .BankAccountId
      Me.CashRegisterAllowBlank = Not .OptionRequireCashRegister

      ' Resolvable 'List' tags for use in grids to display Payment Methods dropdown
      Me.PaymentMethodsIncomingListTag = "RANGE.PaymentMethods{" &amp; finBL.BatchFunctions.GetBankBatchPaymentMethodsIncomingDataViewFilter(Me.BankAccountId) &amp; " AND Active='True'}"
      Me.PaymentMethodsOutgoingListTag = "RANGE.PaymentMethods{" &amp; finBL.BatchFunctions.GetBankBatchPaymentMethodsOutgoingDataViewFilter(Me.BankAccountId) &amp; " AND Active='True'}"
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Global Collection: Elements.
''' &lt;/summary&gt;
Public Class ElementDetails

  ' Properties
  Public ElementId As String

  Public PaymentMethodIncoming As Boolean

  Public Sub New(finBL As ISfinSupport,
                 element As finElementRO)

    With element
      Me.ElementId = .ElementId

      ' Is this Element used for Incoming (rather than Outgoing) Payment Methods?
      Select Case .ElementType
        Case isefinElementType.Investment, isefinElementType.InvestmentAdditional, isefinElementType.PaymentReceived
          PaymentMethodIncoming = True
        Case Else
          PaymentMethodIncoming = False
      End Select
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Global Collection: Payment Methods.
''' &lt;/summary&gt;
Public Class PaymentMethodDetails

  ' Properties
  Public PaymentMethodId As String

  Public CardSecurityCodeRequired As Boolean
  Public PaymentFlowDirection As isefinPaymentMethodPaymentFlowDirection
  Public PaymentTypeCategory As isefinPaymentTypeCategory

  Public Sub New(finBL As ISfinSupport,
                 paymentMethod As finPaymentMethodRO)

    With paymentMethod
      Me.PaymentMethodId = .PaymentMethodId

      Me.CardSecurityCodeRequired = .CardSecurityCodeRequired
      Me.PaymentFlowDirection = .PaymentFlowDirection
      Me.PaymentTypeCategory = .PaymentTypeCategory
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Global Collection: Transaction Types.
''' &lt;/summary&gt;
Public Class TransactionTypeDetails

  ' Properties
  Public TransactionTypeId As String

  Public BatchIdAllowBlank As Boolean
  Public DefaultBankAccountId As String
  Public ElementId As String
  Public ElementsListTag As String

  Public Sub New(finBL As ISfinSupport,
                 transactionType As finTransactionTypeRO)

    With transactionType
      Me.ElementId = .ElementId
      Me.BatchIdAllowBlank = (.HasAutoSequencedBatchId OrElse Len(finBL.Settings.AccountNextBatchId) &lt;&gt; 0)
      Me.DefaultBankAccountId = .DefaultBankAccountId
      Me.TransactionTypeId = .TransactionTypeId

      ' Resolvable 'List' tag for use in grids to display Elements dropdown
      Me.ElementsListTag = "RANGE.Elements{" &amp; finBL.BatchFunctions.GetBankBatchElementsDataViewFilter(Me.transactionTypeId) &amp; "}"
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Wizard Finish Parameters (used to save Bank Bank, not for committing).
''' &lt;/summary&gt;
Public Class WizardFinishParameters

  Public BatchDetails As BatchDetails
  Public Transactions As List(Of BatchBankTransaction)
  Public MoveUnallocatedToSuspense 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 Details.
''' &lt;/summary&gt;
Public Class WizardFinishDetails

  Public BatchId As String
  Public BatchPk As Integer
  Public CommitStatuses As New List(Of TransactionCommitStatus)
  Public HasUncommittedTransactions As Boolean
  Public PartiallyCommitted As Boolean
  Public Warning As String

  ' Private
  Private mFinBl As ISfinSupport

  Public Sub New(finBL As ISfinSupport,
                 batchBank As finBatchBank)

    mFinBl = finBL

    With batchBank
      Me.BatchId = .BatchId
      Me.BatchPk = .Pk

      Me.HasUncommittedTransactions = .HasUncommittedTransactions()
      Me.PartiallyCommitted = .HasCommittedTransactions()
    End With

  End Sub

  Public Sub AddCommitStatus(transaction As finBatchBankTransaction)

    Me.CommitStatuses.Add(New TransactionCommitStatus(mFinBl, transaction))

  End Sub

End Class



''' &lt;summary&gt;
'''  Transactions Commit Status.
''' &lt;/summary&gt;
Public Class TransactionCommitStatus

  ' Properties
  Public Committed As Boolean
  Public CommitError As String

  ' Other Properties (in case Transactions are not loaded client-side)
  Public AccountId As String
  Public [Date] As Date?
  Public Notes As String
  Public PaymentMethodId As String
  Public Reference As String
  Public Value As Decimal

  Public Sub New(finBL As ISfinSupport,
                 transaction As finBatchBankTransaction)

    With transaction
      Me.Committed = .IsCommitted
      Me.CommitError = .CommitErrorResolved

      ' Other
      Select Case .TransactionItems.Count
        Case 0
          Me.AccountId = ""
        Case 1
          Me.AccountId = .TransactionItems(0).AccountId
        Case Else
          Me.AccountId = .TransactionItems(0).AccountId &amp; "+"
      End Select
      Me.Date = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.Date)
      Me.Notes = .Notes
      Me.PaymentMethodId = .BankingDetails.PaymentMethodId
      Me.Reference = .Reference
      Me.Value = .Value
    End With

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "BankEntry".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Select the Bank Batch to edit."&gt;General&lt;/li&gt;
        &lt;li tabId="Details" tooltipText="Review Bank Batch details and optionally Commit the Batch."&gt;Batch Details&lt;/li&gt;
        &lt;li tabId="Items" tooltipText=""&gt;Transactions&lt;/li&gt;
        &lt;li tabId="CommitDetailsSimple" tooltipText=""&gt;Commit Details&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"&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="lblBatch"&gt;Select the Bank Batch to edit or create a new Bank Batch&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBatch"&gt;Batch:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBatch" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;
            &lt;div id="divBatchInfo" class="is-info-text info small" style="display:none"&gt;
              &lt;p id="pBatchNotLocked"&gt;Clicking the "Next &amp;gt;" button will lock this Bank Batch to prevent other Users from editing it.&lt;/p&gt;
              &lt;p id="pBatchInfo"&gt;&lt;/p&gt;
              &lt;p id="pBatchLockInfo" style="color:red"&gt;&lt;/p&gt;
              &lt;p&gt;&lt;button id="cmdBatchUnlock" class="is-button negative"&gt;Unlock Batch&lt;/button&gt;&lt;/p&gt;
            &lt;/div&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;button id="cmdBatchNew" class="is-button ok"&gt;Create a new Bank Batch&lt;/button&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Details --&gt;
    &lt;div id="pageDetails"&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="lblBatchDetails"&gt;Review and optionally update Bank Batch details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtBatchId"&gt;Batch ID:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtBatchId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboTransactionType"&gt;Transaction&amp;nbsp;Type:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboTransactionType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBankAccount"&gt;Bank Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBankAccount" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCashRegister"&gt;Cash Register:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCashRegister" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBatchTotal"&gt;Total:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBatchTotal" /&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 colspan="2"&gt;
            &lt;div id="divBatchDetails" class="is-info-text info small"&gt;
              &lt;p id="pBatchItemsNotLoaded"&gt;Clicking the "Next &amp;gt;" button will load all &lt;b id="bTransactionCount"&gt;&lt;/b&gt; Transactions in this Bank Batch.&lt;/p&gt;
              &lt;p id="pBatchDetails"&gt;&lt;/p&gt;
              &lt;p id="pBatchCommit"&gt;
                &lt;p&gt;Use the button below to Commit this Bank Batch without the overhead of loading its Transactions.&lt;/p&gt;
                &lt;button id="cmdBatchCommit" class="is-button ok"&gt;Commit Batch&lt;/button&gt;
              &lt;/p&gt;
            &lt;/div&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Items --&gt;
    &lt;div id="pageItems"&gt;
      &lt;div class="is-dock-fill is-split-container split5050"&gt;
        &lt;div class="panel"&gt;
          &lt;div id="gridTransactions"&gt;&lt;/div&gt;
          &lt;div id="divTransactionsSummary" class="is-info-text info" style="position:absolute; bottom:2px; right:2px; line-height:19px; font-size:15px; margin:0"&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="panel"&gt;
          &lt;div class="is-dock-fill is-split-container split5050 side-by-side"&gt;
            &lt;div class="panel"&gt;
              &lt;div id="wbTransactions" class="is-dock-fill"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="panel"&gt;
              &lt;div id="gridSplits"&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Commit Details Simple --&gt;
    &lt;div id="pageCommitDetailsSimple"&gt;
      &lt;div id="gridCommitStatuses" class="is-dock-fill"&gt;&lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdBatchSave" class="is-button positive" style="float:left"&gt;Save&lt;/button&gt;
    &lt;button id="cmdBatchRefresh" class="is-button positive" style="float:left"&gt;Refresh&lt;/button&gt;
    &lt;button id="cmdBatchAbandon" class="is-button" style="float:left"&gt;Cancel Edit&lt;/button&gt;
    &lt;button id="cmdBatchDelete" class="is-button negative" style="float:left"&gt;Delete&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;Commit&lt;/button&gt;  &lt;/footer&gt;
&lt;/div&gt;



&lt;!-- frmBatchNew BEGIN --&gt;
&lt;div id="frmBatchNew"  class="is-widget-form-body" style="display:none"&gt;
  &lt;table class="is-form"&gt;
    &lt;colgroup&gt;
      &lt;col style="width:8em" /&gt;
      &lt;col /&gt;
    &lt;/colgroup&gt;

    &lt;tr&gt;
      &lt;th colspan="2"&gt;&lt;label id="lblNewBatchDetails"&gt;New Bank Batch details&lt;/label&gt;&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="cboNewTransactionType"&gt;Transaction&amp;nbsp;Type:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="cboNewTransactionType" /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="txtNewBatchId"&gt;Batch ID:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="txtNewBatchId" /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="cboNewBankAccount"&gt;Bank Account:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="cboNewBankAccount" /&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
&lt;/div&gt;
&lt;!-- frmBatchNew END --&gt;

&lt;script&gt;
// Record
var mRecord;
var mRecord_BatchInfo;
var mRecord_BatchDetails;
var mRecord_CommitDetails;
var mRecord_CommitStatuses;
var mRecord_SplitTransaction;
var mRecord_Transactions;

// Global Collections
var mBankAccounts;
var mElements;
var mPaymentMethods;
var mTransactionTypes;

// Controls
var C = {
  // General
  lblBatch: null,
  cboBatch: null,

  divBatchInfo: null,
  pBatchInfo: null,
  pBatchNotLocked: null,
  pBatchLockInfo: null,
  cmdBatchUnlock: null,
  cmdBatchNew: null,

  // Details
  lblBatchDetails: null,
  txtBatchId: null,
  cboTransactionType: null,
  cboBankAccount: null,
  cboCashRegister: null,
  numBatchTotal: null,
  txtNotes: null,

  divBatchDetails: null,
  pBatchItemsNotLoaded: null,
  bTransactionCount: null,
  pBatchDetails: null,
  pBatchCommit: null,
  cmdBatchCommit: null,

  // Items
  gridTransactions: null,
  divTransactionsSummary: null,
  gridSplits: null,
  wbTransactions: null,

  // Commit Details Simple
  gridCommitStatuses: null,

  // frmBatchNew
  lblNewBatchDetails: null,
  cboNewTransactionType: null,
  txtNewBatchId: null,
  cboNewBankAccount: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdBatchSave;
var cmdBatchRefresh;
var cmdBatchAbandon;
var cmdBatchDelete;
var cmdBatchRefresh;

// Other
var mBankAccount;
var mGrids_ShowBanking = false;
var mGrids_ShowElement = false;
var mLockedBatchId = "";
var mPostCommit = false;
var mTransactionType;

// Sub-Forms
var mForm_BatchNew;

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

  // Controls
  //   General
  C.lblBatch = widget.UI.Label("lblBatch", {});
  C.cboBatch = widget.UI.DBCombo("cboBatch", {
    allowBlank: false,
    limitToList: true,
    showDescription: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboBatch_Change,
  });
  C.divBatchInfo = $("#divBatchInfo");
  C.pBatchInfo = $("#pBatchInfo");
  C.pBatchNotLocked = $("#pBatchNotLocked");
  C.pBatchLockInfo = $("#pBatchLockInfo");
  C.cmdBatchUnlock = $("#cmdBatchUnlock");
  C.cmdBatchUnlock.click(BatchUnlock);
  C.cmdBatchNew = $("#cmdBatchNew");
  C.cmdBatchNew.click(BatchNew);

  //   Details
  C.lblBatchDetails = widget.UI.Label("lblBatchDetails", {});
  C.txtBatchId = widget.UI.TextBox("txtBatchId", {
    allowBlank: false,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.cboTransactionType = widget.UI.DBCombo("cboTransactionType", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboTransactionType_Change,
  });
  C.cboBankAccount = widget.UI.DBCombo("cboBankAccount", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboBankAccount_Change,
  });
  C.cboCashRegister = widget.UI.DBCombo("cboCashRegister", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.numBatchTotal = widget.UI.NumberBox("numBatchTotal", {
    blankIfZero: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });

  C.divBatchDetails = $("#divBatchDetails");
  C.pBatchItemsNotLoaded = $("#pBatchItemsNotLoaded");
  C.bTransactionCount = $("#bTransactionCount");
  C.pBatchDetails = $("#pBatchDetails");
  C.pBatchCommit = $("#pBatchCommit");
  C.cmdBatchCommit = $("#cmdBatchCommit");
  C.cmdBatchCommit.click(function () {
    if (tabWizard.Validate(true)) Form_ExecuteAction_FinishCommitBatch();
  });

  //   Items
  C.wbTransactions = widget.UI.PreviewPane("wbTransactions", {});

  // frmBatchNew
  C.lblNewBatchDetails = widget.UI.Label("lblNewBatchDetails", {});
  C.cboNewTransactionType = widget.UI.DBCombo("cboNewTransactionType", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboNewTransactionType_Change
  });
  C.txtNewBatchId = widget.UI.TextBox("txtNewBatchId", {
    allowBlank: false,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.cboNewBankAccount = widget.UI.DBCombo("cboNewBankAccount", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10
  });

  // Grids
  C.gridTransactions = widget.UI.Grid("gridTransactions", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,
    allowAddRows: true,

    onAction: gridTransactions_Action,
    onAfterRowActivate: gridTransactions_AfterRowActivate,
    onBeforeCellUpdate: gridTransactions_BeforeCellUpdate,
    onInitialiseRow: gridTransactions_InitialiseRow,
    onRowAdd: gridTransactions_RowAdd,
  });
  C.divTransactionsSummary = $("#divTransactionsSummary");

  C.gridSplits = widget.UI.Grid("gridSplits", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,
    allowAddRows: true,
    maxNewRows: 10,

    onAction: gridSplits_Action,
    onAfterRowActivate: gridSplits_AfterRowActivate,
    onBeforeCellUpdate: gridSplits_BeforeCellUpdate,
    onInitialiseRow: gridSplits_InitialiseRow,
    onRowAdd: gridSplits_RowAdd,
  });

  C.gridCommitStatuses = widget.UI.Grid("gridCommitStatuses", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,

    onInitialiseRow: gridCommitStatuses_InitialiseRow,
  });

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

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

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

  cmdBatchSave = $("#cmdBatchSave");
  cmdBatchRefresh = $("#cmdBatchRefresh");
  cmdBatchAbandon = $("#cmdBatchAbandon");
  cmdBatchDelete = $("#cmdBatchDelete");
  cmdBatchSave.click(function() { Form_ExecuteAction("BatchSave"); });
  cmdBatchRefresh.click(function() { Form_ExecuteAction("BatchRefresh"); });
  cmdBatchAbandon.click(function() { Form_ExecuteAction("BatchAbandon"); });
  cmdBatchDelete.click(function() { Form_ExecuteAction("BatchDelete"); });

  // Reset Form
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_BatchInfo = null;
  mRecord_BatchDetails = null;
  mRecord_CommitDetails = null;
  mRecord_CommitStatuses = null;
  mRecord_SplitTransaction = null;
  mRecord_Transactions = null;
  mLockedBatchId = "";
  mPostCommit = false;

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);

      // Settings
      mGrids_ShowBanking = mRecord.GridsShowBanking;
      mGrids_ShowElement = mRecord.GridsShowElement;

      // Global Collections
      mBankAccounts = mRecord.BankAccounts;
      mElements = mRecord.Elements;
      mPaymentMethods = mRecord.PaymentMethods;
      mTransactionTypes = mRecord.TransactionTypes;

      // Give Collections ability To lookup by code
      widget.ArrayAllowLookupById(mBankAccounts, "BankAccountId");
      widget.ArrayAllowLookupById(mElements, "ElementId");
      widget.ArrayAllowLookupById(mPaymentMethods, "PaymentMethodId");
      widget.ArrayAllowLookupById(mTransactionTypes, "TransactionTypeId");

      // Load Fields
      Fields_Load();
    },

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

// ===========
// Record Save
// ===========
function Record_Save(moveUnallocatedToSuspense, callback) {
  // Save non-Transaction Batch Details
  Fields_Save_BatchDetails();

  // Block UI
  if (moveUnallocatedToSuspense) {
    widget.UI.Block("Saving Bank Batch and moving unallocated Transactions to Suspense, please wait...");
  }
  else {
    widget.UI.Block("Saving Bank Batch, please wait...");
  }

  // Create Parameters
  var params = CreateFinishParameters();
  if (moveUnallocatedToSuspense) params.moveUnallocatedToSuspense = true;

  // Save
  widget.GetString("SaveBatch", params,
    // Success
    function (data) {
      // Parse
      data = JSON.parse(data);

      // Unblock UI
      widget.UI.Unblock()

      // Update Batch Id (in case auto-generated)
      C.txtBatchId.Text(data.BatchId);

      // Callback (e.g., closing form and auto-saving)
      if (callback) {
        callback();
        return;
      }

      // Prompt to continue editing
      var message = "&lt;p&gt;This Bank Batch was successfully saved.&lt;/p&gt;";
      if (moveUnallocatedToSuspense) {
        switch(data.MovedToSuspense) {
          case 0:
            message += "&lt;p&gt;No items were moved to Suspense.&lt;/p&gt;";
            break;

          case 1:
            message += "&lt;p&gt;&lt;b&gt;1&lt;/b&gt; item was moved to Suspense.&lt;/p&gt;";
            break;

          default:
            message += "&lt;p&gt;&lt;b&gt;" + data.MovedToSuspense + "&lt;/b&gt; items were moved to Suspense.&lt;/p&gt;";
            break;
        }

        if (data.CountTransactions != 0) {
          message += "&lt;p&gt;One or more items were not moved to Suspense. Reasons for this include:&lt;/p&gt;";
          message += "&lt;ul&gt;";
          message += "&lt;li&gt;Payment Method not specified&lt;/li&gt;";
          message += "&lt;li&gt;No Payment split lines defined&lt;/li&gt;";
          message += "&lt;li&gt;Payment is allocated or partially allocated to an Account&lt;/li&gt;";
          message += "&lt;/ul&gt;";
        }
      }
      message += "&lt;p&gt;Do you wish to continue editing this Bank Batch?&lt;/p&gt;";
      if (tabWizard.SelectedTabId() == "Items") {
        message += "&lt;p&gt;&lt;b&gt;NOTE:&lt;/b&gt; To ensure all information is up-to-date, the Transactions grid will be reloaded.&lt;/p&gt;";
      }

      widget.UI.MsgBoxConfirm(message, { heading: "Bank Batch Saved", messageIsHtml: true, captionOk: "Yes", captionCancel: "No" },
        function () {
          // Reload Transactions so that original indexes etc are all up-to-date with changes
          if (mRecord_Transactions) {
            // Force reload
            mRecord_Transactions = null;

            // Reload now?
            if (tabWizard.SelectedTabId() == "Items") {
              // Move back a tab
              tabWizard.SelectedTabId("Details");
              tabWizard_UpdateButtons();

              // Reload (bypassing any prompts and then moving to the Items tab)
              tabWizard_Validate(function () { tabWizard_Move(1); }, true);
            }
          }
        },

        function () {
          Form_ExecuteAction_BatchAbandon();
        });
    },

    // Fail
    function (error) {
      // Unblock UI
      widget.UI.Unblock()

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboBatch.Text(mRecord.BatchId);
  }

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

  // Update Controls
  if (mRecord) {
    cboBatch_Change();
  }

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

function Fields_Load_BatchDetails() {
  C.txtBatchId.Text(mRecord_BatchDetails.BatchId);
  C.cboTransactionType.Text(mRecord_BatchDetails.TransactionTypeId);
  C.cboBankAccount.Text(mRecord_BatchDetails.BankAccountId);
  C.cboCashRegister.Text(mRecord_BatchDetails.CashRegisterId);
  C.numBatchTotal.Value(mRecord_BatchDetails.BatchTotal);
  C.txtNotes.Text(mRecord_BatchDetails.Notes);

  // Update Fields
  cboTransactionType_Change();
}

// ===========
// Fields Save
// ===========
function Fields_Save_BatchDetails() {
  mRecord_BatchDetails.BatchId = C.txtBatchId.Text();
  mRecord_BatchDetails.TransactionTypeId = C.cboTransactionType.Text();
  if (!mRecord_BatchDetails.Imported) {
    mRecord_BatchDetails.BankAccountId = C.cboBankAccount.Text();
  }
  mRecord_BatchDetails.CashRegisterId = C.cboCashRegister.Text();
  mRecord_BatchDetails.BatchTotal = C.numBatchTotal.Value();
  mRecord_BatchDetails.Notes = C.txtNotes.Text();
}

// ==============
// cboBankAccount
// ==============
function cboBankAccount_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Get Bank Account
  mBankAccount = mBankAccounts.GetItem(C.cboBankAccount.Text());

  // Refresh Page
  pageDetails_Refresh();
}

// ========
// cboBatch
// ========
function cboBatch_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Hide details
  C.pBatchNotLocked.hide();
  C.pBatchLockInfo.hide();
  C.cmdBatchUnlock.hide();

  // Fetch Batch details
  if (C.cboBatch.Text()) {
    C.pBatchInfo.text("Retrieving details, please wait...");
    C.divBatchInfo.show();
    cmdNext.prop("disabled", true);

    widget.GetString("GetBatchInfo", { batchId: C.cboBatch.Text() },
      function (data) {
        // Parse
        mRecord_BatchInfo = JSON.parse(data);

        // Update Summary
        if (mRecord_BatchInfo.BatchId != C.cboBatch.Text()) {
          // User changed Batch mid-callback
          C.pBatchInfo.text("Invalid Bank Batch information retrieved");
        }
        else {
          // Information
          var s = "";
          if (mRecord_BatchInfo.IsLocked) {
            s += "&lt;p style='color:red'&gt;This Bank Batch is locked and cannot be edited.&lt;/p&gt;";
          }
          s += "&lt;ul&gt;";
          s += "&lt;li&gt;Batch ID: &lt;b&gt;" + widget.UI.HtmlEncode(mRecord_BatchInfo.BatchId) + "&lt;/b&gt;&lt;/li&gt;";
          if (mRecord_BatchInfo.TransactionTypeId) s += "&lt;li&gt;Transaction Type: &lt;b&gt;" + widget.UI.HtmlEncode(mRecord_BatchInfo.TransactionTypeId) + "&lt;/b&gt;, &lt;b&gt;'" + widget.UI.HtmlEncode(mRecord_BatchInfo.TransactionTypeDescription) + "'&lt;/b&gt;&lt;/li&gt;";
          if (mRecord_BatchInfo.BankAccountId) s += "&lt;li&gt;Bank Account: &lt;b&gt;" + widget.UI.HtmlEncode(mRecord_BatchInfo.BankAccountId) + "&lt;/b&gt;, &lt;b&gt;'" + widget.UI.HtmlEncode(mRecord_BatchInfo.BankAccountDescription) + "'&lt;/b&gt;&lt;/li&gt;";
          if (mRecord_BatchInfo.CashRegisterId) s += "&lt;li&gt;Cash Register: &lt;b&gt;" + widget.UI.HtmlEncode(mRecord_BatchInfo.CashRegisterId) + "&lt;/b&gt;, &lt;b&gt;'" + widget.UI.HtmlEncode(mRecord_BatchInfo.CashRegisterDescription) + "'&lt;/b&gt;&lt;/li&gt;";
          s += "&lt;/ul&gt;";
          C.pBatchInfo.html(s);

          // Lock Info
          if (mRecord_BatchInfo.IsLocked) {
            C.pBatchNotLocked.hide();
            C.pBatchLockInfo.show();

            var s = "&lt;ul&gt;"
            s += "&lt;li&gt;Locked by: &lt;b&gt;" + widget.UI.HtmlEncode(mRecord_BatchInfo.LockedByUserId) + "&lt;/b&gt;, &lt;b&gt;'" + widget.UI.HtmlEncode(mRecord_BatchInfo.LockedByUserName) + "'&lt;/b&gt;&lt;/li&gt;";
            s += "&lt;li&gt;Locked: &lt;b&gt;" + mRecord_BatchInfo.LockedDate + "&lt;/b&gt;&lt;/li&gt;";
            s += "&lt;/ul&gt;";
            C.pBatchLockInfo.html(s);

            // Allow Unlock
            if (mRecord_BatchInfo.CanUnlock) {
             C.cmdBatchUnlock.show();
            }
            else {
              C.cmdBatchUnlock.hide();
            }
          }
          else {
            C.pBatchNotLocked.show();
            C.pBatchLockInfo.hide();
          }

          // Enable Next button if not locked
          if (!mRecord_BatchInfo.IsLocked) cmdNext.prop("disabled", false);
        }
      },

      function (error) {
        widget.UI.MsgBoxAlert(error);
      }
    );
  }
  else {
    C.divBatchInfo.hide();
  }
}

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

  // Get Transaction Type
  mTransactionType = mTransactionTypes.GetItem(C.cboTransactionType.Text());

  // Defaults (if changed by User)
  if (e &amp;&amp; mTransactionType) {
    if (mTransactionType.DefaultBankAccountId) {
      C.cboBankAccount.Text(mTransactionType.DefaultBankAccountId);
    }
  }

  // Update Controls
  cboBankAccount_Change();

  // Refresh Page
  pageDetails_Refresh();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    BatchDetails: mRecord_BatchDetails
  }

  // Add Transactions (but clear information-only details)
  if (mRecord_Transactions) {
    var transactions = JSON.parse(JSON.stringify(mRecord_Transactions));
    for (var i = 0; i &lt; transactions.length; i++) {
      var transaction = transactions[i];
      transaction.ImportDetails = null;
    }

    params.Transactions = transactions;
  }

  return params;
}

// =============
// Fields Update
// =============
function Fields_Update() {
  // Information Lists

  // Lists
  if (mRecord) {
    C.cboBatch.RefreshFromCollection(mRecord.BatchList, "BatchId", "", "BatchId,TransactionTypeId,CreatedUserId,CreatedDate,Notes");
    C.cboTransactionType.RefreshFromStandardRange("TransactionTypes", mRecord.TransactionTypesSqlWhere);
    C.cboBankAccount.RefreshFromStandardRange("BankAccounts", mRecord.BankAccountsSqlWhere);
    if (mRecord.ShowCashRegister) C.cboCashRegister.RefreshFromStandardRange("CashRegisters");

    // frmBatchNew
    C.cboNewTransactionType.RefreshFromStandardRange("TransactionTypes", mRecord.TransactionTypesSqlWhere);
    C.cboNewBankAccount.RefreshFromStandardRange("BankAccounts", mRecord.BankAccountsSqlWhere);
  }

  // Controls
  if (mRecord) {
    C.cboCashRegister.VisibleRow(mRecord.ShowCashRegister);
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

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

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "BATCHABANDON":
      // Abandon Changes
      if (mPostCommit) {
        if (mLockedBatchId) {
          Form_ExecuteAction_BatchAbandon();
        }
        else {
          Form_Reset();
        }
      }
      else {
        widget.UI.MsgBoxConfirm("&lt;p&gt;Cancelling edit will:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Lose any unsaved changes you have made&lt;/li&gt;&lt;li&gt;Unlock this Bank Batch&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Are you sure you want to continue?&lt;/p&gt;", { heading: "Cancel Edit", messageIsHtml: true },
          function () {
            Form_ExecuteAction_BatchAbandon();
          });
      }
      break;

    case "BATCHDELETE":
      // Delete Batch
      widget.UI.MsgBoxConfirmDelete("Are you sure you want to PERMANENTLY delete this Bank Batch?", { heading: "Delete Bank Batch" }, Form_ExecuteAction_BatchDelete);
      break;

    case "BATCHREFRESH":
      // Refresh Batch (to allow edit after commit)
      Form_ExecuteAction_BatchRefresh();
      break;

    case "BATCHSAVE":
      // Save Batch
      if (tabWizard.Validate(true)) {
        if (mRecord.PromptOnCommit) {
          widget.UI.MsgBoxConfirm("Are you sure you want save the changes you have made to this Bank Batch?", { heading: "Save Changes" },
            function () {
              Record_Save(false);
            }
          );
        }
        else {
          Record_Save(false);
        }
      }
      break;

    case "FINISH":
      // Finish
      if (mRecord.ReadOnly || mPostCommit) {
        tabWizard_Cancel();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;

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

function Form_ExecuteAction_BatchRefresh() {
  var transactionsLoaded = (mRecord_Transactions != null);
  var gotoItemsPage = false;

  // Abandon Commit Details Simple page
  if (tabWizard.SelectedTabId() == "CommitDetailsSimple") {
    tabWizard_Refresh(1);

    // Force Transactions to load (more streamlined this way)
    transactionsLoaded = true;
    gotoItemsPage = true;
  }

  // Block UI
  widget.UI.Block("Refreshing Bank Batch, please wait...");

  widget.GetString("RefreshBatch", { batchPk: mRecord_BatchDetails.BatchPk, includeTransactions: transactionsLoaded },
    function (data) {
      // Parse
      data = JSON.parse(data);
      mRecord_BatchDetails = data.BatchDetails;
      if (data.Transactions) mRecord_Transactions = data.Transactions;

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

      // Finalise
      mPostCommit = false;
      mRecord_CommitDetails = null;
      mRecord_CommitStatuses = null;

      Fields_Load_BatchDetails();
      pageDetails_Refresh();
      if (gotoItemsPage) tabWizard.SelectedTabId("Items");
      if (tabWizard.SelectedTabId() == "Items") gridTransactions_Refresh();
      tabWizard_UpdateButtons();
    },

    function (error) {
      // Unblock UI
      widget.UI.Unblock();

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

function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function() {
    // Confirm (ignore setting since prompt contains summary information we always want to show)
    if (true) { //mRecord.PromptOnCommit) {
      Form_ExecuteAction_FinishCommitBatch();
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishCommitBatch() {
  // Confirm
  var heading = "Commit Bank Batch";
  var message = "&lt;p&gt;Are you sure you want to save and commit this Bank Batch?&lt;/p&gt;";
  message += "&lt;ul&gt;";
  message += "&lt;li&gt;Batch ID: &lt;b&gt;" + widget.UI.HtmlEncode(C.txtBatchId.Text()) + "&lt;/b&gt;&lt;/li&gt;";
  message += "&lt;li&gt;Transaction Type: &lt;b&gt;" + widget.UI.HtmlEncode(C.cboTransactionType.Text()) + "&lt;/b&gt;, &lt;b&gt;" + widget.UI.HtmlEncode(C.cboTransactionType.GetDescription()) + "&lt;/b&gt;&lt;/li&gt;";
  message += "&lt;li&gt;Bank Account: &lt;b&gt;" + widget.UI.HtmlEncode(C.cboBankAccount.Text()) + "&lt;/b&gt;, &lt;b&gt;" + widget.UI.HtmlEncode(C.cboBankAccount.GetDescription()) + "&lt;/b&gt;&lt;/li&gt;";
  message += "&lt;/ul&gt;";

  widget.UI.MsgBoxConfirm(message,
                          {
                            heading: heading,
                            messageIsHtml: true,
                          },
                          Form_ExecuteAction_FinishPost,
                          null);

}

function Form_ExecuteAction_FinishPost() {
  // Block UI
  widget.UI.Block("Saving Bank Batch, please wait...");

  // Save non-Transaction Batch Details
  Fields_Save_BatchDetails();

  // Get Parameters
  var params = CreateFinishParameters();

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

      // Update Batch Id (in case auto-generated)
      C.txtBatchId.Text(data.BatchId);

      // Commit
      Form_ExecuteAction_FinishPost_Commit(data.BatchPk);
    },

    function (error) {
      // Unblock UI
      widget.UI.Unblock();

      // Show Error
      widget.UI.MsgBoxAlert(error);
   }
  );
}

function Form_ExecuteAction_FinishPost_Commit(batchPk) {
  // Block UI
  widget.UI.Block("Committing Bank Batch, please wait...");

  // Commit
  widget.GetString("Finish", { batchPk: batchPk },
    function (data) {
      // Parse
      data = JSON.parse(data);
      mRecord_CommitDetails = data;
      mRecord_CommitStatuses = data.CommitStatuses;

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

      // Batch is now read-only and cannot be updated without reloading
      mPostCommit = true;
      pageDetails_Refresh();
      if (mRecord_Transactions) {
        gridTransactions_Refresh();
      }
      else if (data.HasUncommittedTransactions) {
        gridCommitStatuses_Refresh();
        tabWizard_Refresh(3);
      }

      // Warnings
      if(data.HasUncommittedTransactions || data.Warning) {
        var message = "";
        if (data.Warning) {
          message = data.Warning;
        }
        else if (data.PartiallyCommitted) {
          message = "&lt;p&gt;Batch was only partially committed.&lt;/p&gt;";
        }
        else {
          message = "&lt;p&gt;No Transactions were committed.&lt;/p&gt;";
        }

        message += "&lt;p&gt;Check individual items for Errors.&lt;/p&gt;";
        if (!mRecord_Transactions) {
          message += "&lt;p&gt;To view full transaction details and individual errors, you will need to reload this Bank Batch and perform a 'Commit' from the Transactions page.&lt;/p&gt;";
        }
        message += "&lt;p&gt;&lt;b&gt;NOTE:&lt;/b&gt; All details on this form are now read-only. Use the 'Refresh' button to re-load and edit this Bank Batch.&lt;/p&gt;";

        widget.UI.MsgBoxAlert(message, { heading: "Commit Warnings", messageIsHtml: true }, function () {
          Form_ExecuteAction_FinishPost_Commit_Done(data);
        });
      }
      else {
        // Clear Batch since it will no longer exist
        mLockedBatchId = "";
        C.cboBatch.Text("");

        // Notify
        widget.UI.MsgBoxInfo("Batch was successfully committed.", {}, function () {
          Form_ExecuteAction_FinishPost_Commit_Done(data);
        });
      }

      // Update Buttons
      tabWizard_UpdateButtons();
    },

    function (error) {
      // Unblock UI
      widget.UI.Unblock();

      // Show Error
      widget.UI.MsgBoxAlert(error);
   }
  );
}

function Form_ExecuteAction_FinishPost_Commit_Done(data) {
}

function Form_ExecuteAction_BatchAbandon(callback) {
  // Block UI
  if (mPostCommit) {
    widget.UI.Block("Unlocking Bank Batch, please wait...");
  }
  else {
    widget.UI.Block("Cancelling edit, please wait...");
  }

  widget.GetString("UnlockBatch", { batchPk: mRecord_BatchInfo.BatchPk, isCurrentBatch: true },
    function (data) {
      // Unblock UI
      widget.UI.Unblock();

      // Reset
      if (callback) {
        callback();
      }
      else {
        Form_Reset();
      }
    },

    function (error) {
      // Unblock UI
      widget.UI.Unblock();

      // Show Error
      widget.UI.MsgBoxAlert(error);
    }
  );
}

function Form_ExecuteAction_BatchDelete() {
  // Block UI
  widget.UI.Block("Deleting Bank Batch, please wait...");

  widget.GetString("DeleteBatch", { batchPk: mRecord_BatchInfo.BatchPk },
    function (data) {
      // Unblock UI
      widget.UI.Unblock();

      // Reset
      C.cboBatch.Text("");
      Form_Reset();
    },

    function (error) {
      // Unblock UI
      widget.UI.Unblock();

      // Show Error
      widget.UI.MsgBoxAlert(error);
    }
  );
}

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

  // Tab
  tabWizard_Resize();
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Notify if Batch is Locked
  if (mLockedBatchId) {
    var message = "&lt;p&gt;You are attempting to close this form and have Bank Batch '&lt;b&gt;" + widget.UI.HtmlEncode(mLockedBatchId) + "&lt;/b&gt;' locked.&lt;/p&gt;&lt;p&gt;Use the 'Cancel Edit' button to unlock this Bank Batch.&lt;p&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;If you continue, neither you or any other User will be able to edit this Bank Batch without first unlocking it.&lt;/p&gt;&lt;p&gt;Are you sure you want to continue?&lt;/p&gt;";
    var additionalButtons = [{ actionId: "CloseNoSave", caption: "Close Without Save", buttonStyle: "danger" }];

    widget.UI.MsgBoxConfirm(message, { messageIsHtml: true, heading: "Batch Locked", icon: "Warning", captionOk: "Save and Close", additionalButtons: additionalButtons }, tabWizard_Cancel_Done);
  }
  else {
    tabWizard_Cancel_Done();
  }
}

function tabWizard_Cancel_Done(actionId) {
  switch(actionId) {
    case "Ok":
      // Save and Close
      Record_Save(false, function () {
        Form_ExecuteAction_BatchAbandon(tabWizard_Cancel_Done_Close);
      });
      break;

    case "CloseNoSave":
      // Close without Save
      Form_ExecuteAction_BatchAbandon(tabWizard_Cancel_Done_Close);
      break;

    default:
      tabWizard_Cancel_Done_Close();
      break;
  }

}

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

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

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "Details":
        C.bTransactionCount.text(mRecord_BatchDetails.TransactionCount);
        break;

      case "Items":
        divTransactionsSummary_Refresh();
        break;
    }
  }

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

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Items":
      var summary = "Batch '" + mRecord_BatchDetails.BatchId + "', Transaction Type " + C.cboTransactionType.Text() + ", '" + C.cboTransactionType.GetDescription() + "'";
      if (mRecord_BatchDetails.Imported) summary = "Imported " + summary;

      frmMain.RefreshHeading("Transactions for " + C.cboBankAccount.Text() + ", '" + C.cboBankAccount.GetDescription() + "'", summary);
      break;

    case "CommitDetailsSimple":
      var summary = "Batch '" + mRecord_BatchDetails.BatchId + "', Transaction Type " + C.cboTransactionType.Text() + ", '" + C.cboTransactionType.GetDescription() + "'";
      if (mRecord_BatchDetails.Imported) summary = "Imported " + summary;

      frmMain.RefreshHeading("Commit Details", summary);
      break;

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

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

  // Resize Wizard
  tabWizard_Resize();

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "Options":
      C.txtNotes.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  var tabIndex = tabWizard.SelectedTabIndex();

  // Back, Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    // Back and Next Buttons?
    cmdBack.prop("disabled", tabIndex &lt; 1);
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 2);
  }

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

  // Exceptions
  cmdFinish.text("Commit");
  if ((mLockedBatchId || mPostCommit) &amp;&amp; tabIndex == 1) cmdBack.prop("disabled", true);

  // Other Buttons
  if (mPostCommit) {
    if (mLockedBatchId) {
      // Still locked, i.e., still Transactions to commit
      cmdBatchRefresh.show();
      cmdBatchAbandon.text("Unlock Batch");

      cmdBatchSave.hide();
      cmdBatchDelete.hide();

      cmdBack.prop("disabled", true);
      cmdFinish.prop("disabled", true);
    }
    else {
      // Fully committed, nothing left to do
      cmdBatchSave.hide();
      cmdBatchRefresh.hide();
      cmdBatchDelete.hide();

      cmdBatchAbandon.show();
      cmdBatchAbandon.text("Reset Form");

      cmdFinish.text("Close");
      cmdFinish.prop("disabled", false);
    }

    if (!mRecord_Transactions) cmdNext.prop("disabled", true);
  }
  else if (mLockedBatchId) {
    cmdBatchSave.show();
    cmdBatchRefresh.hide();
    cmdBatchAbandon.text("Cancel Edit");
    cmdBatchAbandon.show();
    cmdBatchDelete.show();
  }
  else {
    cmdBatchSave.hide();
    cmdBatchRefresh.hide();
    cmdBatchAbandon.hide();
    cmdBatchDelete.hide();
  }
}

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

  // Other client-side validation
  if (Ok &amp;&amp; !skipClientSide) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        break;

      case "Details":
        if (!mRecord_Transactions &amp;&amp; mRecord_BatchDetails.TransactionCount &gt; mRecord.TransactionLoadCountPrompt) {
          widget.UI.MsgBoxConfirm("&lt;p&gt;All &lt;b&gt;" + mRecord_BatchDetails.TransactionCount + "&lt;/b&gt; Transactions in this Bank Batch are about to be loaded.&lt;/p&gt;&lt;p&gt;Are you sure you want to continue?&lt;/p&gt;", { heading: "Load Transactions", messageIsHtml: true },
            function () {
              tabWizard_Validate(validCallback, true);
            });
          return;
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        params = { batchId: mRecord_BatchInfo.BatchId };
        break;

      case "Details":
        if (!mRecord_Transactions) params = { batchPk: mRecord_BatchInfo.BatchPk };
        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
        mLockedBatchId = C.cboBatch.Text();
        mRecord_BatchDetails = o.Data;

        // Clear Transactions just in case!
        mRecord_Transactions = null;

        // Load Fields
        Fields_Load_BatchDetails();

        // Other
        C.divBatchDetails.show();

        // Refresh Page
        pageDetails_Refresh();
        break;

      case "Details":
        // Details
        mRecord_Transactions = o.Data;

        // Other
        C.divBatchDetails.hide();

        // Refresh Grid
        gridTransactions_Refresh();
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ============
// Unlock Batch
// ============
function BatchUnlock() {
  // Confirm
  widget.UI.MsgBoxConfirm("&lt;p&gt;Are you sure you want to unlock this Bank Batch?&lt;/p&gt;&lt;p&gt;&lt;b&gt;WARNING:&lt;/b&gt; Unlocking a Bank Batch that is being edited by another User may cause them to lose any changes they have made.&lt;/p&gt;", { heading: "Unlock Bank Batch", messageIsHtml: true, icon: "Lock|Delete" },
    function () {
      // Block UI
      widget.UI.Block("Unlocking Batch, please wait...");

      widget.GetString("UnlockBatch", { batchPk: mRecord_BatchInfo.BatchPk },
        function (data) {
          // Unblock UI
          widget.UI.Unblock();

          // Refresh
          cboBatch_Change();
        },

        function (error) {
          // Unblock UI
          widget.UI.Unblock();

          // Show Error
          widget.UI.MsgBoxAlert(error);
        }
      );
    }
  );
}

// ================
// gridTransactions
// ================
function gridTransactions_Refresh() {
  // Post-Commit, everything should be read-only
  C.gridTransactions.ReadOnly(mPostCommit);

  // Can add a new row?
  C.gridTransactions.AllowAddRows(!mRecord_BatchDetails.Imported);

  // Add Columns
  C.gridTransactions.ClearColumns();
  C.gridTransactions.AddColumnIcon("Icon", { caption: "" });
  if (mPostCommit) {
    C.gridTransactions.AddColumnString("CommitStatus", { caption: "Commit Status", width: "30%" });
  }
  C.gridTransactions.AddColumnInteger("SplitCount", { caption: "Splits", width: "20px", visible: !mPostCommit });
  C.gridTransactions.AddColumnCode("AccountId", { caption: "Account", width: widget.UI.FIELD_WIDTH_CODE_10, allowEdit: true, standardRange: "Accounts", sqlWhere: "", displayColumns: "AccountId,Name" });
  if (!mPostCommit) {
    C.gridTransactions.AddColumnString("AccountName", { caption: "Name", width: "30%" });
  }
  C.gridTransactions.AddColumnDate("Date", { caption: "Date", allowEdit: !mRecord_BatchDetails.Imported });
  C.gridTransactions.AddColumnString("ElementId", { caption: "Element", width: "6em", allowEdit: true, visible: mGrids_ShowElement, list: mTransactionType.ElementsListTag, columns: "ElementId,Description,ElementTypeText", idColumn: "ElementId" });
  C.gridTransactions.AddColumnCurrency("Value", { caption: "Value", allowEdit: !mRecord_BatchDetails.Imported });
  C.gridTransactions.AddColumnString("PaymentMethodId", { caption: "Pay Method", width: "6em", allowEdit: true, columns: "PaymentMethodId,Description", idColumn: "PaymentMethodId" });
  if (mRecord_BatchDetails.Imported) {
    C.gridTransactions.AddColumnBoolean("UpdateAccountBankMatch", { caption: "Update Match", allowEdit: true });
  }
  C.gridTransactions.AddColumnString("Reference", { caption: "Reference", width: "6em", allowEdit: true });

  if (mGrids_ShowBanking) {
    C.gridTransactions.AddColumnString("BankAccountName", { caption: "Account Name", width: "12em", allowEdit: true });
    C.gridTransactions.AddColumnString("BankAccountNumber", { caption: "Account No.", width: "8em", allowEdit: true });
    C.gridTransactions.AddColumnString("AccountSortCode", { caption: mRecord.TerminologyBankSortCode, width: "6em", allowEdit: true, visible: mRecord.SupportsBankSortCode || mRecord.TerminologyBankSortCode });
    C.gridTransactions.AddColumnString("BankShortName", { caption: "Bank", width: "6em", allowEdit: true });
    C.gridTransactions.AddColumnString("BankBranchName", { caption: "Branch", width: "6em", allowEdit: true });
    C.gridTransactions.AddColumnString("CardSecurityCode", { caption: "CSC", width: "3em", allowEdit: true });
    C.gridTransactions.AddColumnString("CardExpiryDate", { caption: "Expires", width: "4em", allowEdit: true });
    C.gridTransactions.AddColumnString("BankReference", { caption: "Bank Reference", width: "6em", allowEdit: true });
  }

  C.gridTransactions.AddColumnString("Notes", { caption: "Notes", allowEdit: true, width: "30%" });

  // Actions
  var actions = [];
  if (!mPostCommit) {
    actions.push({ actionId: "DeleteRow", tooltipText: "Remove row", icon: "Delete" });
    if (!mRecord_BatchDetails.Imported) {
      actions.push({});
      actions.push({ actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" });
      actions.push({ actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });
    }    
    actions.push({});
  }
  if (!mPostCommit) {
    actions.push({ actionId: "ToSuspense", tooltipText: "Send unallocated items to the Suspense Account", icon: "BankTransaction_Suspense", caption: "To Suspense" });
    actions.push({});
  }
  actions.push({ actionId: "ToggleElement", tooltipText: "Show/ hide element columns", icon: "Grid_Column", caption: "Element", checked: mGrids_ShowElement });
  actions.push({ actionId: "ToggleBanking", tooltipText: "Show/ hide banking columns", icon: "Grid_Column", caption: "Banking", checked: mGrids_ShowBanking });
  C.gridTransactions.Actions().Define(actions);

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mRecord_Transactions.GetCacheKey = function (index) {
    var item = mRecord_Transactions[index];
    return index + "|" + item.Date + "|" + item.UpdateAccountBankMatch + "|" + item.Splits[0].AccountId;
  };
  mRecord_Transactions.GetPreviewFetchParameters = function (index) {
    var item = mRecord_Transactions[index];
    var split1 = item.Splits[0];
    var o = {};

    o.transactionDate = item.Date;
    o.paymentMethodId = item.PaymentMethodId;
    o.importDetails = item.ImportDetails;
    o.updateAccountBankMatch = item.UpdateAccountBankMatch;

    o.target = "WebInternal";
    o.highDpi = widget.IsHighDpi();
    return o;
  };

  // Refresh
  C.gridTransactions.VirtualDataRefresh(mRecord_Transactions);

  // Refresh Headings
  gridTransactions_RefreshHeadings();

  // Activate First Row
  C.gridTransactions.ActivateFirstDataRow();
}

function gridTransactions_InitialiseRow(e) {
  var item = mRecord_Transactions[e.row.listIndex];
  var split1 = item.Splits[0];
  var importDetails = item.ImportDetails
  var commitStatus = null;
  if (mRecord_CommitStatuses &amp;&amp; e.row.listIndex &lt; mRecord_CommitStatuses.length) commitStatus = mRecord_CommitStatuses[e.row.listIndex];

  // NOTE: For simplicity, everything editable that can be is done via the Splits collection

  // Update cells
  e.row.AutoBind(item);

  // Split-based cells
  e.row.cells.SplitCount.value = item.Splits.length;
  if (item.Splits.length &gt; 1) {
    e.row.cells.AccountId.value = split1.AccountId + "+";
    if (e.row.cells.AccountName) e.row.cells.AccountName.value = "(multiple Accounts)";
    e.row.cells.ElementId.value = split1.ElementId + "+";
  }
  else {
    e.row.cells.AccountId.value = split1.AccountId;
    if (e.row.cells.AccountName) e.row.cells.AccountName.value = split1.AccountName;
    e.row.cells.ElementId.value = split1.ElementId;
  }

  // Commit Status
  if (commitStatus) {
    if (commitStatus.Committed) {
      e.row.cells.CommitStatus.value = "Committed";
      e.row.cells.CommitStatus.colour = "limegreen";
    }
    else if(commitStatus.CommitError) {
      e.row.cells.CommitStatus.value = commitStatus.CommitError;
      e.row.cells.CommitStatus.colour = "red";
    }
  }

  // Total Value
  var value = split1.Value;
  for (var i = 1; i &lt; item.Splits.length; i++) {
    value += item.Splits[i].Value;
  }
  e.row.cells.Value.value = value;

  // Icon
  if (commitStatus) {
    if (commitStatus.Committed) {
      e.row.cells.Icon.value = "Ok";
    }
    else if (commitStatus.CommitError) {
      e.row.cells.Icon.value = "Error";
    }
  }
  else if (split1.Warning) {
    e.row.cells.Icon.value = "Warning";
  }
  else {
    e.row.cells.Icon.value = null;
  }

  // Tooltip
  e.row.cells.Icon.tooltipText = split1.Warning;

  // Colour cells to show read-only state
  e.row.cells.Icon.readOnly = true;
  e.row.cells.SplitCount.readOnly = true;
  if (e.row.cells.AccountName) e.row.cells.AccountName.readOnly = true;
  e.row.cells.Date.readOnly = mRecord_BatchDetails.Imported;
  e.row.cells.Value.readOnly = true;

  // Validation colouring
  if (importDetails) {
    if (value == importDetails.Value) {
      e.row.cells.Value.backgroundColour = "";
      e.row.cells.Value.colour = "";
    }
    else {
      e.row.cells.Value.backgroundColour = "red";
      e.row.cells.Value.colour = "white";
    }
  }

  // Update Match?
  if (mRecord_BatchDetails.Imported) {
    e.row.cells.UpdateAccountBankMatch.readOnly = (item.ImportedMatch.length == 0);
  }

  // Lock columns if split
  var split = (item.Splits.length &gt; 1);
  e.row.cells.AccountId.readOnly = split;
  e.row.cells.ElementId.readOnly = split;
  e.row.cells.Value.readOnly = split;

  // Payment Type Category Specific
  if (mGrids_ShowBanking) {
    var paymentMethod = mPaymentMethods.GetItem(item.PaymentMethodId)
    if (paymentMethod) {
      switch(paymentMethod.PaymentTypeCategory) {
        case "Bank":
          // ====
          // Bank
          // ====
          e.row.cells.BankAccountNumber.notApplicable = false;
          e.row.cells.BankAccountName.notApplicable = false;
          e.row.cells.CardSecurityCode.notApplicable = true;
          e.row.cells.CardExpiryDate.notApplicable = true;
          e.row.cells.BankReference.notApplicable = true;

          switch(mRecord.CountryCode) {
            case "AU":
              e.row.cells.AccountSortCode.notApplicable = false;
              e.row.cells.BankShortName.notApplicable = true;
              e.row.cells.BankBranchName.notApplicable = true;
              break;

            case "NZ":
              e.row.cells.AccountSortCode.notApplicable = true;
              e.row.cells.BankShortName.notApplicable = true;
              e.row.cells.BankBranchName.notApplicable = true;
              break;

            default:
              e.row.cells.AccountSortCode.notApplicable = false;
              e.row.cells.BankShortName.notApplicable = false;
              e.row.cells.BankBranchName.notApplicable = false;
              break;
          }
          break;

        case "Cash":
          // ====
          // Cash
          // ====
          e.row.cells.BankAccountNumber.notApplicable = true;
          e.row.cells.BankAccountName.notApplicable = true;
          e.row.cells.AccountSortCode.notApplicable = true;
          e.row.cells.BankShortName.notApplicable = true;
          e.row.cells.BankBranchName.notApplicable = true;
          e.row.cells.CardSecurityCode.notApplicable = true;
          e.row.cells.CardExpiryDate.notApplicable = true;
          e.row.cells.BankReference.notApplicable = true;
          break;

        case "Cheque":
          // ======
          // Cheque
          // ======
          e.row.cells.BankAccountNumber.notApplicable = true;
          e.row.cells.BankAccountName.notApplicable = false;
          e.row.cells.CardSecurityCode.notApplicable = true;
          e.row.cells.CardExpiryDate.notApplicable = true;
          e.row.cells.BankReference.notApplicable = false;

          if (paymentMethod.PaymentFlowDirection == "Incoming") {
            e.row.cells.AccountSortCode.notApplicable = false;
            e.row.cells.BankShortName.notApplicable = false;
            e.row.cells.BankBranchName.notApplicable = false;
          }
          else {
            e.row.cells.AccountSortCode.notApplicable = true;
            e.row.cells.BankShortName.notApplicable = true;
            e.row.cells.BankBranchName.notApplicable = true;
          }
          break;

        case "CreditCard":
          // ===========
          // Credit Card
          // ===========
          e.row.cells.BankAccountNumber.notApplicable = false;
          e.row.cells.BankAccountName.notApplicable = false;
          e.row.cells.AccountSortCode.notApplicable = true;
          e.row.cells.BankShortName.notApplicable = true;
          e.row.cells.BankBranchName.notApplicable = true;
          e.row.cells.CardSecurityCode.notApplicable = !paymentMethod.CardSecurityCodeRequired;
          e.row.cells.CardExpiryDate.notApplicable = false;
          e.row.cells.BankReference.notApplicable = false;
          break;

        case "PosCard":
          // ========
          // POS Card
          // ========
          e.row.cells.BankAccountNumber.notApplicable = false;
          e.row.cells.BankAccountName.notApplicable = false;
          e.row.cells.AccountSortCode.notApplicable = true;
          e.row.cells.BankShortName.notApplicable = true;
          e.row.cells.BankBranchName.notApplicable = true;
          e.row.cells.CardSecurityCode.notApplicable = !paymentMethod.CardSecurityCodeRequired;
          e.row.cells.CardExpiryDate.notApplicable = false;
          e.row.cells.BankReference.notApplicable = true;
          break;

        case "Token":
          // =====
          // Token
          // =====
          e.row.cells.BankAccountNumber.notApplicable = false;
          e.row.cells.BankAccountName.notApplicable = false;
          e.row.cells.AccountSortCode.notApplicable = true;
          e.row.cells.BankShortName.notApplicable = true;
          e.row.cells.BankBranchName.notApplicable = true;
          e.row.cells.CardSecurityCode.notApplicable = true;
          e.row.cells.CardExpiryDate.notApplicable = true;
          e.row.cells.BankReference.notApplicable = false;
          break;

        default:
          console.warn("Unhandled Payment Type in gridTransactions_InitialiseRow");
          break;
      }
    }
    else {
      e.row.cells.BankAccountNumber.notApplicable = true;
      e.row.cells.BankAccountName.notApplicable = true;
      e.row.cells.AccountSortCode.notApplicable = true;
      e.row.cells.BankShortName.notApplicable = true;
      e.row.cells.BankBranchName.notApplicable = true;
      e.row.cells.CardSecurityCode.notApplicable = true;
      e.row.cells.CardExpiryDate.notApplicable = true;
      e.row.cells.BankReference.notApplicable = true;
    }
  }

  // Cell Styles
  if (e.row.cells.AccountName) e.row.cells.AccountName.small = true;
  if (e.row.cells.CommitStatus) e.row.cells.CommitStatus.small = true;

  // Post Commit?
  if (mPostCommit) {
    for (var k in e.row.cells) {
      e.row.cells[k].readOnly = true;
    }
  }
}

function gridTransactions_BeforeCellUpdate(e) {
  var item = mRecord_Transactions[e.row.listIndex];
  var split1 = item.Splits[0];

  switch(e.columnKey) {
    case "AccountId":
      split1.AccountId = e.newValue;

      // Update Account Details
      UpdateAccountDetails(e.row.listIndex, 0);
      break;

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

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

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

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

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

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

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

    case "CardExpiryDate":
      item.CardExpiryDate = widget.FormatCardExpiryDate(e.newValue);
      break;

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

    case "ElementId":
      split1.ElementId = e.newValue;
      break;

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

    case "PaymentMethodId":
      item.PaymentMethodId = e.newValue;

      // Refresh column headings to be more intuitive
      gridTransactions_RefreshHeadings();
      break;

    case "UpdateAccountBankMatch":
      item.UpdateAccountBankMatch = e.newValue;
      
      // Refresh Summary      
      wbTransactions_Preview();
      break;

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

    case "Value":
      split1.Value = e.newValue;
      break;
  }

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

  // Refresh split row to update values (since some values in this grid come from the first split record)
  C.gridSplits.RefreshRow(0);

  // Refresh Summary
  divTransactionsSummary_Refresh();
}

function gridTransactions_AfterRowActivate(e) {
  // Preview
  wbTransactions_Preview();

  // Refresh Buttons
  gridTransactions_RefreshButtons();

  // Refresh Splits
  gridSplits_Refresh();

  // Payment Method List
  // NOTE: The Element can vary between splits but assume the first one to decide which type of Payment Methods to use
  if (C.gridTransactions.ActiveDataRowListIndex() != -1) {
    var split1 = mRecord_Transactions[C.gridTransactions.ActiveDataRowListIndex()].Splits[0];
    var element = mElements.GetItem(split1.ElementId);

    if (!element) {
      // Use Transaction Type's Element
      element = mElements.GetItem(mTransactionType.ElementId);
    }

    if (!mBankAccount || !element || element.PaymentMethodIncoming) {
      // Incoming
      C.gridTransactions.SetColumnList("PaymentMethodId", mBankAccount.PaymentMethodsIncomingListTag);
    }
    else {
      // Outgoing
      C.gridTransactions.SetColumnList("PaymentMethodId", mBankAccount.PaymentMethodsOutgoingListTag);
    }
  }
}

function gridTransactions_RowAdd(e) {
  // Create item
  var item = {
    AccountId: null,
    AccountName: null,
    Date: mRecord.DefaultTransactionDate,
    Notes: null,
    Value: 0,
    OrigIndex: -1, // New item

    // Splits
    Splits: [{ AccountId: null, AccountName: null, Notes: null, Value: 0, OrigIndex: -1}]
  };

  // Add
  mRecord_Transactions.push(item);
}

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

  C.gridTransactions.RefreshButtons();
}

function gridTransactions_Action(actionId) {
  var index;

  switch (actionId.toUpperCase()) {
    case "DELETEROW":
      // Delete Row
      // NOTE: This action is also called automatically by the grid if delete is pressed and a row but no cells are selected
      if (!mPostCommit) {
        C.gridTransactions.RemoveRowAndCollectionItem(C.gridTransactions.ActiveDataRowIndex());
        C.gridTransactions.Focus();

        // Clear Cache &amp; Refresh Summary for newly selected row
        C.wbTransactions.CacheClear();
        wbTransactions_Preview();

        // Refresh Buttons
        gridTransactions_RefreshButtons();                
      }
      break;

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

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

    case "TOGGLEBANKING":
      mGrids_ShowBanking = !mGrids_ShowBanking;
      index = C.gridTransactions.ActiveDataRowIndex();
      gridTransactions_Refresh();
      C.gridTransactions.ActiveDataRowIndex(index);
      break;

    case "TOGGLEELEMENT":
      mGrids_ShowElement = !mGrids_ShowElement;
      index = C.gridTransactions.ActiveDataRowIndex();
      gridTransactions_Refresh();
      C.gridTransactions.ActiveDataRowIndex(index);

      // Also affects Splits grid
      index = C.gridSplits.ActiveDataRowIndex();
      gridSplits_Refresh();
      C.gridSplits.ActiveDataRowIndex(index);
      break;

    case "TOSUSPENSE":
      // To Suspense
      var message = "&lt;p&gt;Are you sure you want to save changes to this Bank Batch and move all unallocated items to Suspense for Bank Account &lt;b&gt;" + widget.UI.HtmlEncode(C.cboBankAccount.Text()) + "&lt;/b&gt;, '&lt;b&gt;" + widget.UI.HtmlEncode(C.cboBankAccount.GetDescription()) + "&lt;/b&gt;'?";
      widget.UI.MsgBoxConfirm(message, { heading: "Move To Suspense", messageIsHtml: true, icon: "BankTransaction_Suspense"},
        function () {
          Record_Save(true);
        });
      break;

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

function gridTransactions_RefreshHeadings() {
  var card = false;
  var bank = false;

  // Analyse Payment Methods
  for (var i = 0; i &lt; mRecord_Transactions.length; i++) {
    var paymentMethod = mPaymentMethods.GetItem(mRecord_Transactions[i].PaymentMethodId)
    if (paymentMethod) {
      switch(paymentMethod.PaymentTypeCategory) {
        case "Bank":
          bank = true;
          break;

        case "CreditCard":
        case "PosCard":
          card = true;
          break;
      }
    }
  }

  // Update Headings
  var BankAccountName = "Account Name";
  var BankAccountNumber = "Account No.";

  if (card &amp;&amp; bank) {
    BankAccountName = "Account/Card Name";
    BankAccountNumber = "Account/Card No.";
  }
  else if(card) {
    BankAccountName = "Card Name";
    BankAccountNumber = "Card No.";
  }

  C.gridTransactions.ColumnCaption("BankAccountName", BankAccountName);
  C.gridTransactions.ColumnCaption("BankAccountNumber", BankAccountNumber);
}

// ==========
// gridSplits
// ==========
function gridSplits_Refresh() {
  mRecord_SplitTransaction = null;

  // Determine record to show splits for
  if (C.gridTransactions.ActiveDataRowListIndex() != -1) {
    mRecord_SplitTransaction = mRecord_Transactions[C.gridTransactions.ActiveDataRowListIndex()];
  }

  // Show/ Hide grid
  if (mRecord_SplitTransaction) {
    C.gridSplits.Visible(true);
  }
  else {
    C.gridSplits.Visible(false);
    return;
  }

  // Post-Commit, everything should be read-only
  C.gridSplits.ReadOnly(mPostCommit);

  // Add Columns
  C.gridSplits.ClearColumns();
  C.gridSplits.AddColumnIcon("Icon", { caption: "" });
  C.gridSplits.AddColumnCode("AccountId", { caption: "Account", width: widget.UI.FIELD_WIDTH_CODE_10, allowEdit: true, standardRange: "Accounts", sqlWhere: "", displayColumns: "AccountId,Name" });
  C.gridSplits.AddColumnString("AccountName", { caption: "Name", width: "30%" });
  C.gridSplits.AddColumnString("ElementId", { caption: "Element", width: "6em", allowEdit: true, visible: mGrids_ShowElement, list: mTransactionType.ElementsListTag, columns: "ElementId,Description,ElementTypeText", idColumn: "ElementId" });
  C.gridSplits.AddColumnCurrency("Value", { caption: "Value", allowEdit: true });
  C.gridSplits.AddColumnCurrency("Balance", { caption: "Balance" });
  C.gridSplits.AddColumnCurrency("BalanceOverdue", { caption: "Overdue" });
  C.gridSplits.AddColumnString("Notes", { caption: "Notes", allowEdit: true });

  // Actions
  var actions = [];
  if (!mPostCommit) {
    actions.push({ actionId: "DeleteRow", tooltipText: "Remove row", icon: "Delete" });
    actions.push({});
    actions.push({ actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" });
    actions.push({ actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });
  }
  C.gridSplits.Actions().Define(actions);

  // Refresh
  C.gridSplits.VirtualDataRefresh(mRecord_SplitTransaction.Splits);

  // Activate First Row
  C.gridSplits.ActivateFirstDataRow();
}

function gridSplits_InitialiseRow(e) {
  var item = mRecord_SplitTransaction.Splits[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Colour cells to show read-only state
  e.row.cells.Icon.readOnly = true;
  e.row.cells.AccountName.readOnly = true;
  e.row.cells.Balance.readOnly = true;
  e.row.cells.BalanceOverdue.readOnly = true;

  // Icon
  if (item.Warning) {
    e.row.cells.Icon.value = "Warning";
  }
  else {
    e.row.cells.Icon.value = null;
  }

  // Tooltip
  e.row.cells.Icon.tooltipText = item.Warning;

  // Cell Styles
  e.row.cells.AccountName.small = true;

  // Post Commit
  if (mPostCommit) {
    for (var k in e.row.cells) {
      e.row.cells[k].readOnly = true;
    }
  }
}

function gridSplits_BeforeCellUpdate(e) {
  var item = mRecord_SplitTransaction.Splits[e.row.listIndex];

  switch(e.columnKey) {
    case "AccountId":
      item.AccountId = e.newValue;

      // Update Account Details
      UpdateAccountDetails(C.gridTransactions.ActiveDataRowListIndex(), e.row.listIndex);
      break;

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

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

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

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

  // Refresh parent row to update values (since many come from the first split record)
  C.gridTransactions.RefreshRow(C.gridTransactions.ActiveDataRowListIndex());

  // Refresh Summary
  divTransactionsSummary_Refresh();
}

function gridSplits_RowAdd(e) {
  // Create item
  var item = {
    AccountId: null,
    AccountName: null,
    Notes: null,
    Value: 0,
    OrigIndex: -1, // New item
  };

  // Add
  mRecord_SplitTransaction.Splits.push(item);
}

function gridSplits_AfterRowActivate(e) {
  // Refresh Buttons
  gridSplits_RefreshButtons();
}

function gridSplits_RefreshButtons() {
  if (C.gridSplits.ActiveDataRowListIndex() == -1) {
    C.gridSplits.Actions().SetEnabled("DeleteRow", false);
    C.gridSplits.Actions().SetEnabled("RowMoveUp", false);
    C.gridSplits.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    C.gridSplits.Actions().SetEnabled("DeleteRow", mRecord_SplitTransaction &amp;&amp; mRecord_SplitTransaction.Splits.length &gt; 1);
    C.gridSplits.Actions().SetEnabled("RowMoveUp", C.gridSplits.ActiveDataRowListIndex() &gt; 0);
    C.gridSplits.Actions().SetEnabled("RowMoveDown", C.gridSplits.ActiveDataRowListIndex() &lt; mRecord_SplitTransaction.Splits.length - 1);
  }

  C.gridSplits.RefreshButtons();
}

function gridSplits_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "DELETEROW":
      // Delete Row
      // NOTE: This action is also called automatically by the grid if delete is pressed and a row but no cells are selected
      if (!mPostCommit &amp;&amp; mRecord_SplitTransaction.Splits.length &gt; 1) {
        C.gridSplits.RemoveRowAndCollectionItem(C.gridSplits.ActiveDataRowIndex());
        C.gridSplits.Focus();

        // Refresh Buttons
        gridSplits_RefreshButtons();

        // Refresh Transactions grid row to re-total
        C.gridTransactions.RefreshRow(C.gridTransactions.ActiveDataRowListIndex());
      }
      break;

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

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

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

// ==============
// wbTransactions
// ==============
function wbTransactions_Preview() {
  C.wbTransactions.PreviewFromGridCollection(C.gridTransactions, mRecord_Transactions, "GetTransactionPreview");
}

// ======================
// divTransactionsSummary
// ======================
function divTransactionsSummary_Refresh() {
  var total = 0;

  // Total
  for (var i = 0; i &lt; mRecord_Transactions.length; i++) {
    for (var j = 0; j &lt; mRecord_Transactions[i].Splits.length; j++) {
      total += mRecord_Transactions[i].Splits[j].Value;
    }
  }

  // Avoid rounding issues
  total = widget.RoundCurrency(total);

  // Message
  if (C.numBatchTotal.Value() == 0 || total == C.numBatchTotal.Value()) {
    C.divTransactionsSummary.html("&lt;b&gt;" + widget.FormatCurrency(total, true) + "&lt;/b&gt;");
  }
  else {
    var diff;
    if (total &gt; C.numBatchTotal.Value()) {
      diff = "&lt;b style='color:green'&gt;&lt;small&gt;+" + widget.FormatNumber(total - C.numBatchTotal.Value(), -1, true) + "&lt;/small&gt;&lt;/b&gt;";
    }
    else {
      diff = "&lt;b style='color:red'&gt;&lt;small&gt;-" + widget.FormatNumber(C.numBatchTotal.Value() - total, -1, true) + "&lt;/small&gt;&lt;/b&gt;";
    }
    C.divTransactionsSummary.html("&lt;b style='color:red'&gt;" + widget.FormatCurrency(total, true) + "&lt;/b&gt; &lt;small&gt;expected&lt;/small&gt; &lt;b&gt;" + widget.FormatCurrency(C.numBatchTotal.Value(), true) + "&lt;/b&gt; (" + diff + ")");
  }
}

// ======================================
// Update Account Details on Split record
// =======================================
function UpdateAccountDetails(transactionIndex, splitIndex) {
  var transaction = mRecord_Transactions[transactionIndex];
  var split = transaction.Splits[splitIndex];

  // Clear informational values
  transaction.AccountName = null;

  split.AccountName = null;
  split.Balance = null;
  split.BalanceOverdue = null;
  split.BalanceOverdueC = null;
  split.Warning = null;
  split.Info = null;

  // Lookup
  if (split.AccountId) {
   widget.GetString("GetAccountDetails", { transactionDate: transaction.Date, accountId: split.AccountId },
      function (data) {
        // Parse
        data = JSON.parse(data);

        // Update objects
        transaction.accountId = data.AccountId;
        transaction.AccountName = data.AccountName;

        split.AccountName = data.AccountName;
        split.Balance = data.Balance;
        split.BalanceOverdue = data.BalanceOverdue;
        split.BalanceOverdueC = data.BalanceOverdueC;
        split.Warning = data.Warning

        // Refresh Grid rows
        C.gridTransactions.RefreshRow(transactionIndex);
        C.gridSplits.RefreshRow(splitIndex);
      },

      function (error) {
        // Ignore
        console.warn(error);
      }
    );
  }
}

// ===========
// pageDetails
// ===========
function pageDetails_Refresh() {
  // Update Controls
  if (mTransactionType) {
    C.txtBatchId.AllowBlank(mTransactionType.BatchIdAllowBlank);
  }
  else {
    C.txtBatchId.AllowBlank(false);
  }

  if (mBankAccount) {
    C.cboCashRegister.AllowBlank(mBankAccount.CashRegisterAllowBlank);
  }
  else {
    C.cboCashRegister.AllowBlank(true);
  }

  // Post-Commit everthing is read-only
  if (mPostCommit) C.divBatchDetails.hide();
  C.txtBatchId.ReadOnly(mPostCommit);
  C.cboTransactionType.ReadOnly(mPostCommit);
  C.cboBankAccount.ReadOnly(mPostCommit);
  C.cboCashRegister.ReadOnly(mPostCommit);
  C.numBatchTotal.ReadOnly(mPostCommit);
  C.txtNotes.ReadOnly(mPostCommit);

  // Imported Batch?
  if (mRecord_BatchDetails &amp;&amp; mRecord_BatchDetails.Imported) {
    C.cboBankAccount.ReadOnly(true);
  }
}

// ===============
// FORM: New Batch
// ===============
function BatchNew() {
  // Create Modal
  mForm_BatchNew = widget.UI.Modal({
    title: "New Bank Batch",
    width: "90%",
    height: "90%",
    maxWidth: 640,
    maxHeight: 480,
    minWidth: 400,
    minHeight: 400,

    onAction: BatchNew_Action,
  });

  // Actions
  mForm_BatchNew.Actions().Define([{ groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
                                   { groupId: "[buttons]", actionId: "Ok", caption: "Add Bank Batch" }]);

  // Reset Fields
  C.txtNewBatchId.Text("");

  // Show
  mForm_BatchNew.Show({contentSourceElement: "frmBatchNew"});

  // Focus
  C.cboNewTransactionType.Focus();
}

// Handle Actions
function BatchNew_Action(actionId) {
  switch(actionId) {
    case "Cancel":
      mForm_BatchNew.Close();
      break;

   case "Ok":
      BatchNew_Action_Ok();
      break;

    default:
      window.alert(actionId);
  }
}

function BatchNew_Action_Ok() {
  // Validate
  var Ok = widget.UI.ValidateContainer(mForm_BatchNew.ContentElement());

  // Add New Batch
  if (Ok) {
    // Block UI
    widget.UI.Block("Adding New Bank Batch, please wait...");

    // Create Parameters
    var params = {
                   transactionTypeId: C.cboNewTransactionType.Text(),
                   batchId: C.txtNewBatchId.Text(),
                   bankAccountId: C.cboNewBankAccount.Text()
                 };

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

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

        // Close
        mForm_BatchNew.Close();

        // Edit New Batch
        C.cboBatch.Text(data.BatchId);
        mRecord_BatchInfo = { BatchId: data.BatchId, BatchPk: data.BatchPk };
        tabWizard_Move(1);
      },

      function(error) {
        // Unblock UI
        widget.UI.Unblock();

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

// =====================
// cboNewTransactionType
// =====================
function cboNewTransactionType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Get Transaction Type
  var transactionType = mTransactionTypes.GetItem(C.cboNewTransactionType.Text());

  // Update Controls
  if (transactionType) {
    C.txtNewBatchId.AllowBlank(transactionType.BatchIdAllowBlank);
  }
  else {
    C.txtNewBatchId.AllowBlank(false);
  }
}

// =======================
// gridCommitStatuses
// =======================
function gridCommitStatuses_Refresh() {
  // Add Columns
  C.gridCommitStatuses.ClearColumns();
  C.gridCommitStatuses.AddColumnIcon("Icon", { caption: "" });
  C.gridCommitStatuses.AddColumnString("CommitStatus", { caption: "Commit Status" });
  C.gridCommitStatuses.AddColumnCode("AccountId", { caption: "Account", width: widget.UI.FIELD_WIDTH_CODE_10 });
  C.gridCommitStatuses.AddColumnDate("Date", { caption: "Date" });
  C.gridCommitStatuses.AddColumnCurrency("Value", { caption: "Value" });
  C.gridCommitStatuses.AddColumnString("PaymentMethodId", { caption: "Pay Method", width: "6em" });
  C.gridCommitStatuses.AddColumnString("Reference", { caption: "Reference", width: "6em" });
  C.gridCommitStatuses.AddColumnString("Notes", { caption: "Notes", width: "30%" });

  // Refresh
  C.gridCommitStatuses.VirtualDataRefresh(mRecord_CommitStatuses);

  // Activate First Row
  C.gridCommitStatuses.ActivateFirstDataRow();
}

function gridCommitStatuses_InitialiseRow(e) {
  var item = mRecord_CommitStatuses[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Commit Status
  if (item.Committed) {
    e.row.cells.CommitStatus.value = "Committed";
    e.row.cells.CommitStatus.colour = "limegreen";
    e.row.cells.Icon.value = "Ok";
  }
  else if(item.CommitError) {
    e.row.cells.CommitStatus.value = item.CommitError;
    e.row.cells.CommitStatus.colour = "red";
    e.row.cells.Icon.value = "Error";
  }

  // Cell Styles
  e.row.cells.CommitStatus.small = true;
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>mbBHPCivEEa-dRACK90+vQ</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1280</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1600</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 />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="BatchUnlockPolicy" 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>Administrator Only</Value>
            <Visible>true</Visible>
            <List>Administrator Only,Administrator plus Batch User,Any User</List>
            <LimitToList>true</LimitToList>
            <MaxLength>30</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="TransactionLoadCountPrompt" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Prompt before showing the Transactions page if the number of Transactions in this Bank Batch excedes this number.</TooltipText>
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>200</Value>
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="GridsShowElement" type="Boolean">
            <BlankTip />
            <Caption>Show Element column in grids by default?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="GridsShowBanking" type="Boolean">
            <BlankTip />
            <Caption>Show Banking columns in Transaction grid by default?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="BatchId" type="Text">
            <BlankTip />
            <Caption>BatchId</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>
            <MaxLength>20</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>