<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2026-04-13T03:39:10.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2026-01-20T03:03:47.1800000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2026-04-13T03:38:44.1330000</UpdatedUtcDate>
    <ScriptId>HWTE</ScriptId>
    <Description>Transaction Entry</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_TransactionEntry
Option Explicit On
Option Strict On

' #################################################################
' Transaction Entry wizard
'
' (C) Copyright Intersoft Systems Limited 2026
'
' Version: 1.00 (13/04/2026)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  13/04/2026  ISS      J029911   Created
' #################################################################

' Constants
Private Const FORM_KEY As String = "TransactionEntry"

' Common Parameters
Private WithEvents mBatch As finBatch
Private mBatchId As String
Private mBatchUnlockPolicy As String
Private mGridsShowElement As Boolean
Private mTransactionLoadCountPrompt As Integer

' Objects
Private mCombinedParameters As ISKeyValueList
Private mDesktopMode As Boolean
Private mLastCaption As String
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList

' Other
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus

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")
    mDesktopMode = .GetBoolean("DesktopMode")
    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 "BackgroundProcess.Execute"
      ' Called by Web Services to execute a Background Process that was initially queued in the Widget's UI (via the Finish event)
      Main = BackgroundProcess_Execute(returnValue)
      
    Case "CancelBackgroundProcess"
      ' Cancel a Process
      Main = CancelBackgroundProcess(returnValue)      
      
    Case "DeleteBatch"
      ' Delete Batch
      Main = DeleteBatch(returnValue)

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

    Case "GetAccountDetails"
      ' Get Account Details
      Main = GetAccountDetails(returnValue)
      
    Case "GetBackgroundProcessStatus"
      ' Get Background Process Status
      Main = GetBackgroundProcessStatus(returnValue)

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

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

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

    Case "RefreshBatchList"
      ' Refresh the Batch List
      Main = RefreshBatchList(returnValue)
      
    Case "RefreshDisbursementExternalPartyList"
      ' Refresh the Disbursement External Party List
      ' This is dependent on the Disbursement Type and Disbursement Payee
      Main = RefreshDisbursementExternalPartyList(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;
'''  Commit Batch.
''' &lt;/summary&gt;
Private Function BackgroundProcess_Execute(ByRef returnValue As String) As Boolean
  
  Dim BatchTransaction As finBatchTransaction
  Dim BatchPk As Integer
  Dim IsLocked As Boolean
  Dim LockDetails As ISLockRO  
  Dim Success As Boolean
  Dim WizardFinishDetails As WizardFinishDetails
  
  ' Assume Success
  Success = True
  
  ' Get Background Process
  ' NOTE: This is required to add events and to check to see if the User has attempted to cancel this process (if supported)
  mProcessStatus = DirectCast(ScriptInfo.ContextData.GetObject("ProcessStatus"), finHtmlWidgetBackgroundProcessStatus)
  
  If Success Then
    mProcessStatus.AddEvent_Information("Starting Process")    
  End If
  
  ' Retrieve Parameters
  If Success Then
    With mParameters
      BatchPk = .GetInteger("BatchPk")
    End With
  End If
  
  ' 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 Batch is locked by another User.")
        End If
      End If
    Else
      Success = False
    End If
  End If  
  
  ' Load Batch
  If Success Then
    mBatch = finBL.CreateBatch(True)
    Success = mBatch.LoadPk(BatchPk)
  End If
  
  ' Commit Batch
  If Success Then
    mProcessStatus.AddEvent_Information("Committing Batch")
    Success = mBatch.ExecuteCommit(True)
  End If
  
  ' Finish Details
  If Success Then
    WizardFinishDetails = New WizardFinishDetails(finBL, mBatch)
    
    ' Record Commit Status
    For Each BatchTransaction In mBatch.Transactions
      WizardFinishDetails.AddCommitStatus(BatchTransaction)
    Next
    
    ' Remove Committed (and blank) Transactions
    mBatch.RemoveCommitted(True)
    
    ' Close Batch (also releases Lock)
    If mBatch.HasUncommittedTransactions() Then 
      mProcessStatus.AddEvent_Warning("Batch finished with uncommitted transactions.")
    Else
      If Not mBatch.StatusClose() Then
        mProcessStatus.AddEvent_Warning("Batch was successfully committed but failed to close.")
      End If
    End If
  End If
  
  ' Finalise
  If Success Then
    If finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(WizardFinishDetails, returnValue) Then
      Success = mProcessStatus.OtherDetails.FromSimpleJsonString(returnValue)
    Else
      Success = False
    End If
  End If
  
  Return Success  
  
End Function

''' &lt;summary&gt;
'''  Request that a Background Process is Cancelled.
''' &lt;/summary&gt;
Private Function CancelBackgroundProcess(ByRef returnValue As String) As Boolean

  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ProcessId = mCombinedParameters.GetString("ProcessId")

  ' Request Cancel
  Success = finBL.HtmlWidgetUtilities.CancelBackgroundProcess(processId)

  Return Success

End Function


''' &lt;summary&gt;
'''  Run Background Process (Queued and run via Web Services).
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        startupParametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim Data As Object                        
  Dim ProcessId As String                        
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Validate
  If Success Then
    ' Not required
  End If  
  
  ' Start Background Process
  If Success Then
    ' NOTE: If mDesktopMode is True then the desktop User Interface will handle this rather than Web Services Background Processes
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript(ScriptInfo.ScriptId, parametersJson, startupParametersJson, ProcessId, mDesktopMode)    
  End If  
  
  ' Process Id
  If Success Then
    Data = New With {
      .ProcessId = ProcessId
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, 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 Batch As finBatch
  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 Batch is locked by another User.")
        End If
      End If
    Else
      Success = False
    End If
  End If

  ' Delete Batch
  If Success Then
    Batch = finBL.CreateBatch(True)
    If Batch.LoadPk(batchPk) Then
      ' Delete
      Success = Batch.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 Batch As finBatch
  Dim BatchId As String
  Dim obj As Object
  Dim Success As Boolean
  Dim TransactionTypeId As String

  ' Assume Success
  Success = True

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

  ' Validate
  If Success Then
  End If

  ' Create Batch
  If Success Then
    Batch = finBL.CreateBatch(False)
    With Batch
      .BatchId = BatchId
      .TransactionTypeId = TransactionTypeId

      ' Source
      .SourceSet(isefinTransactionSource.TransactionEntry)

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

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

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

  Return Success

End Function

Private Function RefreshBatchList(ByRef returnValue As String) As Boolean
  
  Dim BatchList As List(Of BatchListItem)
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Get Batch List
  If Success Then
    Success = GetBatchList(BatchList)
  End If
  
  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(BatchList, returnValue)
  End If
  
  Return Success
  
End Function

Private Function RefreshDisbursementExternalPartyList(ByRef returnValue As String) As Boolean
  
  Dim ExternalPartyDetails As DisbursementExternalPartyListDetails
  Dim DisbursementType As String
  Dim PayeeType As String
  Dim Success As Boolean
  Dim TransactionType As String
  
  ' Assume Success
  Success = True
  
  ' Unpack
  With mCombinedParameters
    DisbursementType = .GetString("DisbursementType")
    PayeeType = .GetString("PayeeType")
    TransactionType = .GetString("TransactionType")
  End With
  
  ' Get Details
  ExternalPartyDetails = New DisbursementExternalPartyListDetails(PayeeType, DisbursementType, TransactionType)
  
  ' Serialise
  Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ExternalPartyDetails, returnValue)
  
  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 Batch As finBatch
  Dim BatchTransaction As finBatchTransaction
  Dim BatchDetails As BatchDetails
  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 BatchTransaction
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True
  
  ' Initialise
  ListOrder = New List(Of Object)  

  ' Create a lockable Batch object
  ' NOTE: Working with Locks and Batches cannot be done within a Database Transaction
  Batch = finBL.CreateBatch(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 Batch is locked by another User.")
        End If
      Else
        Success = False
        finBL.Error.ErrorBegin("This Batch is not locked and cannot be updated.")
      End If
    Else
      Success = False
    End If
  End If

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

  ' Update
  If Success Then
    ' General
    With Batch
      .AutoPostWithholdingTax = BatchDetails.AutoPostWithholdingTax
      .BatchId = BatchDetails.BatchId
      .BatchTotal = BatchDetails.BatchTotal
      .Notes = BatchDetails.Notes
      .TransactionTypeId = BatchDetails.TransactionTypeId
      
      ' Auto Post Withholding Tax
      If .TransactionType.CreditInterest AndAlso finBL.Settings.AddOns.DepositAccount Then
        .AutoPostWithholdingTax = BatchDetails.AutoPostWithholdingTax
      End If      
      
      ' Disbursement
      If .TransactionType.AllowDisbursementEntry Then
        .DisbursementTypeText = BatchDetails.DisbursementTypeText
        .DisbursementPayeeTypeText = BatchDetails.DisbursementPayeeTypeText
        .DisbursementExternalPartyId = BatchDetails.DisbursementExternalPartyId
      End If
    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
          BatchTransaction = Batch.Transactions.CreateBatchTransaction()
          Batch.Transactions.Add(BatchTransaction)
        ElseIf Transaction.OrigIndex &gt;= Batch.Transactions.Count Then
          ' Invalid!
          Success = False
          finBL.Error.ErrorBeginFormat("No Transaction with an index of {0} was found in this Batch.", Transaction.OrigIndex)
          Exit For
        Else
          ' Existing
          BatchTransaction = Batch.Transactions(Transaction.OrigIndex)
        End If
        
        ' Record for Re-Order later
        ListOrder.Add(BatchTransaction)        

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

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

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

  ' Get Details
  If Success Then
    obj = New With {
      .BatchId = Batch.BatchId,
      .BatchPk = Batch.Pk,
      .CountTransactions = Batch.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(batchTransaction As finBatchTransaction,
                                             transaction As BatchTransaction) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Update Transaction
  With batchTransaction
    Success = .AccountIdSet(transaction.AccountId)
    
    If Success Then
      .ElementId = transaction.ElementId
      .Date = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(transaction.Date)
      .Reference = transaction.Reference
      .Value = transaction.Value
      .DisbursementValue = transaction.Disburse
      .Notes = transaction.Notes
  
      ' Tag original index
      .Tag = transaction.OrigIndex
    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 BatchList As List(Of BatchListItem)
  Dim Element As finElementRO
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)  
  Dim Success As Boolean
  Dim TransactionType As finTransactionTypeRO

  ' Assume Success
  Success = True

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

  ' Get Batches
  If Success Then
    Success = GetBatchList(BatchList)
  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
        .BatchList = BatchList
        .DisbursementPayeeTypeListCsv = finBL.Enums.isefinDisbursementPayeeType_GetList(False, False, True).ToCsvString()
        .DisbursementTypeListCsv = finBL.Enums.isefinDisbursementType_GetList(True, True, False, False).ToCsvString()
        
        ' Configuration
        .CountryCode = finBL.CountryCode
        .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
        .ReadOnly = finBL.Database.IsReadOnly
        .TransactionLoadCountPrompt = mTransactionLoadCountPrompt
        .TransactionTypesSqlWhere = finBL.TransactionTypes.GetDataViewFilter_AllowTransactionEntryBulk()
        
        ' License
        .AddonsDepositAccount = finBL.Settings.AddOns.DepositAccount
        .AddonsDisbursements = finBL.Settings.AddOns.Disbursements

        ' Global Collections
        For Each Element In finBL.Elements
          If Element.Active Then
            .Elements.Add(New ElementDetails(finBL, Element))
          End If
        Next

        For Each TransactionType In finBL.TransactionTypes
          If TransactionType.Active Then
            .TransactionTypes.Add(New TransactionTypeDetails(finBL, TransactionType))
          End If
        Next
      End With
      
      ' Get current and recent Background Processes for this User
      If finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_HtmlWidgetScript(ScriptInfo.ScriptId, True, ProcessStatuses) Then
        FormInitialisationInfo.CurrentProcesses = ProcessStatuses
      Else
        Success = False
      End If      

      ' 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 Batch As finBatch
  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 finBatchTransaction

  ' 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 Batch object
        Batch = finBL.CreateBatch(True)

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

        ' Return Batch Details (excluding any transactions)
        If Success Then
          Data = New BatchDetails(finBL, batch)
        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 Batch object
        Batch = finBL.CreateBatch(False)

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

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

          With DirectCast(Data, List(Of BatchTransaction))
            For Each Transaction In Batch.Transactions
              .Add(New BatchTransaction(finBL, Batch, 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 Background Process Status.
''' &lt;/summary&gt;
Private Function GetBackgroundProcessStatus(ByRef returnValue As String) As Boolean

  Dim LastEventId As String
  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Background Processes Status including Events
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessStatusIncludingEventsJson(processId, lastEventId, returnValue)

  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

Private Function GetBatchList(ByRef BatchList As List(Of BatchListItem)) As Boolean
  
  Dim DataRow As DataRow
  Dim dt As DataTable
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  BatchList = New List(Of BatchListItem)
  
  ' Get Batches
  If Success Then
    Success = finBL.BatchFunctions.GetBatchListAsDataTable(dt)
  End If
  
  If Success Then
    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
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get current and recent Background Processes that for this User (these  are also returned in GetInitialisationInfo).
''' &lt;/summary&gt;
Private Function GetCurrentProcesses(ByRef returnValue As String) As Boolean

  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get current and recent Background Processes that for this User
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_HtmlWidgetScript(ScriptInfo.ScriptId, True, ProcessStatuses)

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ProcessStatuses, returnValue)
  End If

  Return Success

End Function

Private Sub mBatch_CommitProgress(sender As Object, e As finProgressEventArgs) Handles mBatch.CommitProgress
  
  Dim AddEvent As Boolean
  
  ' Filter Events - mostly to prevent multiple 'Committing Batch' events from being written
  If Len(mLastCaption) = 0 Then
    AddEvent = True
  ElseIf StrComp(e.Caption, mLastCaption) = 0 Then
    AddEvent = False
  Else 
    AddEvent = True
  End If  
  
  ' Log Event
  If AddEvent Then
    mProcessStatus.AddEvent_Information(e.Caption)
    
    ' Update last caption
    mLastCaption = e.Caption
  End If
  
End Sub

''' &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 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
  
  ' Current Processes
  Public CurrentProcesses As New List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)  

  ' General
  Public BatchId As String
  Public DefaultTransactionDate As Date

  ' Lists
  Public BatchList As New List(Of BatchListItem)
  Public DisbursementPayeeTypeListCsv As String
  Public DisbursementTypeListCsv As String

  ' Configuration
  Public CountryCode As String
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean
  Public TransactionLoadCountPrompt As Integer
  Public TransactionTypesSqlWhere As String

  ' Global Collections
  Public Elements As New List(Of ElementDetails)
  Public TransactionTypes As New List(Of TransactionTypeDetails)
  
  ' Licence
  Public AddonsDepositAccount As Boolean
  Public AddonsDisbursements As Boolean

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;
'''  Class to store details of a single Batch Transaction
''' &lt;/summary&gt;
Public Class BatchTransaction
  
  ' Properties
  Public AccountId As String
  Public AccountName As String
  Public [Date] As Date?
  Public Disburse As Decimal
  Public ElementId As String
  Public Notes As String
  Public Reference As String
  Public Value As Decimal

  ' Other
  Public OrigIndex As Integer

  Public Sub New()
    ' For desrialisation
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 batch As finBatch,
                 transaction As finBatchTransaction)

    With transaction
      Me.AccountId = .AccountId
      Me.AccountName = .AccountName
      Me.Date = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.Date)
      Me.Disburse = .DisbursementValue
      Me.ElementId = .ElementId
      Me.Notes = .Notes
      Me.Reference = .Reference
      Me.Value = .Value
      
      ' Other
      Me.OrigIndex = batch.Transactions.IndexOf(transaction)
    End With

  End Sub  

  ' Prevent Serialisation for non-applicable properties
  Public Function ShouldSerializeNotes() As Boolean
    Return Len(Me.Notes) &lt;&gt; 0
  End Function
  
End Class



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

  Public AutoPostWithholdingTax As Boolean
  Public BatchId As String
  Public BatchPk As Integer
  Public BatchTotal As Decimal
  Public CreatedDate As String
  Public CreatedUserId As String
  Public DisbursementExternalPartyId As String  
  Public DisbursementPayeeTypeText As String  
  Public DisbursementTypeText As String
  Public Notes As String
  Public Pk As Integer
  Public TransactionTypeId As String

  ' Information
  Public TransactionCount As Integer

  Public Sub New()
    ' For desrialisation
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 batch As finBatch)

    With batch
      Me.AutoPostWithholdingTax = batch.AutoPostWithholdingTax
      Me.BatchId = .BatchId
      Me.BatchPk = .Pk
      Me.BatchTotal = .BatchTotal
      Me.DisbursementExternalPartyId = .DisbursementExternalPartyId      
      Me.DisbursementPayeeTypeText = .DisbursementPayeeTypeText
      Me.DisbursementTypeText = .DisbursementTypeText
      Me.Notes = .Notes
      Me.TransactionTypeId = .TransactionTypeId

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

  End Sub

End Class



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

  ' Defaults
  Public DefaultNotes As String  
  Public DefaultReference As String
  Public DefaultValue As Decimal  
  
  ' 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
      
      ' Defaults
      Me.DefaultNotes = .TransactionNotes
      Me.DefaultReference = .TransactionReferenceResolved
      Me.DefaultValue = .TransactionValue
      
    End With

  End Sub

End Class



Public Class DisbursementTypeDetails
  
  Public AllowPayeeType As Boolean
  Public AllowExternalParty As Boolean
  Public DisbursementType As String  
  Public IsCommission As Boolean
  
  Public Sub New(disbursementTypeText As String)
    
    Dim DisbursementType As isefinDisbursementType
    
    DisbursementType = finBLShared.Enums.isefinDisbursementType_FromString(disbursementTypeText)
    Me.DisbursementType = disbursementTypeText
    
    ' Default
    Me.AllowPayeeType = True
    Me.AllowExternalParty = True
    Me.IsCommission = False
    
    ' Special Cases
    Select Case DisbursementType
      Case isefinDisbursementType.None
        Me.AllowExternalParty = False
        Me.AllowPayeeType = False
        
      Case isefinDisbursementType.Commission, isefinDisbursementType.CommissionRecovery
        Me.IsCommission = True
        
    End Select
    
  End Sub
  
End Class



Public Class DisbursementExternalPartyListDetails
  
  Public ExternalPartyCaption As String
  Public ExternalPartySqlWhere As String
  
  Public Sub New(disbursementPayeeTypeText As String,
                 disbursementType As String,
                 transactionType As String)
    
    Dim CategoryRange As String
    Dim ExternalPartyType As isefinExternalPartyType
    Dim PayeeType As isefinDisbursementPayeeType

    PayeeType = finBLShared.Enums.isefinDisbursementPayeeType_FromString(disbursementPayeeTypeText)
    
    Select Case PayeeType
      Case isefinDisbursementPayeeType.Broker
        ExternalPartyType = isefinExternalPartyType.Broker
        Me.ExternalPartyCaption = "Broker:"

      Case isefinDisbursementPayeeType.BulkFunder
        ExternalPartyType = isefinExternalPartyType.BulkFunder
        Me.ExternalPartyCaption = "Bulk Funder:"

      Case isefinDisbursementPayeeType.Insurer
        ExternalPartyType = isefinExternalPartyType.Insurer
        Me.ExternalPartyCaption = "Insurer:"

      Case isefinDisbursementPayeeType.Other
        ExternalPartyType = isefinExternalPartyType.Other
        Me.ExternalPartyCaption = "Other:"

      Case Else
        ExternalPartyType = isefinExternalPartyType.Dealer
        Me.ExternalPartyCaption = "Dealer:"    
      
    End Select
    
    ' Get valid Categories from Transaction Type/Element
    If finBLShared.TransactionTypes.Exists(transactionType) Then
      CategoryRange = finBLShared.TransactionTypes.Item(transactionType).Element.DisbursementPayeeExternalPartyCategories
    Else
      CategoryRange = ""
    End If
    
    ' Get filter
    Select Case finBLShared.Enums.isefinDisbursementType_FromString(disbursementType)
      Case isefinDisbursementType.Commission, isefinDisbursementType.CommissionRecovery
        ' Commissions
        Me.ExternalPartySqlWhere = finBLShared.ExternalParties.GetDataViewFilter_SupportsCommissions(ExternalPartyType, CategoryRange)
        
      Case Else
        ' Disbursements
        Me.ExternalPartySqlWhere = finBLShared.ExternalParties.GetDataViewFilter_SupportsDisbursements(ExternalPartyType, CategoryRange)
        
    End Select
    
  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 CreditInterest As Boolean
  Public CreditInterestAllowAutoPostWithholdingTax As Boolean
  Public CreditInterestDefaultAutoPostWithholdingTax As Boolean
  Public ElementId As String
  Public ElementsListTag As String

  ' Disbursement
  Public AllowDisbursementEntry As Boolean
  
  Public Sub New(finBL As ISfinSupport,
                 transactionType As finTransactionTypeRO)

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

      ' 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 BatchTransaction)

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 BatchDetails As BatchDetails
  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()
  End Sub
  
  Public Sub New(finBL As ISfinSupport,
                 batch As finBatch)

    mFinBl = finBL

    BatchDetails = New BatchDetails(finBL, batch)
    
    With batch
      Me.BatchId = .BatchId
      Me.BatchPk = .Pk

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

  End Sub

  Public Sub AddCommitStatus(transaction As finBatchTransaction)

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

  End Sub

End Class



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

  ' Properties
  Public Committed As Boolean
  Public CommitError As String

  ' Other Properties (in case Transaction is not loaded client-side)
  Public AccountId As String
  Public [Date] As Date?
  Public Disburse As Decimal
  Public ElementId As String
  Public Notes As String
  Public Reference As String
  Public Value As Decimal

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

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

      ' Other
      Me.AccountId = .AccountId
      Me.Date = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.Date)
      Me.Disburse = .DisbursementValue
      Me.ElementId = .ElementId
      Me.Notes = .Notes
      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 "TransactionEntry".</Notes>
    <PermissionKeyExecute />
    <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="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent Transaction Entries you have run."&gt;Recent Transaction Entries&lt;/li&gt;      
        &lt;li tabId="General" tooltipText="Select the Transaction Batch to edit."&gt;General&lt;/li&gt;
        &lt;li tabId="Details" tooltipText="Review Transaction 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="Progress" tooltipText="Processing progress."&gt;Progress&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;!-- Current Processes --&gt;
    &lt;div id="pageCurrentProcesses"&gt;
      &lt;div id="gridCurrentProcesses"&gt;&lt;/div&gt;
    &lt;/div&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 Transaction Batch to edit or create a new Transaction 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 Transaction 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 Transaction 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 Transaction Batch details&lt;/label&gt;&lt;/th&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="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="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 colspan="2"&gt;&lt;label id="lblPostWithholdingTax"&gt;Automatically calculate and post Withholding Tax on Interest transactions for Deposit Accounts?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAutoPostWithholdingTax" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDisbursementDetails"&gt;Specify Disbursement Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboDisbursementType"&gt;Type:&lt;/label&gt;
          &lt;td&gt;&lt;input id="cboDisbursementType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboDisbursementPayeeType"&gt;Payee Type:&lt;/label&gt;
          &lt;td&gt;&lt;input id="cboDisbursementPayeeType" /&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboDisbursementExternalParty"&gt;External&amp;nbsp;Party:&lt;/label&gt;
          &lt;td&gt;&lt;input id="cboDisbursementExternalParty" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblNotes" for="txtNotes"&gt;Notes&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="txtNotes" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;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 Transaction 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 Transaction 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&gt;
    &lt;/div&gt;

    &lt;!-- Progress --&gt;
    &lt;div id="pageProgress" style="display:flex"&gt;
      &lt;div id="divProgress" class="progress-events"&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="cmdHistory" class="is-button" style="float:left"&gt;Recent&lt;/button&gt;  
    &lt;button id="cmdBatchSave" class="is-button positive" style="float:left"&gt;Save&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 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;/table&gt;
&lt;/div&gt;
&lt;!-- frmBatchNew END --&gt;

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

// Global Collections
var mElements;
var mExternalPartyListDetails;
var mTransactionTypes;

// Controls
var C = {
  // Current Processes
  gridCurrentProcesses: null,

  // General
  lblBatch: null,
  cboBatch: null,

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

  // Details
  lblBatchDetails: null,
  cboTransactionType: null,
  txtBatchId: null,  
  numBatchTotal: null,
  
  lblPostWithholdingTax: null,
  chkAutoPostWithholdingTax: null,
  
  lblDisbursementDetails: null,
  cboDisbursementType: null,
  cboDisbursementPayeeType: null,
  cboDisbursementExternalParty: null,

  lblNotes: null,
  txtNotes: null,

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

  // Items
  gridTransactions: null,
  divTransactionsSummary: null,

  // Commit Details Simple
  gridCommitStatuses: null,

  // frmBatchNew
  lblNewBatchDetails: null,
  cboNewTransactionType: null,
  txtNewBatchId: null,
  
  //   Progress
  divProgress: null,  
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory
var cmdBatchSave;
var cmdBatchAbandon;
var cmdBatchDelete;

// Other
var mComplete = false;
var mFromRecent = false;
var mLastEventId = "";
var mLastProcessStatus = "";
var mLockedBatchId = "";
var mMonitoringExisting = false;
var mPostCommit = false;
var mProcessId;
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.cboTransactionType = widget.UI.DBCombo("cboTransactionType", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboTransactionType_Change,
  });  
  C.txtBatchId = widget.UI.TextBox("txtBatchId", {
    allowBlank: false,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.numBatchTotal = widget.UI.NumberBox("numBatchTotal", {
    blankIfZero: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  
  C.lblPostWithholdingTax = widget.UI.Label("lblPostWithholdingTax", {});
  C.chkAutoPostWithholdingTax = widget.UI.CheckBox("chkAutoPostWithholdingTax", {
    caption: "Automatically post Withholding Tax?"
  });
  
  C.lblDisbursementDetails = widget.UI.Label("lblDisbursementDetails", {});
  C.cboDisbursementType = widget.UI.ComboBox("cboDisbursementType", {
    limitToList: true,
    allowBlank: false,
    
    onChange: cboDisbursementType_Change
  });
  C.cboDisbursementPayeeType = widget.UI.ComboBox("cboDisbursementPayeeType", {
    limitToList: true,
    allowBlank: false,
    
    onChange: cboDisbursementPayeeType_Change
  });
  C.cboDisbursementExternalParty = widget.UI.DBCombo("cboDisbursementExternalParty", {
    limitToList: true,
    allowBlank: false,
  });
  
  C.lblNotes = widget.UI.Label("lblNotes", {});
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 8,
    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();
  });

  // 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,
  });
  
  // Progress
  C.divProgress = $("#divProgress");  

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

    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });  
  
  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.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"); });

  cmdHistory = $("#cmdHistory");
  cmdBatchSave = $("#cmdBatchSave");
  cmdBatchAbandon = $("#cmdBatchAbandon");
  cmdBatchDelete = $("#cmdBatchDelete");
  cmdHistory.click(function() { Form_ExecuteAction("Recent"); });  
  cmdBatchSave.click(function() { Form_ExecuteAction("BatchSave"); });
  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_CurrentProcesses = 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);
      mRecord_CurrentProcesses = mRecord.CurrentProcesses;

      // Global Collections
      mElements = mRecord.Elements;
      mTransactionTypes = mRecord.TransactionTypes;

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

      // Load Fields
      Fields_Load();
      
      // Notify if there are Current Processes
      var countCurrent = 0;
      for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
        switch (mRecord_CurrentProcesses[i].Status) {
          case "Pending":
          case "InProgress":
          case "InProgressCancelRequested":
            countCurrent += 1;
        }
      }
      if (countCurrent != 0) {
        tabWizard_Move(-1);
        widget.UI.MsgBoxInfo("There are existing Transaction Entries that you have run that are not yet complete.\n\nReview and optionally monitor these or use the 'Next &gt;' button to create a new Transaction Entry.", { heading: "Transaction Entry Still Running", icon: "MonitorCategory"} );
      }      
    },

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

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

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

  // Create Parameters
  var params = CreateFinishParameters();

  // 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 Batch was successfully saved.&lt;/p&gt;";
      message += "&lt;p&gt;Do you wish to continue editing this 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: "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(null, "Cancelling edit, please wait...");
        });
    },

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

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

// ===========================
// Refresh External Party List
// ===========================
function RefreshDisbursementExternalPartyList() {
  
  // Validate
  if (C.cboDisbursementPayeeType.Text().length == 0) {
    // Clear
    mExternalPartyListDetails = null;
    C.cboDisbursementExternalParty.Caption("External Party:");
  }
  else {
    // Block
    widget.UI.Block();  
  
    // Parameters
    var params = {
      DisbursementType: C.cboDisbursementType.Text(),
      PayeeType: C.cboDisbursementPayeeType.Text(),
      TransactionType: C.cboTransactionType.Text()
    }
    
    // Get list
    widget.GetString("RefreshDisbursementExternalPartyList", params, RefreshDisbursementExternalPartyList_Done,       
      function (error) {
        widget.UI.MsgBoxAlert(error);
      }
    );
  }
}

function RefreshDisbursementExternalPartyList_Done(data) {
  // Unblock
  widget.UI.Unblock();
  
  if (data) {
    // parse
    mExternalPartyListDetails = JSON.parse(data);
    
    if (mExternalPartyListDetails) {
      C.cboDisbursementExternalParty.Caption(mExternalPartyListDetails.ExternalPartyCaption);
      C.cboDisbursementExternalParty.RefreshFromStandardRange("ExternalParties", mExternalPartyListDetails.ExternalPartySqlWhere, false);
    }
  }
}

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // Current Processes
    // NOTE: Bind here since this is the first page
    gridCurrentProcesses_Refresh();  
  
    // 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();
}

function Fields_Load_BatchDetails() {
  C.txtBatchId.Text(mRecord_BatchDetails.BatchId);
  C.cboTransactionType.Text(mRecord_BatchDetails.TransactionTypeId);
  C.numBatchTotal.Value(mRecord_BatchDetails.BatchTotal);
  C.txtNotes.Text(mRecord_BatchDetails.Notes);
  
  // Update Fields
  cboTransactionType_Change();  
  
  if (mTransactionType) {
    // Auto Post Withholding Tax
    if (mTransactionType.CreditInterest &amp;&amp; mRecord.AddonsDepositAccount) {
      C.chkAutoPostWithholdingTax.Value(mRecord_BatchDetails.AutoPostWithholdingTax);
    }
    
    // Disbursement
    if (mTransactionType.AllowDisbursementEntry &amp;&amp; mRecord.AddonsDisbursements) {
      C.cboDisbursementType.Text(mRecord_BatchDetails.DisbursementTypeText);
      C.cboDisbursementPayeeType.Text(mRecord_BatchDetails.DisbursementPayeeTypeText);
      C.cboDisbursementExternalParty.Text(mRecord_BatchDetails.DisbursementExternalPartyId);
      
      // Update Fields
      cboDisbursementType_Change();
      cboDisbursementPayeeType_Change();
    }
  }
}

// ===========
// Fields Save
// ===========
function Fields_Save_BatchDetails() {
  mRecord_BatchDetails.BatchId = C.txtBatchId.Text();
  mRecord_BatchDetails.TransactionTypeId = C.cboTransactionType.Text();
  mRecord_BatchDetails.BatchTotal = C.numBatchTotal.Value();
  mRecord_BatchDetails.Notes = C.txtNotes.Text();
  
  if (mTransactionType) {
    // Auto Post Withholding Tax
    if (mTransactionType.CreditInterest &amp;&amp; mRecord.AddonsDepositAccount) { 
      mRecord_BatchDetails.AutoPostWithholdingTax = C.chkAutoPostWithholdingTax.Value();
    }
      
    // Disbursement
    if (mTransactionType.AllowDisbursementEntry &amp;&amp; mRecord.AddonsDisbursements) {
      mRecord_BatchDetails.DisbursementTypeText = C.cboDisbursementType.Text();
      mRecord_BatchDetails.DisbursementPayeeTypeText = C.cboDisbursementPayeeType.Text();
      mRecord_BatchDetails.DisbursementExternalPartyId = C.cboDisbursementExternalParty.Text();
    }  
  }
}

// ========
// 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 Batch information retrieved");
        }
        else {
          // Information
          var s = "";
          if (mRecord_BatchInfo.IsLocked) {
            s += "&lt;p style='color:red'&gt;This 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;";
          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();
  }
}

// ===================
// cboDisbursementType
// ===================
function cboDisbursementType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  switch (C.cboDisbursementType.Text().toUpperCase()) {
    case "NONE":
      C.cboDisbursementPayeeType.ReadOnly(true);
      C.cboDisbursementPayeeType.AllowBlank(true);
      C.cboDisbursementExternalParty.ReadOnly(true);
      C.cboDisbursementExternalParty.AllowBlank(true);
      break;
      
    default:
      C.cboDisbursementPayeeType.ReadOnly(false);
      C.cboDisbursementPayeeType.AllowBlank(false);
      C.cboDisbursementExternalParty.ReadOnly(false);    
      C.cboDisbursementExternalParty.AllowBlank(false);
      break;
  }
}

// ========================
// cboDisbursementPayeeType
// ========================
function cboDisbursementPayeeType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Refresh the Disbursement External Party List
  RefreshDisbursementExternalPartyList();
}

// ==================
// 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 &amp;&amp; mRecord.AddonsDepositAccount) {
    C.chkAutoPostWithholdingTax.Value(mTransactionType.CreditInterestDefaultAutoPostWithholdingTax);
  }

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

    // frmBatchNew
    C.cboNewTransactionType.RefreshFromStandardRange("TransactionTypes", mRecord.TransactionTypesSqlWhere);
    
    // Disbursement
    C.cboDisbursementType.ListFromCsvString(mRecord.DisbursementTypeListCsv);
    C.cboDisbursementPayeeType.ListFromCsvString(mRecord.DisbursementPayeeTypeListCsv);
  }

  // Controls
  if (mRecord) {
  }

  // 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(null, "Cancelling edit, please wait...");
        }
        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 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(null, "Cancelling edit, please wait...");
          });
      }
      break;

    case "BATCHDELETE":
      // Delete Batch
      widget.UI.MsgBoxConfirmDelete("Are you sure you want to PERMANENTLY delete this Batch?", { heading: "Delete Batch" }, Form_ExecuteAction_BatchDelete);
      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 Batch?", { heading: "Save Changes" },
            function () {
              Record_Save();
            }
          );
        }
        else {
          Record_Save();
        }
      }
      break;

    case "FINISH":
      // Finish
      if ((mRecord.ReadOnly || mPostCommit || mFromRecent) &amp;&amp; cmdFinish.text().toUpperCase() != "STOP") {
        tabWizard_Cancel();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;
      
    case "RECENT":
      // Recent
      Form_ExecuteAction_Recent();
      break;

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

function Form_ExecuteAction_Finish() {
  if (cmdFinish.text().toUpperCase() == "STOP") {
    // Stop Process?
    //widget.UI.MsgBoxConfirm("Are you sure you want to stop this process?\n\nNOTE: This may not take effect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
    widget.UI.MsgBoxAlert("Stopping this process is not supported.");
  }
  else {
    // 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 Batch";
  var message = "&lt;p&gt;Are you sure you want to save and commit this Batch?&lt;/p&gt;";
  message += "&lt;ul&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;Batch ID: &lt;b&gt;" + widget.UI.HtmlEncode(C.txtBatchId.Text()) + "&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 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("Starting Process, please wait...");
  
  // Running new process
  mMonitoringExisting = false;    
  
  // Clear Progress Page
  pageProgress_Refresh(true);  

  // Commit
  widget.GetString("Finish", { batchPk: batchPk },
    function (data) {
      // Parse
      data = JSON.parse(data);
      
      mPostCommit = true;      
      
      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();
      
      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Unblock UI
      widget.UI.Unblock();
      
      // Refresh Progress
      pageProgress_Refresh();
      
      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);          
    },

    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, msg) {
  // Block UI
  widget.UI.Block(msg);

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  // Continue
  widget.GetString("GetBackgroundProcessStatus", { processId: mProcessId, lastEventId: mLastEventId },
    function (data) {
      data = JSON.parse(data);

      // Update Status
      mRecord_BackgroundProcessStatus = data;

      // Refresh Progress
      pageProgress_Refresh();

      // Status
      var Status = mRecord_BackgroundProcessStatus.Status;

      // Handle Status
      switch(Status) {
        case "Cancelled":
          // Cancelled
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Batch was successfully cancelled.");
          break;

        case "Complete":
        case "CompleteWithErrors":
        case "CompleteWithWarnings":
          // Complete
          mComplete = true;
          mRecord_BackgroundProcessStatus = null;

          var OtherDetails = JSON.parse(data.OtherDetailsJson);
          mRecord_CommitDetails = OtherDetails;
          if (OtherDetails.CommitStatuses) {
            mRecord_CommitStatuses = JSON.parse(OtherDetails.CommitStatuses);
          }
          else {
            mRecord_CommitStatuses = null;
          }
          if (mRecord_CommitDetails.BatchDetails) {
            mRecord_BatchDetails = JSON.parse(mRecord_CommitDetails.BatchDetails);   
            
            // Transaction Type
            mTransactionType = mTransactionTypes.GetItem(mRecord_BatchDetails.TransactionTypeId);            
            
            // Update Controls
            if (mTransactionType) {
              C.cboTransactionType.Text(mTransactionType.TransactionTypeId);            
            }
            
            // Update Heading
            tabWizard_UpdateHeading();
          }
          else {
            mRecord_BatchDetails = null;
          }      
          
          // Warnings
          if(mRecord_CommitDetails.HasUncommittedTransactions || mRecord_CommitDetails.Warning) {
            var message = "";
            if (data.Warning) {
              message = data.Warning;
            }
            else if (mRecord_CommitDetails.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;Click 'Next' to check individual items for Errors.&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();          
          break;

        case "Failed":
          // Failed
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Batch failed to complete.");
          break;

        default:
          // Continue Polling
          window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 2500);

          // Prevent finPOWER Connect Cloud UI signing the User out
          widget.NotifyBusy();
      }
    },

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

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();
    }
  );
}

function Form_ExecuteAction_Recent() {
  // Validate
  if (mLockedBatchId) {
    // Notify
    var message = "&lt;p&gt;You have 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 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 Batch without first unlocking it.&lt;/p&gt;&lt;p&gt;Are you sure you want to continue?&lt;/p&gt;";
  
    widget.UI.MsgBoxConfirm(message, { messageIsHtml: true, heading: "Batch Locked", icon: "Warning", captionOk: "Continue"}, Form_ExecuteAction_Recent_Post);    
  }
  else {
    Form_ExecuteAction_Recent_Post();
  }
}

function Form_ExecuteAction_Recent_Post() {
  // Hide buttons
  cmdBatchSave.hide();
  cmdBatchAbandon.hide();
  cmdBatchDelete.hide();
  
  // Clear
  mLockedBatchId = "";
  mPostCommit = false;
  mRecord_CommitStatuses = null;
  
  // Move
  tabWizard_Refresh(0);
}

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

  // Tab
  tabWizard_Resize();
}

function GetBatchList() {
  // Block UI
  widget.UI.Block("Refreshing Batch List, please wait..."); 
  
  // Refresh
  widget.GetString("RefreshBatchList", {}, 
    // Success
    function (data) {
      // Unblock
      widget.UI.Unblock();
      
      // Parse
      if (data) {
        mRecord.BatchList = JSON.parse(data);
      }
      
      // Refresh
      C.cboBatch.RefreshFromCollection(mRecord.BatchList, "BatchId", "", "BatchId,TransactionTypeId,CreatedUserId,CreatedDate,Notes");
      cboBatch_Change();      
    },
     
    // Fail
    function (message) {
      widget.UI.MsgBoxAlert("fail: " + message);
      Fields_Load();
    }
  );     
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Batch is still running.\n\nThis will continue to run and you can re-open this form at any time to check on its status.\n\n\Close this form?", {}, tabWizard_Cancel_Done);    
  } 
  else if (mLockedBatchId &amp;&amp; !mPostCommit) {
    // Notify if Batch is Locked  
    var message = "&lt;p&gt;You are attempting to close this form and have 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 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 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 if (mLockedBatchId) {
    tabWizard_Cancel_Done("CloseNoSave");
  }
  else {
    tabWizard_Cancel_Done_Close();
  }
}

function tabWizard_Cancel_Done(actionId) {
  switch(actionId) {
    case "Ok":
      // Save and Close
      Record_Save(function () {
        Form_ExecuteAction_BatchAbandon(tabWizard_Cancel_Done_Close, "Unlocking Batch, please wait...");
      });
      break;

    case "CloseNoSave":
      // Close without Save
      Form_ExecuteAction_BatchAbandon(tabWizard_Cancel_Done_Close, "Unlocking Batch, please wait...");
      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;
        
      case "CommitDetailsSimple":
        pageCommitDetailsSimple_Refresh();
        break;
    }
  }

  // Always Refresh Current Processes, even when moving back
  if (newTab == 0) {
    if (!mRecord_CurrentProcesses) pageCurrentProcesses_Refresh();
  }  
  
  // Always refresh the General page
  if (newTab == 1) {
    pageGeneral_Refresh();
  }
  
  // Make Tab it
  tabWizard.SelectedTabIndex(newTab);

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "CurrentProcesses":
      // Reset from recent flag
      mFromRecent = false;
      mProcessId = null;
      break;
  
    default:
      break;
  }

  // Tweak fields

  // Update Heading
  tabWizard_UpdateHeading();

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

  // Resize Wizard
  tabWizard_Resize();

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

function tabWizard_UpdateHeading() {
  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;
      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;
  }  
}

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

    default:
      break;
  }
}

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

  // Finish Button
  cmdFinish.prop("disabled", tabIndex &lt; 3);

  // Batch has been locked?
  if ((mLockedBatchId || mPostCommit) &amp;&amp; tabIndex == 2) cmdBack.prop("disabled", true);

  // Page Exceptions
  if (mRecord_BackgroundProcessStatus) {
    cmdBack.prop("disabled", true);
    cmdHistory.prop("disabled", true);

    switch(mRecord_BackgroundProcessStatus.Status) {
      case "Pending":
      case "InProgress":
        cmdFinish.text("Stop");
        cmdFinish.prop("disabled", false);
        cmdFinish.addClass("negative");
        break;

      default:
        cmdFinish.text("Process");
        cmdFinish.prop("disabled", true);
        cmdFinish.removeClass("negative");
    }
  }
  else {
    cmdFinish.text("Process");
    cmdHistory.prop("disabled", false);
  }

  // Progress page exception
  if (tabWizard.SelectedTabId() == "Progress")  {
    cmdBack.prop("disabled", true);  
    cmdNext.prop("disabled", mRecord_CommitStatuses == null);   
  }

  // Recent Page exceptions
  if (mFromRecent) {
    cmdHistory.prop("disabled", false);
  }
  
  // Other Buttons
  if (mLockedBatchId &amp;&amp; !mPostCommit) {
    cmdBatchSave.show();
    cmdBatchAbandon.text("Cancel Edit");
    cmdBatchAbandon.show();
    cmdBatchDelete.show();
  }
  else {
    cmdBatchSave.hide();
    cmdBatchAbandon.hide();
    cmdBatchDelete.hide();    
  }  

  if (mComplete || mPostCommit) {
    // Complete, i.e., Finish now closes the wizard
    cmdFinish.text("Close");
    cmdFinish.prop("disabled", false);

    // Allow viewing recent list
    cmdHistory.prop("disabled", false);
  }
}

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 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;
        
      case "Items":
        if (mRecord_Transactions &amp;&amp; mRecord_Transactions.length &gt; 0) {
          Ok = true;
        }
        else {
          Ok = false;
          C.gridTransactions.ActivateFirstDataRow();
        }
        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 Batch?&lt;/p&gt;&lt;p&gt;&lt;b&gt;WARNING:&lt;/b&gt; Unlocking a Batch that is being edited by another User may cause them to lose any changes they have made.&lt;/p&gt;", { heading: "Unlock 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.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.AddColumnString("ElementId", { caption: "Element", width: "6em", allowEdit: true, list: mTransactionType.ElementsListTag, columns: "ElementId,Description,ElementTypeText", idColumn: "ElementId" });
  C.gridTransactions.AddColumnDate("Date", { caption: "Date", allowEdit: !mRecord_BatchDetails.Imported });  
  C.gridTransactions.AddColumnString("Reference", { caption: "Reference", width: "6em", allowEdit: true });
  C.gridTransactions.AddColumnCurrency("Value", { caption: "Value", allowEdit: !mRecord_BatchDetails.Imported});
  if (mRecord.AddonsDisbursements) C.gridTransactions.AddColumnCurrency("Disburse", { caption: "Disburse", allowEdit: (!mRecord_BatchDetails.Imported &amp;&amp; mTransactionType.AllowDisbursementEntry)});
  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({});
  }
  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;
  };

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

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

function gridTransactions_InitialiseRow(e) {
  var item = mRecord_Transactions[e.row.listIndex];
  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];

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

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

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

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

  // 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";
    }
  }
  
  // Disbursement Value
  if (mRecord.AddonsDisbursements &amp;&amp; item.Disburse &amp;&amp; item.Disburse != 0) {
    switch (C.cboDisbursementType.Text().toUpperCase()) {
      case "RECOVERY":
        e.row.cells.Disburse.value = item.Disburse * -1; 
        break;
        
      default:
        e.row.cells.Disburse.value = item.Disburse;
        break;
    }
  }

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

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

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

    case "ElementId":
      item.ElementId = e.newValue;
      
      // Populate Defaults
      var element = mElements.GetItem(item.ElementId);
      if (element) {
        item.Reference = element.DefaultReference;
        item.Value = element.DefaultValue;
        item.Notes = element.DefaultNotes;
      }
      break;

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

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

    case "Value":
      item.Value = e.newValue;
      break;
      
    case "Disburse":
      // Disbursement Value
      if (e.newValue &amp;&amp; e.newValue != 0) {
        switch (C.cboDisbursementType.Text().toUpperCase()) {
          case "RECOVERY":
            item.Disburse = e.newValue * -1; 
            break;
            
          default:
            item.Disburse = e.newValue;
            break;
        }
      }
      else {
        item.Disburse = e.newValue;
      }
      break;

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

  }

  // Refresh row to update styles
  e.refreshRow = true;
  
  // Refresh Summary
  divTransactionsSummary_Refresh();
}

function gridTransactions_AfterRowActivate(e) {
  // Refresh Buttons
  gridTransactions_RefreshButtons();
}

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

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

        // Refresh Buttons
        gridTransactions_RefreshButtons();                
      }
      break;

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

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

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

// ======================
// divTransactionsSummary
// ======================
function divTransactionsSummary_Refresh() {
  var html = "";
  var totalValue = 0;
  var totalDisburse = 0;

  // Total
  for (var i = 0; i &lt; mRecord_Transactions.length; i++) {
    totalValue += mRecord_Transactions[i].Value;
    totalDisburse += mRecord_Transactions[i].Disburse;
  }

  // Avoid rounding issues
  totalValue = widget.RoundCurrency(totalValue);
  totalDisburse = widget.RoundCurrency(totalDisburse);

  // Message Value
  html = "&lt;div style='display:flex;flex-direction:row;gap:8px;'&gt;&lt;div&gt;"
  if (C.numBatchTotal.Value() == 0 || totalValue == C.numBatchTotal.Value()) {
    html += "Value: &lt;b&gt;" + widget.FormatCurrency(totalValue, true) + "&lt;/b&gt;";
  }
  else {
    var diff;
    if (totalValue &gt; C.numBatchTotal.Value()) {
      diff = "&lt;b style='color:green'&gt;&lt;small&gt;+" + widget.FormatNumber(totalValue - 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() - totalValue, -1, true) + "&lt;/small&gt;&lt;/b&gt;";
    }
    html += "Value: &lt;b style='color:red'&gt;" + widget.FormatCurrency(totalValue, true) + "&lt;/b&gt; &lt;small&gt;expected&lt;/small&gt; &lt;b&gt;" + widget.FormatCurrency(C.numBatchTotal.Value(), true) + "&lt;/b&gt; (" + diff + ")";
  }
  html += "&lt;/div&gt;";
  
  // Message Disburse
  if (totalDisburse != 0 &amp;&amp; mRecord.AddonsDisbursements) {
    html += "&lt;div&gt;";
    html += "Disburse: &lt;b&gt;" + widget.FormatCurrency(totalDisburse, true) + "&lt;/b&gt;";
    html += "&lt;/div&gt;";
  }
  
  html += "&lt;/div&gt;";
  
  // Display Message
  C.divTransactionsSummary.html(html);
}

// ========================
// Update Account Details 
// ========================
function UpdateAccountDetails(transactionIndex) {
  var transaction = mRecord_Transactions[transactionIndex];

  // Clear informational values
  transaction.AccountName = null;

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

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

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

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

// ====================
// pageCurrentProcesses
// ====================
function pageCurrentProcesses_Refresh() {
  // Reset flags
  mComplete = false;

  // Block UI
  widget.UI.Block("Refreshing recent list, please wait...");

  // Fetch
  widget.GetString("GetCurrentProcesses", {},
    function (data) {
      // Parse
      mRecord_CurrentProcesses = JSON.parse(data);

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

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

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

// ============
// pageProgress
// ============
function pageProgress_Refresh(clear) {
  if (clear) {    
    mLastProcessStatus = "";
    mLastEventId = "";
    mRecord_BackgroundProcessStatus = null;
    mRecord_CurrentProcesses = null;
  }
  else if (mRecord_BackgroundProcessStatus) {
    // Retrieve Last Process Status
    mLastProcessStatus = mRecord_BackgroundProcessStatus.StatusText;
  }

  // Build Progress
  mLastEventId = widget.UI.BuildBackgroundProcessProgress(C.divProgress, clear, mRecord_BackgroundProcessStatus, mLastEventId);

  // Stop button valid?
  tabWizard_UpdateButtons()

  // Update Heading
  if (tabWizard.SelectedTabId() == "Progress") {
    if (mLastProcessStatus &amp;&amp; mLastProcessStatus.length != 0) {
      frmMain.RefreshHeading(mLastProcessStatus, "Processing progress.");
    }
    else {
      frmMain.RefreshHeading("Progress", "Processing progress.");
    }
  }
}

function pageCommitDetailsSimple_Refresh() {
  gridCommitStatuses_Refresh();
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  GetBatchList();
}

// ===========
// pageDetails
// ===========
function pageDetails_Refresh() {
  // Update Controls
  C.lblPostWithholdingTax.VisibleRow(false);
  C.chkAutoPostWithholdingTax.VisibleRow(false);
  
  C.lblDisbursementDetails.VisibleRow(false);
  C.cboDisbursementExternalParty.VisibleRow(false);
  C.cboDisbursementPayeeType.VisibleRow(false);
  C.cboDisbursementType.VisibleRow(false);
  
  if (mTransactionType) {
    C.txtBatchId.AllowBlank(mTransactionType.BatchIdAllowBlank);
    
    // Auto Post Withholding Tax
    if (mTransactionType.CreditInterest &amp;&amp; mRecord.AddonsDepositAccount) {
      C.lblPostWithholdingTax.VisibleRow(true);
      C.chkAutoPostWithholdingTax.VisibleRow(true);
      C.chkAutoPostWithholdingTax.ReadOnly(!mTransactionType.CreditInterestAllowAutoPostWithholdingTax);
    }
    
    // Disbursement Details
    if (mTransactionType.AllowDisbursementEntry &amp;&amp; mRecord.AddonsDisbursements) {
      C.lblDisbursementDetails.VisibleRow(true);
      C.cboDisbursementExternalParty.VisibleRow(true);
      C.cboDisbursementPayeeType.VisibleRow(true);
      C.cboDisbursementType.VisibleRow(true);      
      
      // Trigger change events
      cboDisbursementType_Change();
      cboDisbursementPayeeType_Change();
    }
  }
  else {
    C.txtBatchId.AllowBlank(false);
  }

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

  // Imported Batch?
  if (mRecord_BatchDetails &amp;&amp; mRecord_BatchDetails.Imported) {
  }
}

// ===============
// FORM: New Batch
// ===============
function BatchNew() {
  // Create Modal
  mForm_BatchNew = widget.UI.Modal({
    title: "New 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 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 Batch, please wait...");

    // Create Parameters
    var params = {
                   transactionTypeId: C.cboNewTransactionType.Text(),
                   batchId: C.txtNewBatchId.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);
        C.cboDisbursementType.Text(data.DefaultDisbursementType);
        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);
  }
}

// ====================
// gridCurrentProcesses
// ====================
function gridCurrentProcesses_Refresh() {
  // Add Columns
  if (C.gridCurrentProcesses.ColumnCount() == 0) {
    C.gridCurrentProcesses.AddColumnDrilldown();
    C.gridCurrentProcesses.AddColumnString("StatusText", { caption: "Status" });
    C.gridCurrentProcesses.AddColumnDateTime("CreatedDate", { caption: "Started" });
  }

  // Refresh
  C.gridCurrentProcesses.VirtualDataRefresh(mRecord_CurrentProcesses);

  // Activate no rows
  C.gridCurrentProcesses.ActiveDataRowIndex(-1);
}

function gridCurrentProcesses_InitialiseRow(e) {
  var item = mRecord_CurrentProcesses[e.row.listIndex];

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

  // Styles
  switch(item.Status) {
    case "Complete":
      e.row.cells.StatusText.colour = "green";
      break;

    case "CompleteWithErrors":
      e.row.cells.StatusText.colour = "darkred";
      break;

    case "CompleteWithWarnings":
      e.row.cells.StatusText.colour = "orange";
      break;

    case "Failed":
      e.row.cells.StatusText.colour = "red";
      break;

    case "Pending":
    case "InProgress":
    case "InProgressCancelRequested":
      e.row.bold = true;
      break;
  }
}

function gridCurrentProcesses_RowDrilldown(e) {
  ViewExistingProcess(e.row.listIndex);
}

// ===================================
// View an existing Background Process
// ===================================
function ViewExistingProcess(itemIndex) {
  var item = mRecord_CurrentProcesses[itemIndex];
  var Ok = true;
  
  // Note that this Widget does not have a Refresh step.

  if (Ok) {
    // Set Information from Process
    mProcessId = item.ProcessId;
    mComplete = true;

    // Status-dependant
    switch (item.Status) {
      default:
        mFromRecent = true;
        mMonitoringExisting = true;

        // Switch to Progress Page
        tabWizard_Refresh(tabWizard.GetTabIndexById("Progress"));
        pageProgress_Refresh(true);

        // Start monitoring
        Form_ExecuteAction_GetBackgroundProcessStatus();
        break;
    }
  }
}

// =======================
// 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.AddColumnCode("ElementId", { caption: "Element", width: widget.UI.FIELD_WIDTH_CODE_10 });
  C.gridCommitStatuses.AddColumnDate("Date", { caption: "Date" });
  C.gridCommitStatuses.AddColumnCurrency("Value", { caption: "Value" });
  if (mRecord.AddonsDisbursements) C.gridCommitStatuses.AddColumnCurrency("Disburse", { caption: "Disburse" });
  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 />
    <UniqueId>9dCtEe5hPE2JwXdqvbEClA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1280</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1600</HtmlWidgetMaxWidth>
    <HtmlWidgetDarkModeNotSupported>false</HtmlWidgetDarkModeNotSupported>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetShowParameterEntry>false</HtmlWidgetShowParameterEntry>
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>Transaction_Entry</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 Transaction 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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="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>
          <Parameter name="DesktopMode" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>