<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-26T02:38:52.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-10-06T01:40:25.2170000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-26T02:38:15.3600000</UpdatedUtcDate>
    <ScriptId>PDD</ScriptId>
    <Description>Process Direct Debit Payments</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountDirectDebitsProcess
Option Explicit On
Option Strict On

' #################################################################
' Process Direct Debit Payments
'
' Version: 1.05 (26/09/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  19/11/2021  ISS      J024137   Created
'    1.01  08/12/2021  ISS      J027840   Spelling Correction
'    1.02  23/09/2022  ISS      J029500   Added option to open Export Bank Transactions wizard after processing
'          28/09/2022  ISS      J029698   Added Bank Account date validation
'          29/09/2022  ISS      J029737   Implemented widget.UI.BuildBackgroundProcessProgress
'    1.03  24/03/2023  ISS      J030395   Value can now be updated
'    1.04  21/06/2024  ISS      J032861   Most columns in the Direct Debits grid are now sortable
'    1.05  26/09/2024  ISS      J034357   Further enhancements related to J032861
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountDirectDebitsProcess"

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

' Other
Private mAutoCommit As Boolean
Private mHideValidRows As Boolean
Private mProcessId As String

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 Parameters
  With mCombinedParameters
    mAutoCommit = .GetBoolean("AutoCommit")
    mHideValidRows = .GetBoolean("HideValidRows")
    mProcessId = .GetString("ProcessId")
  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 "CancelBackgroundProcess"
      ' Cancel a Process
      Main = CancelBackgroundProcess(returnValue)

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

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

    Case "GetCurrentProcesses"
      ' Get Current Processes
      Main = GetCurrentProcesses(returnValue)

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

    Case "GetItemPreview"
      ' Get the HTML Summary Page for the active row on the grid
      Main = GetItemPreview(returnValue)

    Case "GetProcessSummary"
      ' Get Process Summary
      Main = GetProcessSummary(parametersJson, returnValue)

    Case "Refresh"
      ' Refresh (and Execute Commit, if in Auto Commit mode)
      Main = Refresh(parametersJson, returnValue)

    Case "UpdateRefreshData"
      ' Update Refresh Data
      Main = UpdateRefreshData(parametersJson)

    Case "WizardValidate"
      ' Validate wizard page
      Main = WizardValidate(parametersJson, returnValue)
      
    Case Else
      finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
      Main = False
  End Select

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 AccountDirectDebits As finAccountDirectDebits
  Dim BankAccountRO As finBankAccountRO
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

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

  ' Validate Process Id
  If Success AndAlso Len(mProcessId) &lt;&gt; 0 Then
    Success = finBL.HtmlWidgetUtilities.BackgroundProcessStatusIsValid(mProcessId, isefinCloudConnectProcessType.AccountDirectDebitsProcess)
  End If

  ' Get finAccountDirectDebits Object
  If Success Then
    Success = CreateAccountDirectDebits(Nothing, AccountDirectDebits)
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ProcessId = mProcessId
      .BankAccountId = AccountDirectDebits.SetDefaultBankAccount()
      .PaymentsDueProcessToDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountDirectDebits.PaymentsDueProcessToDate)
      .PostPaymentTransactionsDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountDirectDebits.PostPaymentTransactionsDate)

      ' Lists
      For Each BankAccountRO In finBL.BankAccounts
        If BankAccountRO.Active Then
          .BankAccounts.Add(New BankAccount(BankAccountRO))
        End If
      Next 
      
      ' Advanced
      .ShowAccountManagers = mCombinedParameters.GetString("ShowAccountManagers") : If Len(.ShowAccountManagers) = 0 Then .ShowAccountManagers = "Advanced"
      .ShowAccounts = mCombinedParameters.GetString("ShowAccounts") : If Len(.ShowAccounts) = 0 Then .ShowAccounts = "Advanced"
      .ShowAccountTypes = mCombinedParameters.GetString("ShowAccountTypes") : If Len(.ShowAccountTypes) = 0 Then .ShowAccountTypes = "Advanced"
      .ShowBranches = mCombinedParameters.GetString("ShowBranches") : If Len(.ShowBranches) = 0 Then .ShowBranches = "True"
      .ShowClientGroups = mCombinedParameters.GetString("ShowClientGroups") : If Len(.ShowClientGroups) = 0 Then .ShowClientGroups = "Advanced"
      .ShowClients = mCombinedParameters.GetString("ShowClients") : If Len(.ShowClients) = 0 Then .ShowClients = "Advanced"
      .ShowClientTypes = mCombinedParameters.GetString("ShowClientTypes") : If Len(.ShowClientTypes) = 0 Then .ShowClientTypes = "Advanced"
      .ShowDepartments = mCombinedParameters.GetString("ShowDepartments") : If Len(.ShowDepartments) = 0 Then .ShowDepartments = "Advanced"
      .ShowEntities = mCombinedParameters.GetString("ShowEntities") : If Len(.ShowEntities) = 0 Then .ShowEntities = "True"
      .ShowPaymentMethods = mCombinedParameters.GetString("ShowPaymentMethods") : If Len(.ShowPaymentMethods) = 0 Then .ShowPaymentMethods = "True"
      .ShowProductTypes = mCombinedParameters.GetString("ShowProductTypes") : If Len(.ShowProductTypes) = 0 Then .ShowProductTypes = "Advanced"

      ' Licence
      If Not finBL.Settings.AddOns.Branch Then .ShowBranches = "False"
      If Not finBL.Settings.AddOns.Entity Then .ShowEntities = "False"

      ' Ranges Heading
      If (.ShowPaymentMethods = "True" OrElse .ShowAccounts = "True" OrElse .ShowAccountManagers = "True" OrElse .ShowAccountTypes = "True" OrElse
          .ShowBranches = "True" OrElse .ShowClients = "True" OrElse .ShowClientGroups = "True" OrElse .ShowClientTypes = "True" OrElse
          .ShowDepartments = "True" OrElse .ShowEntities = "True" OrElse .ShowProductTypes = "True") Then
        .ShowRangesHeading = "True"
      ElseIf (.ShowPaymentMethods = "False" AndAlso .ShowAccounts = "False" AndAlso .ShowAccountManagers = "False" AndAlso .ShowAccountTypes = "False" AndAlso
              .ShowBranches = "False" AndAlso .ShowClients = "False" AndAlso .ShowClientGroups = "False" AndAlso .ShowClientTypes = "False" AndAlso
              .ShowDepartments = "False" AndAlso .ShowEntities = "False" AndAlso .ShowProductTypes = "False") Then
        .ShowRangesHeading = "False"
      Else
        .ShowRangesHeading = "Advanced"
      End If

      ' General
      .PageGeneralHasAdvanced = (.ShowPaymentMethods = "Advanced" OrElse .ShowAccounts = "Advanced" OrElse .ShowAccountManagers = "Advanced" OrElse
                                 .ShowAccountTypes = "Advanced" OrElse .ShowBranches = "Advanced" OrElse .ShowClients = "Advanced" OrElse
                                 .ShowClientGroups = "Advanced" OrElse .ShowClientTypes = "Advanced" OrElse .ShowDepartments = "Advanced" OrElse
                                 .ShowEntities = "Advanced" OrElse .ShowProductTypes = "Advanced")

      ' Permissions
      .CanUpdateValue = finBL.CurrentUser.Permissions.Allow("Account.DirectDebitProcessing.ValueUpdate")

      ' Configuration
      .AutoCommit = mAutoCommit
      .HideValidRows = mHideValidRows
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    End With

    ' Get current and recent Background Processes for this User
    If Success Then
      If finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_AccountDirectDebits(True, ProcessStatuses) Then
        FormInitialisationInfo.CurrentProcesses = ProcessStatuses
      Else
        Success = False
      End If
    End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get the HTML Summary Page for the active row on the grid.
''' &lt;/summary&gt;
Private Function GetItemPreview(ByRef returnValue As String) As Boolean

  Dim AccountDirectDebits As finAccountDirectDebits
  Dim AccountId As String
  Dim ClientId As String
  Dim Combine As Boolean
  Dim i As Integer
  Dim Include As Boolean
  Dim ProcessId As String
  Dim RefreshData As String
  Dim Success As Boolean
  Dim Value As Decimal

  ' Assume Success
  Success = True

  ' Initialise
  AccountDirectDebits = finBL.CreateAccountDirectDebits()

  ' Get Parameters
  With mCombinedParameters
    AccountId = .GetString("AccountId")
    ClientId = .GetString("ClientId")
    Combine = .GetBoolean("Combine")
    Include = .GetBoolean("Include")
    ProcessId = .GetString("ProcessId")
    Value = .GetDecimal("Value")
  End With

  If Len(AccountId) &lt;&gt; 0 Then
    ' Get Refresh Data (Direct Debit Items)
    Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessRefreshData(ProcessId, RefreshData)

    ' Build Object from Json
    If Success Then
      ' Filter for the specified Client so we only get the subset of items required for the preview
      If AccountDirectDebits.FromHtmlWidgetJsonString(RefreshData, ClientId) Then
        If AccountDirectDebits.Count = 0 Then
          Success = False
          finBL.Error.ErrorBeginFormat("Could not find Accounts belonging to Client '{0}'.", ClientId)
        Else
          Success = AccountDirectDebits.GetIndexByAccountId(AccountId, i)
        End If
      Else
        Success = False
      End If

      ' Extend error with more information
      If Not Success Then
        finBL.Error.ErrorExtend("This may have been caused by the Payment being processed elsewhere. Please cancel this Direct Debit batch and restart the process again.")
      End If
    End If

    ' Get Summary
    If Success Then
      ' Update Direct Debit to match grid
      If i &gt;= 0 AndAlso i &lt; AccountDirectDebits.Count Then
        With AccountDirectDebits(i)
          .Include = Include
          .Combine = Combine
          .Value = Value
        End With
      End If
      
      ' Get Summary
      returnValue = finBL.SummaryPageFunctions.AccountDirectDebitsSummary(False, AccountDirectDebits, i, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
    End If
  End If

  ' Error
  If Not Success Then
    ' Error HTML
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message, finBL.Error.Details)
  End If

  Return Success

End Function

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

  Dim AccountDirectDebit As finAccountDirectDebit
  Dim AccountDirectDebits As finAccountDirectDebits
  Dim cdlItem As ISCodeDescriptionListItem
  Dim CountCannotInclude As Integer
  Dim CountExcluded As Integer
  Dim CountHasWarnings As Integer
  Dim Errors As ISCodeDescriptionList
  Dim ErrorsSummaryTable As ISSummaryTable
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim ValueFee As Decimal
  Dim ValueIncluded As Decimal
  Dim Warnings As ISCodeDescriptionList
  Dim WarningsSummaryTable As ISSummaryTable

  ' Assume Success
  Success = True

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()
  Errors = finBL.Runtime.CreateCodeDescriptionList(iseCodeDescriptionListType.Normal)
  ErrorsSummaryTable = finBL.CreateSummaryTable()
  Warnings = finBL.Runtime.CreateCodeDescriptionList(iseCodeDescriptionListType.Normal)
  WarningsSummaryTable = finBL.CreateSummaryTable()

  ' Get finAccountDirectDebits
  If CreateAccountDirectDebits(Nothing, AccountDirectDebits) Then
    Success = AccountDirectDebits.FromHtmlWidgetJsonString(parametersJson)
  Else
    Success = False
  End If

  ' Calculate Totals
  If Success Then
    For Each AccountDirectDebit In AccountDirectDebits
      With AccountDirectDebit
        ' Exportable
        If .IsExportable Then
          ' Included
          If .Include Then
            ValueIncluded += .Value
            ValueFee += .Fee

            ' Warnings
            If Len(.InvalidMessage) &lt;&gt; 0 Then
              CountHasWarnings += 1

              ' Add to Warnings List
              If Warnings.ExistsDescription(.InvalidMessage) Then
                Warnings(Warnings.IndexOfDescription(.InvalidMessage)).Code = CStr(CInt(Warnings(Warnings.IndexOfDescription(.InvalidMessage)).Code) + 1)
              Else
                Warnings.Add(CStr(1), .InvalidMessage)
              End If
            End If
          Else
            CountExcluded += 1
          End If
        Else
          ' Cannot Include
          CountCannotInclude += 1

          ' Add to Errors List
          If Errors.ExistsDescription(.InvalidMessage) Then
            Errors(Errors.IndexOfDescription(.InvalidMessage)).Code = CStr(CInt(Errors(Errors.IndexOfDescription(.InvalidMessage)).Code) + 1)
          Else
            Errors.Add(CStr(1), .InvalidMessage)
          End If
        End If
      End With
    Next

    ' List Sorting
    Errors.Sort(False)
    Warnings.Sort(False)
  End If

  ' Summary
  If Success Then
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information

      ' Columns
      With .Columns
        .AddText()
        .AddInteger()
      End With

      .Rows.AddSectionHeading2("Payments")
      .AddRowCaptionInteger("Included:", AccountDirectDebits.CountIncluded)
      .AddRowCaptionInteger("Excluded:", CountExcluded)
      .AddRowCaptionInteger("Cannot Include:", CountCannotInclude,,, iseSummaryTableRowClass.Negative)
      .AddRowCaptionInteger("Total:", AccountDirectDebits.Count,, True, iseSummaryTableRowClass.FooterBold)

      If CountHasWarnings &lt;&gt; 0 Then
        If CountHasWarnings = 1 Then
          .Rows.AddText("{{info|See below to review **1 warning** for included Payments.}}")
        Else
          .Rows.AddText("{{info|See below to review **" &amp; CountHasWarnings &amp; " warnings** for included Payments.}}")
        End If
      End If

      .Rows.AddSectionHeading2("Value to Process")
      .AddRowCaptionCurrency("Payments:", ValueIncluded, False, True)
      .AddRowCaptionCurrency("Fees:", ValueFee, False, True)
      .AddRowCaptionCurrency("Net Value:", ValueIncluded + ValueFee, False, True, iseSummaryTableRowClass.FooterBold)
    End With
  End If

  ' Warnings
  If Success AndAlso Warnings.Count &lt;&gt; 0 Then
    WarningsSummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Columns
    With WarningsSummaryTable.Columns
      .AddInteger("Count")
      .AddText("Warning")
    End With

    For Each cdlItem In Warnings
      With WarningsSummaryTable.Rows.Add.Cells
        .AddInteger(CInt(cdlItem.Code))
        .AddText(cdlItem.Description)
      End With
    Next
  End If

  ' Errors
  If Success AndAlso Errors.Count &lt;&gt; 0 Then
    ErrorsSummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Columns
    With ErrorsSummaryTable.Columns
      .AddInteger("Count")
      .AddText("Error")
    End With

    For Each cdlItem In Errors
      With ErrorsSummaryTable.Rows.Add.Cells
        .AddInteger(CInt(cdlItem.Code))
        .AddText(cdlItem.Description)
      End With
    Next
  End If

  ' Build Summary Page
  If Success Then
    sb.Initialise(ScriptInfo)
    sb.HtmlHeaderBegin("ProcessSummary", isefinSummaryPageStyle.Blocks)
    sb.HtmlHeaderEnd()

    sb.SectionColumnsBegin("50%", "350px")
    sb.ColumnBegin("100%")

    sb.BlockBegin("Process Direct Debit Payments Summary", "", isefinSummaryPageBlockHeadingStyle.Main)
    sb.SummaryTableAppend(SummaryTable)
    sb.BlockEnd()

    sb.ColumnEnd()
    sb.SectionColumnsEnd()

    ' Warnings &amp; Errors
    sb.SectionColumnsBegin("100%")
    sb.ColumnBegin("100%")

    ' Errors
    If ErrorsSummaryTable.HasData Then
      sb.BlockBegin("Errors",, isefinSummaryPageBlockHeadingStyle.Warning)
      sb.SummaryTableAppend(ErrorsSummaryTable)
      sb.BlockEnd()
    End If

    ' Warnings
    If WarningsSummaryTable.HasData Then
      sb.BlockBegin("Warnings", "For Included Payments")
      sb.SummaryTableAppend(WarningsSummaryTable)
      sb.BlockEnd()
    End If

    sb.ColumnEnd()
    sb.SectionColumnsEnd()

    sb.HtmlFinalise()
  End If

  ' Get HTML
  If Success Then
    returnValue = sb.ToString(True)
  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;
'''  Builds a finAccountDirectDebits object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateAccountDirectDebits(parameters As WizardFinishParameters,
                                           ByRef accountDirectDebits As finAccountDirectDebits) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountDirectDebits = finBL.CreateAccountDirectDebits()

  ' Update Parameters
  If Success AndAlso parameters IsNot Nothing Then
    With accountDirectDebits
      .BankAccountId = parameters.BankAccountId
      .PaymentsDueProcessToDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.PaymentsDueProcessToDate)
      .PostPaymentTransactionsDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.PostPaymentTransactionsDate)

      .RangeAccountManagers = parameters.RangeAccountManagers
      .RangeAccounts = parameters.RangeAccounts
      .RangeAccountTypes = parameters.RangeAccountTypes
      .RangeBranches = parameters.RangeBranches
      .RangeClientGroups = parameters.RangeClientGroups
      .RangeClients = parameters.RangeClients
      .RangeClientsIncludeAllOwners = parameters.RangeClientsIncludeAllOwners
      .RangeClientTypes = parameters.RangeClientTypes
      .RangeDepartments = parameters.RangeDepartments
      .RangeEntities = parameters.RangeEntities
      .RangePaymentMethods = parameters.RangePaymentMethods
      .RangeProductTypes = parameters.RangeProductTypes
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Refresh, i.e., Queue Background Process.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Refresh(parametersJson As String,
                         ByRef returnValue As String) As Boolean

  Dim AccountDirectDebits As finAccountDirectDebits
  Dim ProcessId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Validate

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get finAccountDirectDebits Object
  If Success Then
    Success = CreateAccountDirectDebits(WizardFinishParameters, AccountDirectDebits)
  End If

  ' Queue Background Process
  If Success Then
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_AccountDirectDebits_Refresh(AccountDirectDebits, mAutoCommit, ProcessId)
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Queue Background Process.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Queue Background Process
  If mAutoCommit Then
    ' Queue "Refresh" - Execute Commit will occur automatically
    Success = Me.Refresh(parametersJson, returnValue)
  Else
    ' Get Wizard Finish Parameters
    Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

    ' Queue Background Process
    If Success Then
      Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_AccountDirectDebits_ExecuteCommit(WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData)
    End If

    ' Finalise
    If Success Then
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(WizardFinishParameters.ProcessId), returnValue)
    End If
  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 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_AccountDirectDebits(True, ProcessStatuses)

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef wizardFinishParameters As WizardFinishParameters) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Update Refresh Data.
''' &lt;/summary&gt;
Private Function UpdateRefreshData(parametersJson As String) As Boolean

  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Update Process
  If Success Then
    Success = finBL.HtmlWidgetUtilities.UpdateBackgroundProcessRefreshData(WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData)
  End If

  Return Success

End Function

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

  Dim BankAccountId As String                                
  Dim ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim PostPaymentTransactionsDate As Date
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
      ConfirmList = New List(Of String)()
      
      ' Validate Bank Account Dates
      If finBL.BankAccounts.Exists(BankAccountId) Then
        With finBL.BankAccounts(BankAccountId)
          If .AllowDirectDebitsOnAnyDate Then
            If PostPaymentTransactionsDate &lt; finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(-7) Then
              FailedControlId = "datePostPaymentTransactionsDate"
              FailedMessage = "The date to post Payment Transactions on must be on or after 7 days ago."
            ElseIf Not .CalendarProcessing.IsBusinessDay(PostPaymentTransactionsDate) Then
              ConfirmList.Add(String.Format("{0} is not a day the bank normally processes Direct Debits.", finBL.FormatDateLong(PostPaymentTransactionsDate)))
            End If
          Else 
            If PostPaymentTransactionsDate &lt; finBL.TimeZoneFunctions.GetCurrentDatabaseDate() Then
              FailedControlId = "datePostPaymentTransactionsDate"
              FailedMessage = "The date to post Payment Transactions on must be on or after today."
            ElseIf Not .CalendarProcessing.IsBusinessDay(PostPaymentTransactionsDate) Then
              FailedControlId = "datePostPaymentTransactionsDate"
              FailedMessage = String.Format("{0} is not a day the bank accepts Direct Debits.", finBL.FormatDateLong(PostPaymentTransactionsDate))
            End If
          End If
        End With
      Else 
        FailedControlId = "cboBankAccount"
        FailedMessage = String.Format("Bank Account '{0}' does not exist.", BankAccountId)
      End If
      
      Data = ConfirmList
      
    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unhandled page '{0}' in WizardValidate.", PageId)
  End Select

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardValidateResponse(Data, FailedMessage, FailedControlId), returnValue)
  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)
  Public ProcessId As String

  ' Record
  Public BankAccountId As String
  Public PaymentsDueProcessToDate As Date
  Public PostPaymentTransactionsDate As Date

  ' Lists
  Public BankAccounts As New List(Of BankAccount)
  
  ' Advanced
  Public PageGeneralHasAdvanced As Boolean
  Public ShowAccountManagers As String
  Public ShowAccounts As String
  Public ShowAccountTypes As String
  Public ShowBranches As String
  Public ShowClientGroups As String
  Public ShowClients As String
  Public ShowClientTypes As String
  Public ShowDepartments As String
  Public ShowEntities As String
  Public ShowPaymentMethods As String
  Public ShowProductTypes As String
  Public ShowRangesHeading As String

  ' Permissions
  Public CanUpdateValue As Boolean

  ' Configuration
  Public AutoCommit As Boolean
  Public HideValidRows As Boolean
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean

End Class



''' &lt;summary&gt;
'''  Bank Account.
''' &lt;/summary&gt;
Public Class BankAccount

  Public BankAccountId As String
  Public Description As String
  Public PostPaymentTransactionsDate As Date
  
  Public Sub New(bankAccountRO As finBankAccountRO)
    
    With bankAccountRO
      Me.BankAccountId = .BankAccountId
      Me.Description = .Description
      
      If .AllowDirectDebitsOnAnyDate Then
        Me.PostPaymentTransactionsDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBLShared.TimeZoneFunctions.GetCurrentDatabaseDate())
      Else 
        Me.PostPaymentTransactionsDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.CalendarProcessing.GetNextBusinessDay(finBLShared.TimeZoneFunctions.GetCurrentDatabaseDate()))
      End If
      
    End With
    
  End Sub
  
End Class



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

  Public ProcessId As String

  Public Sub New(processId As String)

    Me.ProcessId = processId

  End Sub

End Class



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

  ' Parameters
  Public BankAccountId As String
  Public PaymentsDueProcessToDate As Date
  Public PostPaymentTransactionsDate As Date

  ' Ranges
  Public RangeAccountManagers As String
  Public RangeAccounts As String
  Public RangeAccountTypes As String
  Public RangeBranches As String
  Public RangeClientGroups As String
  Public RangeClients As String
  Public RangeClientsIncludeAllOwners As Boolean
  Public RangeClientTypes As String
  Public RangeDepartments As String
  Public RangeEntities As String
  Public RangePaymentMethods As String
  Public RangeProductTypes As String

  ' Other
  Public ProcessId As String
  Public RefreshData As String

End Class



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

  Public Data As Object
  Public FailedControlId As String
  Public FailedMessage 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</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "AccountDirectDebitsProcess".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
/* Total Summary */
.value-summary {
  display:flex;
  flex-direction:row;

  div {
    font-size:11px;

    &gt; b {
      font-size:14px;
    }
  }

  div:nth-child(2),
  div:nth-child(3) {
    padding-left:12px;
  }
}

/* Small device portrait */
@media screen and (max-width:640px) {
  .value-summary {
    flex-direction:column;
    font-size:12px;

    div:nth-child(2),
    div:nth-child(3) {
      padding-left:0px;
    }
  }
}
&lt;/style&gt;

&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 Direct Debits you have processed."&gt;Recent Direct Debit Processing&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Select the Processing options you wish to run."&gt;Processing options&lt;/li&gt;
        &lt;li tabId="Items" tooltipText="Select the Payments to include."&gt;Payments&lt;/li&gt;
        &lt;li tabId="Confirm" tooltipText="Confirm the Direct Debit Payments to begin processing."&gt;Confirmation&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&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:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBankAccount"&gt;Select the Bank Account to process&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBankAccount"&gt;Bank Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBankAccount" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPaymentsDueProcessToDate"&gt;Process payments due on or before&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePaymentsDueProcessToDate"&gt;Payments to:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePaymentsDueProcessToDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPostPaymentTransactionsDate"&gt;Date to post Payment Transactions on&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePostPaymentTransactionsDate"&gt;Process on:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePostPaymentTransactionsDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr advancedId="RangesHeading"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRanges"&gt;Enter ranges to filter information&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="PaymentMethods"&gt;
          &lt;th&gt;&lt;label for="txtRangePaymentMethods"&gt;Payment&amp;nbsp;Methods:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangePaymentMethods" lookupCaption="Payment Methods" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Accounts"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccounts"&gt;Accounts:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccounts" lookupCaption="Accounts" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountManagers"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountManagers"&gt;Account&amp;nbsp;Managers:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountManagers" lookupCaption="Account Managers" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountTypes"&gt;Account&amp;nbsp;Types:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountTypes" lookupCaption="Account Types" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Branches"&gt;
          &lt;th&gt;&lt;label for="txtRangeBranches"&gt;Branches:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeBranches" lookupCaption="Branches" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Clients"&gt;
          &lt;th&gt;&lt;label for="txtRangeClients"&gt;Clients:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClients" lookupCaption="Clients" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Clients"&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRangeClientsIncludeAllOwners" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ClientGroups"&gt;
          &lt;th&gt;&lt;label for="txtRangeClientGroups"&gt;Client&amp;nbsp;Groups:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClientGroups" lookupCaption="Client Groups" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ClientTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeClientTypes"&gt;Client&amp;nbsp;Types:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClientTypes" lookupCaption="Client Types" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Departments"&gt;
          &lt;th&gt;&lt;label for="txtRangeDepartments"&gt;Departments:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeDepartments" lookupCaption="Departments" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Entities"&gt;
          &lt;th&gt;&lt;label for="txtRangeEntities"&gt;Entities:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeEntities" lookupCaption="Entities" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ProductTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeProductTypes"&gt;Product&amp;nbsp;Types:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeProductTypes" lookupCaption="Product Types" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Update 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="gridDirectDebitItems"&gt;&lt;/div&gt;
          &lt;div id="divDirectDebitSummary" class="is-info-text info" style="position:absolute; bottom:2px; right:2px; line-height:19px; font-size:15px; margin:0"&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="panel"&gt;
          &lt;div id="wbDirectDebitSummary" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Confirmation --&gt;
    &lt;div id="pageConfirm"&gt;
      &lt;div id="wbProcessSummary"&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;/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="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;&amp;lt; Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next &amp;gt;&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Commit&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;

&lt;script&gt;
// Properties
var mRecord;
var mRecord_BackgroundProcessStatus;
var mRecord_CurrentProcesses;

var mAccountDirectDebits;

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

  //   General
  lblBankAccount: null,
  cboBankAccount: null,

  lblPaymentsDueProcessToDate: null,
  datePaymentsDueProcessToDate: null,

	lblPostPaymentTransactionsDate: null,
  datePostPaymentTransactionsDate: null,

  lblRanges: null,
  txtRangePaymentMethods: null,
  txtRangeAccounts: null,
  txtRangeAccountManagers: null,
  txtRangeAccountTypes: null,
  txtRangeBranches: null,
  txtRangeClients: null,
  chkRangeClientsIncludeAllOwners: null,
  txtRangeClientGroups: null,
  txtRangeClientTypes: null,
  txtRangeDepartments: null,
  txtRangeEntities: null,
  txtRangeProductTypes: null,

  //   Allocation Items
  gridDirectDebitItems: null,
  divDirectDebitSummary: null,
  wbDirectDebitSummary: null,

  //   Confirm
  wbProcessSummary: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;
var cmdAdvanced;

// Other
var mAccounts;
var mAdvancedVisible = false;
var mBankAccount;
var mComplete = false;
var mFromRecent = false;
var mLastRefreshParametersJson = "";
var mLastProcessSummaryJson = "";
var mMonitoringExisting = false;
var mProcessId;

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

  // Controls
  //   General
  C.lblBankAccount = widget.UI.Label("lblBankAccount", {});
  C.cboBankAccount = widget.UI.DBCombo("cboBankAccount", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,
    
    onChange: cboBankAccount_Change,
  });

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

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

  C.lblRanges = widget.UI.Label("lblRanges", {});
  C.chkRangeClientsIncludeAllOwners = widget.UI.CheckBox("chkRangeClientsIncludeAllOwners", {
    caption: "Include all Owner Clients?",
    captionWrap: true,
  });

  //   Update Items
  C.divDirectDebitSummary = $("#divDirectDebitSummary");
  C.wbDirectDebitSummary = widget.UI.PreviewPane("wbDirectDebitSummary", {});

  //   Confirm
  C.wbProcessSummary = widget.UI.PreviewPane("wbProcessSummary", {});

  //   Progress
  C.divProgress = $("#divProgress");

  // Ranges
  for(var k in C) {
    if (k.startsWith("txtRange")) {
      C[k] = widget.UI.TextBox(k, {
        maxLength: 255,
        onButtonClick: txtRange_ButtonClick,
      });
      var buttons = [];

      // Lookup button
      buttons.push({id: "Lookup", icon: "Find", tooltipText: "Lookup"});

      // Define buttons
      C[k].ButtonsDefine(buttons);
    }
  }

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

    onAction: gridCurrentProcesses_Action,
    onAfterRowActivate: gridCurrentProcesses_AfterRowActivate,
    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

  C.gridDirectDebitItems = widget.UI.Grid("gridDirectDebitItems", {
    allowCellSelect: false,
    allowMultiRowSelect: true,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridDirectDebitItems_Action,
    onAfterRowActivate: gridDirectDebitItems_AfterRowActivate,
    onBeforeCellUpdate: gridDirectDebitItems_BeforeCellUpdate,
    onInitialiseRow: gridDirectDebitItems_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" });

  // 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");
  cmdHistory.click(function() { Form_ExecuteAction("Recent"); });

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(AdvancedToggle);

  // Handle Notifications
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Reset
  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_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mAccounts = null;
  mAccountDirectDebits = null;

  // Hide content
  frmMain.Visible(false);

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

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

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mRecord.BankAccounts, "BankAccountId");

      // Load Fields
      Fields_Load();

      // Notify if there are Current Processes
      var countCurrent = 0;
      var processIndex = -1;
      for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
        var item = mRecord_CurrentProcesses[i];

        // Process
        if (mRecord.ProcessId &amp;&amp; mRecord.ProcessId == item.ProcessId) {
          processIndex = i;
        }

        // Status
        switch (item.Status) {
          case "Pending":
          case "PendingCommit":
          case "InProgress":
          case "InProgressRefreshComplete":
          case "InProgressCancelRequested":
            countCurrent += 1;
            break;
        }
      }
      if (processIndex != -1) {
        ViewExistingProcess(processIndex);
      }
      else if (countCurrent != 0) {
        tabWizard_Move(-1);
        widget.UI.MsgBoxInfo("There are existing incomplete Direct Debit Payments that you have started and are not yet complete.\n\nYou can review these or use the 'Next &gt;' button to begin a new instance of Direct Debit Processing.", { heading: "Direct Debit Payments still Processing", icon: "MonitorCategory"} );
      }
    },

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // Current Processes
    // NOTE: Bind here since this is the first page
    gridCurrentProcesses_Refresh();

    // General
    C.cboBankAccount.Text(mRecord.BankAccountId);
    C.datePaymentsDueProcessToDate.Value(mRecord.PaymentsDueProcessToDate);
    C.datePostPaymentTransactionsDate.Value(mRecord.PostPaymentTransactionsDate);
  }

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

  // Update Controls
  cboBankAccount_Change();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

  // Lists
  C.cboBankAccount.RefreshFromCollection(mRecord.BankAccounts, "BankAccountId", "Description");

  // Controls
  if(mRecord) {
    // Initialise Advanced
    AdvancedInitialise();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess() {
  if (mAccountDirectDebits) {
    // Controls
    C.cboBankAccount.Text(mAccountDirectDebits.BankAccountId);
    C.datePaymentsDueProcessToDate.Value(mAccountDirectDebits.PaymentsDueProcessToDate);
    C.datePostPaymentTransactionsDate.Value(mAccountDirectDebits.PostPaymentTransactionsDate);

    // Ranges
    C.txtRangeAccountManagers.Text(mAccountDirectDebits.RangeAccountManagers);
    C.txtRangeAccounts.Text(mAccountDirectDebits.RangeAccounts);
    C.txtRangeAccountTypes.Text(mAccountDirectDebits.RangeAccountTypes);
    C.txtRangeBranches.Text(mAccountDirectDebits.RangeBranches);
    C.txtRangeClientGroups.Text(mAccountDirectDebits.RangeClientGroups);
    C.txtRangeClients.Text(mAccountDirectDebits.RangeClients);
    C.chkRangeClientsIncludeAllOwners.Value(mAccountDirectDebits.RangeClientsIncludeAllOwners);
    C.txtRangeClientTypes.Text(mAccountDirectDebits.RangeClientTypes);
    C.txtRangeDepartments.Text(mAccountDirectDebits.RangeDepartments);
    C.txtRangeEntities.Text(mAccountDirectDebits.RangeEntities);
    C.txtRangePaymentMethods.Text(mAccountDirectDebits.RangePaymentMethods);
    C.txtRangeProductTypes.Text(mAccountDirectDebits.RangeProductTypes);

    // Advanced
    if (!mAdvancedVisible) {
      var toggle = false;

      if (mAccountDirectDebits.RangeAccountManagers &amp;&amp; mAccountDirectDebits.RangeAccountManagers.length != 0 &amp;&amp; mRecord.ShowAccountManagers.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeAccounts &amp;&amp; mAccountDirectDebits.RangeAccounts.length != 0 &amp;&amp; mRecord.ShowAccounts.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeAccountTypes &amp;&amp; mAccountDirectDebits.RangeAccountTypes.length != 0 &amp;&amp; mRecord.ShowAccountTypes.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeBranches &amp;&amp; mAccountDirectDebits.RangeBranches.length != 0 &amp;&amp; mRecord.ShowBranches.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeClientGroups &amp;&amp; mAccountDirectDebits.RangeClientGroups.length != 0 &amp;&amp; mRecord.ShowClientGroups.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeClients &amp;&amp; mAccountDirectDebits.RangeClients.length != 0 &amp;&amp; mRecord.ShowClients.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeClientsIncludeAllOwners &amp;&amp; mAccountDirectDebits.RangeClientsIncludeAllOwners &amp;&amp; mRecord.ShowClients.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeClientTypes &amp;&amp; mAccountDirectDebits.RangeClientTypes.length != 0 &amp;&amp; mRecord.ShowClientTypes.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeDepartments &amp;&amp; mAccountDirectDebits.RangeDepartments.length != 0 &amp;&amp; mRecord.ShowDepartments.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeEntities &amp;&amp; mAccountDirectDebits.RangeEntities.length != 0 &amp;&amp; mRecord.ShowEntities.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangePaymentMethods &amp;&amp; mAccountDirectDebits.RangePaymentMethods.length != 0 &amp;&amp; mRecord.ShowPaymentMethods.toUpperCase() != "TRUE") toggle = true;
      if (mAccountDirectDebits.RangeProductTypes &amp;&amp; mAccountDirectDebits.RangeProductTypes.length != 0 &amp;&amp; mRecord.ShowProductTypes.toUpperCase() != "TRUE") toggle = true;

      // Toggle
      if (toggle) AdvancedToggle();
    }
  }
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      default:
        break;
    }
  }

  // Always Refresh Current Processes, even when moving back
  if (newTab == 0) {
    if (!mRecord_CurrentProcesses) pageCurrentProcesses_Refresh();
  }

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

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

      // Reset Objects
      mAccountDirectDebits = null;
      mLastRefreshParametersJson = null;
      mProcessId = null;
      break;

    case "Items":
      // Refesh Update Items
      pageItems_Refresh();
      break;

    case "Confirm":
      // Confirm
      pageConfirm_Refresh();
      break;

    default:
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

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

  // Resize Wizard
  tabWizard_Resize();

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

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters(includeRefreshData) {
  var params = {
    processId: mProcessId,

    bankAccountId: C.cboBankAccount.Text(),
    paymentsDueProcessToDate: C.datePaymentsDueProcessToDate.Value(),
    postPaymentTransactionsDate: C.datePostPaymentTransactionsDate.Value(),

    rangeAccountManagers: C.txtRangeAccountManagers.Text(),
    rangeAccounts: C.txtRangeAccounts.Text(),
    rangeAccountTypes: C.txtRangeAccountTypes.Text(),
    rangeBranches: C.txtRangeBranches.Text(),
    rangeClientGroups: C.txtRangeClientGroups.Text(),
    rangeClients: C.txtRangeClients.Text(),
    rangeClientsIncludeAllOwners: C.chkRangeClientsIncludeAllOwners.Value(),
    rangeClientTypes: C.txtRangeClientTypes.Text(),
    rangeDepartments: C.txtRangeDepartments.Text(),
    rangeEntities: C.txtRangeEntities.Text(),
    rangePaymentMethods: C.txtRangePaymentMethods.Text(),
    rangeProductTypes: C.txtRangeProductTypes.Text(),
  }

  // Selected Accounts
  if (includeRefreshData &amp;&amp; mAccountDirectDebits) {
    params.RefreshData = JSON.stringify(mAccountDirectDebits);
  }

  return params;
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      if (mComplete) {
        widget.Close();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;

    case "RECENT":
      // Recent
      tabWizard_Refresh(tabWizard.GetTabIndexById("CurrentProcesses"));
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  if (cmdFinish.text() == "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);
  }
  else {
    // Validate
    tabWizard_Validate(function () {
      // Confirmation Message
      var message = "";

      // Build Message
      message += "Are you sure you want to Process Direct Debit Payments?";

      // Background Process
      message += "\n\nNOTE: This may take some time. You can close this form at any time and open it again to monitor progress.";

      // Confirm
      widget.UI.MsgBoxConfirm(message, {}, function () { Form_ExecuteAction_FinishPost(); }, null);
    });
  }
}

function Form_ExecuteAction_FinishPost() {
  // Running new process
  mMonitoringExisting = false;

  // Clear Progress Page
  pageProgress_Refresh(true);

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

  // Create Parameters
  var params = CreateFinishParameters(true);

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

      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();

      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },

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

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

function Form_ExecuteAction_FinishStop() {
  // Continue
  widget.GetString("CancelBackgroundProcess", { processId: mProcessId },
    function (data) {
      widget.UI.MsgBoxInfo("The process has been requested to stop.");
    },

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  var InProgressRefreshComplete = false;

  // Just in case!
  if (!mProcessId) return;

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

      // Override Status
      if (Status == "InProgressRefreshComplete" &amp;&amp; mFromRecent) {
        InProgressRefreshComplete = true;
        Status = "Complete";
      }
      if (Status == "InProgressRefreshComplete" &amp;&amp; mRecord.AutoCommit) {
        Status = "Pending";
      }

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Direct Debit Processing was successfully cancelled.");
          break;

        case "InProgressRefreshComplete":
          // Update Items
          mAccountDirectDebits = JSON.parse(mRecord_BackgroundProcessStatus.RefreshData);

          // Save parameters
          mLastRefreshParametersJson = JSON.stringify(CreateFinishParameters(false));

          // Refresh Complete
          mRecord_BackgroundProcessStatus = null;

          // Set Tab
          tabWizard.SelectedTabId("Items");
          tabWizard_Refresh();
          break;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          if (InProgressRefreshComplete) {
            widget.UI.MsgBoxInfo("Direct Debit Processing Refresh is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          else {
            widget.UI.MsgBoxConfirm("Direct Debit Processing is " + widget.SplitWordsAtCapitals(Status, true, true) + ".\n\nDo you want to export these payments now?", { captionOk: "Yes", captionCancel: "No" }, ExportBankTransactions);
          }
          break;

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

          // Ensure if phase 2 has failed we are not prompted to Save and Close
          if (mAccountDirectDebits) mComplete = true;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Direct Debit Processing 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();
    }
  );
}

// ========================
// Export Bank Transactions
// ========================
function ExportBankTransactions() {
  // Open Export Bank Transactions HTML Widget
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=BankExportTransactions");
  
  // Close
  tabWizard_Cancel();
}

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

  // Block UI
  widget.UI.Block("Refreshing Recent Direct Debit Processes, 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);
    }
  );
}

// ===========
// pageConfirm
// ===========
function pageConfirm_Refresh() {
  // Params
  var params = JSON.parse(JSON.stringify(mAccountDirectDebits));

  // Changed?
  if (mLastProcessSummaryJson == JSON.stringify(params)) return;

  // Clear existing
  C.wbProcessSummary.SetContent("", false);

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

  // Get Summary
  widget.GetString("GetProcessSummary", params,
    function(data) {
      // Save
      mLastProcessSummaryJson = JSON.stringify(params);

      // Update Summary
      C.wbProcessSummary.SetContent(data, false);

      // Unblock
      widget.UI.Unblock();
    },
    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();

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

      // Move back
      tabWizard_Move(-1);
    }
  );
}

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

  // 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 Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// ==============
// cboBankAccount
// ==============
function cboBankAccount_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Get Bank Account
  mBankAccount = mRecord.BankAccounts.GetItem(C.cboBankAccount.Text());
  if (mBankAccount) {
    C.datePostPaymentTransactionsDate.Value(mBankAccount.PostPaymentTransactionsDate);
  }
}

// ===============
// pageItems
// ===============
function pageItems_Refresh() {
  // Refresh Grid
  if (mAccountDirectDebits) {
    gridDirectDebitItems_Refresh();
  }
}

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

    // Actions
    C.gridCurrentProcesses.Actions().Define([{ actionId: "Cancel", caption: "Cancel", tooltipText: "Cancel the selected 'Refresh Complete' row", icon: "Trash" }]);
  }

  // Determine if Actions should be visible
  var found = false;
  for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
    var item = mRecord_CurrentProcesses[i];

    if (item.Status == "InProgressRefreshComplete") {
      found = true;
      break;
    }
  }
  C.gridCurrentProcesses.Actions().SetVisible("Cancel", found);

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

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

function gridCurrentProcesses_Action(actionId) {
  var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];

  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      CancelRefreshCompleteBackgroundProcess(item.ProcessId, pageCurrentProcesses_Refresh);
      break;

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

function gridCurrentProcesses_AfterRowActivate(e) {
  // Refresh Buttons
  gridCurrentProcesses_RefreshButtons();
}

function gridCurrentProcesses_RefreshButtons() {
  if (C.gridCurrentProcesses.ActiveDataRowListIndex() == -1) {
    C.gridCurrentProcesses.Actions().SetEnabled("Cancel", false);
  }
  else {
    var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];
    C.gridCurrentProcesses.Actions().SetEnabled("Cancel", item.Status == "InProgressRefreshComplete");
  }

  C.gridCurrentProcesses.RefreshButtons();
}

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":
    case "InProgressRefreshComplete":
      e.row.bold = true;
      break;
  }
}

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

// ===============
// gridDirectDebitItems
// ===============
function gridDirectDebitItems_Refresh() {
  var showWarnings = false;

  // Show / Hide Columns
  for (var i = 0; i &lt; mAccountDirectDebits.Items.length; i++) {
    var item = mAccountDirectDebits.Items[i];

    // Warnings
    if (item.InvalidMessage) showWarnings = true;
  }

  // Add Columns
  C.gridDirectDebitItems.ClearColumns();
  C.gridDirectDebitItems.AddColumnIcon("Icon", { caption: "", visible: showWarnings });
  C.gridDirectDebitItems.AddColumnBoolean("Include", { caption: "Include", allowEdit: true });
  C.gridDirectDebitItems.AddColumnBoolean("Combine", { caption: "Combine", allowEdit: true });
  C.gridDirectDebitItems.AddColumnCode("AccountId", { caption: "Account", sortable: true });
  C.gridDirectDebitItems.AddColumnString("AccountName", { caption: "Name", sortable: true });
  C.gridDirectDebitItems.AddColumnString("PaymentMethodId", { caption: "Pay Method", sortable: true });
  C.gridDirectDebitItems.AddColumnCurrency("Value", { caption: "Value", sortable: true, allowEdit: mRecord.CanUpdateValue });
  C.gridDirectDebitItems.AddColumnCurrency("Fee", { caption: "Fee", sortable: true });
  C.gridDirectDebitItems.AddColumnCurrency("Charge", { caption: "Net Value", sortable: true });
  C.gridDirectDebitItems.AddColumnString("InvalidMessage", { caption: "Status", sortable: true, visible: showWarnings });

  // Actions
  C.gridDirectDebitItems.Actions().Define([{ actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                      { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },
                                      { actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                      { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                      { actionId: "SelectChecked", tooltipText: "Select all rows that are checked to include", icon: "Select_Checked" },
                                      { actionId: "SelectUnchecked", tooltipText: "Select all rows that are not checked to include", icon: "Select_Unchecked" },
                                      {},
                                      { actionId: "Check", tooltipText: "Include selected row(s)", icon: "Checkbox_Checked" },
                                      { actionId: "Uncheck", tooltipText: "Not Include selected row(s)", icon: "Checkbox_Unchecked" },
                                      {},
                                      { actionId: "Combine", tooltipText: "Check 'Combine' on selected row(s)", icon: "Client_Combine" },
                                      { actionId: "NotCombine", tooltipText: "Uncheck 'Combine' on selected row(s)", icon: "Client_Relationship" },
                                     ]);

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mAccountDirectDebits.Items.GetCacheKey = function (index) {
    var item = mAccountDirectDebits.Items[index];
    return "" + item.AccountPk + item.Include + item.Combine + item.Value;
  };
  mAccountDirectDebits.Items.GetPreviewFetchParameters = function (index) {
    var item = mAccountDirectDebits.Items[index];
    var o = {};
    o.AccountId = item.AccountId;
    o.ClientId = item.ClientId;
    o.Include = item.Include;
    o.Combine = item.Combine;
    o.Value = item.Value;
    o.ProcessId = mProcessId;
    return o;
  };

  // Refresh
  C.gridDirectDebitItems.VirtualDataRefresh(mAccountDirectDebits.Items);

  // Select first row
  C.gridDirectDebitItems.ActivateFirstDataRow();

  // Update Totals
  divDirectDebitSummary_Refresh();
}

function gridDirectDebitItems_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "SELECTUP":
      // Select Up
      // NOTE: Because this grid is sortable, we use ActiveDataRowIndex rather than ActiveDataRowListIndex
      var indexes = [];
      for (var i = C.gridDirectDebitItems.ActiveDataRowIndex(); i &gt;= 0; i--) {
        indexes.push(i);
      }
      
      // NOTE: Because this grid is sortable, we use SetSelectedRowIndexesForSortableGrid rather than SetSelectedRowIndexes
      C.gridDirectDebitItems.SetSelectedRowIndexesForSortableGrid(indexes, true);
      indexes = null;
      break;
    
    case "SELECTDOWN":
      // Select Down
      // NOTE: Because this grid is sortable, we use ActiveDataRowIndex rather than ActiveDataRowListIndex
      var indexes = [];
      for (var i = C.gridDirectDebitItems.ActiveDataRowIndex(); i &lt; mAccountDirectDebits.Items.length; i++) {
        indexes.push(i);
      }
      
      // NOTE: Because this grid is sortable, we use SetSelectedRowIndexesForSortableGrid rather than SetSelectedRowIndexes
      C.gridDirectDebitItems.SetSelectedRowIndexesForSortableGrid(indexes, true);
      indexes = null;
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mAccountDirectDebits.Items.length; i++) {
        var item = mAccountDirectDebits.Items[i];
        if(item.IsExportable) indexes.push(i);
      }
      break;

    case "SELECTNONE":
      var indexes = [];
      break;

    case "SELECTCHECKED":
    case "SELECTUNCHECKED":
      var indexes = [];

      for(var i = 0; i &lt; mAccountDirectDebits.Items.length; i++) {
        var item = mAccountDirectDebits.Items[i];

        if(item.IsExportable) {
          if(actionId.toUpperCase() == "SELECTCHECKED" &amp;&amp; item.Include) {
            indexes.push(i);
          }
          else if(actionId.toUpperCase() == "SELECTUNCHECKED" &amp;&amp; !item.Include) {
            indexes.push(i);
          }
        }
      }
      break;

    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridDirectDebitItems.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mAccountDirectDebits.Items[selectedItems[i]];
        if (item.IsExportable) {
          item.Include = (actionId.toUpperCase() == "CHECK")
        }
      }
      C.gridDirectDebitItems.VirtualDataRefresh(mAccountDirectDebits.Items, true, { retainSelectedRows: true });
      break;

    case "COMBINE":
    case "NOTCOMBINE":
      var selectedItems = C.gridDirectDebitItems.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mAccountDirectDebits.Items[selectedItems[i]];
        if (item.CanCombine) {
          item.Combine = (actionId.toUpperCase() == "COMBINE")
        }
      }
      C.gridDirectDebitItems.VirtualDataRefresh(mAccountDirectDebits.Items, true, { retainSelectedRows: true });
      break;
  }

  // Set Indexes
  if(indexes) {
    C.gridDirectDebitItems.SetSelectedVirtualDataRowIndexesForSortableGrid(indexes, true);
  }

  // Update Totals
  divDirectDebitSummary_Refresh();
}

function gridDirectDebitItems_AfterRowActivate(e) {
  // Preview
  wbDirectDebitSummary_Preview();
}

function gridDirectDebitItems_BeforeCellUpdate(e) {
  var item = mAccountDirectDebits.Items[e.row.listIndex];

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

    case "Combine":
      item.Combine = e.newValue;
      break;
      
    case "Value":
      item.Value = e.newValue;
      
      // Update Net Value
      if (item.Fee) {
        item.Charge = (item.Fee + item.Value);
      }
      else {
        item.Charge = item.Value;
      }      
      break;
  }

  // Update Totals
  divDirectDebitSummary_Refresh();
  
  // Refresh Summary
  wbDirectDebitSummary_Preview();
}

function gridDirectDebitItems_InitialiseRow(e) {
  var item = mAccountDirectDebits.Items[e.row.listIndex];

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

  // Hide Row?
  if (mRecord.HideValidRows) {
    if (item.IsExportable &amp;&amp; !item.InvalidMessage) {
      e.row.hidden = true;
    }
  }

  // Invalid rows cannot be edited
  e.row.readOnly = !item.IsExportable;    
  e.row.cells.Value.readOnly = !mRecord.CanUpdateValue;
  if (!item.IsExportable) {
    e.row.cells.Include.value = false;
    e.row.cells.Include.readOnly = true;
  }
  if (!item.CanCombine) {
    e.row.cells.Combine.value = false;
    e.row.cells.Combine.readOnly = true;
  }

  // Name
  e.row.cells.AccountName.small = true;

  // Icon
  if (item.InvalidMessage) {
    if (item.IsExportable) {
      e.row.cells.Icon.value = "Information";
      e.row.cells.InvalidMessage.colour = "#D47700";
    }
    else {
      e.row.cells.Icon.value = "Warning";
      e.row.cells.InvalidMessage.colour = "red";
    }
    e.row.cells.Icon.tooltipText = item.InvalidMessage;
  }

  // Highlight updated rows
  if (item.Value != item.ValueOriginal) {
    e.row.backgroundColour = "#CAFACA";
  }
  else {
    e.row.backgroundColour = "";
  }

  // Hyperlinks
  e.row.cells.AccountId.hyperlink = "app://FormShow?form=Accounts&amp;id=" + widget.UI.HtmlEncode(item.AccountId);
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Direct Debit Processing 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_Post);
  }
  else if (mProcessId &amp;&amp; (tabWizard.SelectedTabId() == "Items" || tabWizard.SelectedTabId() == "Confirm" || mAccountDirectDebits)) {
    var list = [];
    list.push({ key: "CLOSE", caption: "Suspend and Close", icon: "Window_Close", details: "This will close the wizard but retain the list which can be reviewed later by re-opening this wizard." });
    list.push({ key: "CANCEL", caption: "Close and Cancel", icon: "Trash", details: "This will close the wizard and cancel this process. The list of Direct Debit Payments will not be retained." });

    var options = {
      closeOnEscape: true,
      title: "Close Direct Debit Processing",
      showClose: true
    };

    widget.UI.MsgBoxList("Select an option below to close", list, options, function(key) {
      switch (key) {
        case "CLOSE":
          tabWizard_Cancel_Save();
          break;

        case "CANCEL":
          CancelRefreshCompleteBackgroundProcess(mProcessId, tabWizard_Cancel_Post);
          break;
      }
    });
  }
  else {
    tabWizard_Cancel_Post();
  }
}

function tabWizard_Cancel_Save() {
  // Block UI
  widget.UI.Block("Saving, please wait...");

  // Parameters
  var params = CreateFinishParameters(true);

  // Update Refresh Data
  widget.GetString("UpdateRefreshData", params, tabWizard_Cancel_Post, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();

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

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

function tabWizard_Move(direction) {
  var Ok;

  // Validate
  if (direction &gt; 0) {
    tabWizard_Validate(function () { tabWizard_MovePost(direction); });
  }
  else {
    // Can always move backwards
    tabWizard_MovePost(direction);
  }
}

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "Items":
          found = !mRecord.AutoCommit;
          break;

        case "Confirm":
          found = (!mRecord.AutoCommit &amp;&amp; mAccountDirectDebits);
          break;

        default:
          found = true;
          break;
      }

      // Found?
      if (found) {
        break;
      }
      else if (newTab == tabWizard.TabCount() - 1) {
        // Just in case!
        widget.UI.MsgBoxAlert("tabWizard_MovePost: Tab not handled!");
        break;
      }
    }
    while (true);

    // Refresh the New Tab
    tabWizard_Refresh(newTab);
  }
}

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "Confirm":
      C.wbProcessSummary.ResizeFromParent();
      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() - 2);

  // Finish Button
  if (tabWizard.SelectedTabId() == "Confirm") {
    cmdFinish.prop("disabled", false);
  }
  else if (mRecord.AutoCommit &amp;&amp; tabWizard.SelectedTabId() == "General") {
    cmdFinish.prop("disabled", false);
    cmdNext.prop("disabled", true);
  }
  else {
    cmdFinish.prop("disabled", true);
  }

  // Page Exceptions
  if (mRecord_BackgroundProcessStatus) {
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
    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);
  }

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

  // Never allow moving back from Progress page
  if (tabWizard.SelectedTabId() == "Progress") cmdBack.prop("disabled", true);

  // Recent Page exceptions
  if (mFromRecent) {
    cmdHistory.prop("disabled", false);

    cmdBack.prop("disabled", true);
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", true);
  }

  if (mComplete) {
    // 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) {
  // Validate
  var Ok = tabWizard.Validate(true);

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

      case "Items":
        var found = false;
        for (var i = 0; i &lt; mAccountDirectDebits.Items.length; i++) {
          var item = mAccountDirectDebits.Items[i];
          if (item.Include) {
            found = true;
            break;
          }
        }

        if (!found) {
          Ok = false;
          widget.UI.MsgBoxAlert("At least one item must be included to continue.");
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        params = {
          bankAccountId: C.cboBankAccount.Text(),
          postPaymentTransactionsDate: C.datePostPaymentTransactionsDate.Value(),
        }
        break;
    }

    if (params) {
      // Disable Form
      frmMain.FormDisable("Validating");

      // Extend parameters
      params.pageId = tabWizard.SelectedTabId();

      // Call WizardValidate method in Script
      widget.GetString("WizardValidate",
                       params,
                       function (data) { tabWizard_ValidatePost(validCallback, data); },
                       tabWizard_ValidateFail);
    }
    else {    
      // No server-side validation
      validCallback();
    }
  }
}

function tabWizard_ValidatePost(validCallback, data) {
  // Enable form
  frmMain.FormEnable();

  // Parse Data
  var o = {};
  if (data) o = JSON.parse(data);

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { tabWizard_ValidatePost_General(validCallback); },
                                      null);
        }
        else {
          tabWizard_ValidatePost_General(validCallback);
        }
        return;
    }

    // Callback
    validCallback();
  }
}

function tabWizard_ValidatePost_General(validCallback) {
  // Refresh Direct Debits
  if (!mRecord.AutoCommit) RefreshDirectDebits();

  // Callback
  validCallback();
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Advanced handling
// =================
function AdvancedInitialise() {
  // Tweaks

  // General
  AdvancedInitialiseSection("RangesHeading", mRecord.ShowRangesHeading);
  AdvancedInitialiseSection("PaymentMethods", mRecord.ShowPaymentMethods);
  AdvancedInitialiseSection("Accounts", mRecord.ShowAccounts);
  AdvancedInitialiseSection("AccountManagers", mRecord.ShowAccountManagers);
  AdvancedInitialiseSection("AccountTypes", mRecord.ShowAccountTypes);
  AdvancedInitialiseSection("Branches", mRecord.ShowBranches);
  AdvancedInitialiseSection("Clients", mRecord.ShowClients);
  AdvancedInitialiseSection("ClientGroups", mRecord.ShowClientGroups);
  AdvancedInitialiseSection("ClientTypes", mRecord.ShowClientTypes);
  AdvancedInitialiseSection("Departments", mRecord.ShowDepartments);
  AdvancedInitialiseSection("Entities", mRecord.ShowEntities);
  AdvancedInitialiseSection("ProductTypes", mRecord.ShowProductTypes);
}

function AdvancedInitialiseSection(id, option) {
  // Get elements
  var els=$("*[advancedId='" + id + "']");

  // Update
  switch(option.toUpperCase()) {
    case "TRUE":
      // Always show, i.e., not advanced
      break;

    case "FALSE":
      // Never show
      els.hide();
      break;

    case "ADVANCED":
      // Only show in 'Advanced' mode
      els.addClass("advanced");
      break;
  }
}

function AdvancedToggle() {
  // Toggle Advanced
  mAdvancedVisible = !mAdvancedVisible;

  // Update Controls
  if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }

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

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

// =======
// Refresh
// =======
function RefreshDirectDebits() {
  if (mLastRefreshParametersJson == JSON.stringify(CreateFinishParameters(false))) {
    // Parameters have not changed, so do not kick off another refresh
  }
  else {
    // Hide content
    frmMain.Visible(false);

    // Confirmation Message
    var message = "";

    // Build Message
    message += "&lt;p&gt;Click OK to build a list of Direct Debit Payments to be processed.&lt;/p&gt;";

    // Background Process
    message += "&lt;p&gt;NOTE: This may take some time. You can close this form at any time and open it again to monitor progress.&lt;/p&gt;";

    // Process already in progress, warn this will be cancelled
    if (mAccountDirectDebits &amp;&amp; mProcessId) {
      message += "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Accounts have already been refreshed. Continuing will cancel the existing process, and begin a new one.&lt;/p&gt;"
    }

    // Confirm
    var options = {
      heading: "Refresh Direct Debit Payments",
      messageIsHtml: true,
      icon: "Table|Refresh"
    }
    widget.UI.MsgBoxConfirm(message, options,
      function () {
        if (mAccountDirectDebits &amp;&amp; mProcessId) {
          CancelRefreshCompleteBackgroundProcess(mProcessId, RefreshDirectDebits_Post, function() {
            // Move back a page
            tabWizard_Move(-1);

            // Show content
            frmMain.Visible(true);
          })
        }
        else {
          RefreshDirectDebits_Post();
        }
      },

      function() {
        // Move back a page
        tabWizard_Move(-1);

        // Show content
        frmMain.Visible(true);
      }
    );
  }
}

function RefreshDirectDebits_Post() {
  // Running new process
  mMonitoringExisting = false;
  mAccountDirectDebits = null;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Direct Debit Payments Refresh, please wait...");

  // Create Parameters
  var params = CreateFinishParameters(true);

  // Refresh
  widget.GetString("Refresh", params,
    function (data) {
      // Show content
      frmMain.Visible(true);

      // Parse
      data = JSON.parse(data);

      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();

      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },

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

      // Show content
      frmMain.Visible(true);

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

// ==========================================
// Cancel Refresh Complete Background Process
// ==========================================
function CancelRefreshCompleteBackgroundProcess(processId, callback, cancelCallback) {
  widget.UI.MsgBoxConfirm("Are you sure you want to cancel this Background Process?", {},
  function() {
    // Block
    widget.UI.Block("Cancelling Background Process, please wait...");

    // Params
    var params = {
      processId: processId,
    }
    widget.GetString("CancelBackgroundProcess", params, function() { callback(); }, function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();

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

// =====================
// divDirectDebitSummary
// =====================
function divDirectDebitSummary_Refresh() {
  var fees = 0;
  var html = "";
  var value = 0;

  // Total
  for (var i = 0; i &lt; mAccountDirectDebits.Items.length; i++) {
    var item = mAccountDirectDebits.Items[i];

    if (item.Include &amp;&amp; item.IsExportable) {
      value += item.Value;
      if (item.Fee) fees += item.Fee;
    }
  }

  // Message
  html = "&lt;div class='value-summary'&gt;";
  html += "&lt;div&gt;Value: &lt;b&gt;" + widget.UI.HtmlEncode(widget.FormatCurrency(value, true)) + "&lt;/b&gt;&lt;/div&gt;";
  html += "&lt;div&gt;Fees: &lt;b&gt;" + widget.UI.HtmlEncode(widget.FormatCurrency(fees, true)) + "&lt;/b&gt;&lt;/div&gt;";
  html += "&lt;div&gt;Net Value: &lt;b&gt;" + widget.UI.HtmlEncode(widget.FormatCurrency(value + fees, true)) + "&lt;/b&gt;&lt;/div&gt;";
  html += "&lt;/div&gt;";
  C.divDirectDebitSummary.html(html);

  // Show
  C.divDirectDebitSummary.show();
}

// ===================================
// View an existing Background Process
// ===================================
function ViewExistingProcess(itemIndex) {
  var item = mRecord_CurrentProcesses[itemIndex];
  var Ok = true;

  // Validate
  if (item.Status == "InProgressRefreshComplete" &amp;&amp; mRecord.AutoCommit) {
    Ok = false;
    widget.UI.MsgBoxInfo("Cannot resume a two-phase Process when this HTML Widget is configured to run in single-phase (Auto Commit) mode.");
  }

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

    // Status-dependant
    switch (item.Status) {
      case "InProgressRefreshComplete":
        // Update Items
        mAccountDirectDebits = JSON.parse(item.RefreshData);

        // Update Controls
        Fields_Update_FromBackgroundProcess();

        // Save parameters
        mLastRefreshParametersJson = JSON.stringify(CreateFinishParameters(false));

        // Set Tab
        tabWizard.SelectedTabId("Items");
        tabWizard_Refresh();
        break;

      default:
        mFromRecent = true;
        mMonitoringExisting = true;

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

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

// ====================
// wbDirectDebitSummary
// ====================
function wbDirectDebitSummary_Preview() {
  C.wbDirectDebitSummary.PreviewFromGridCollection(C.gridDirectDebitItems, mAccountDirectDebits.Items, "GetItemPreview");
}

// ========
// txtRange
// ========
function txtRange_ButtonClick(sender, e) {
  if (e.id == "Lookup") {
    var caption = sender.Element().attr("lookupCaption");
    var range = sender.Element().attr("id");

    range = range.substr(8);
    if(range.startsWith("Payee")) range = "ExternalParties" + range.substr(5);

    widget.UI.Forms.ShowRangeLookupFromStandardRange(range, sender.Text(), { caption: "Lookup " + caption},
    function (newRange) {
      sender.Text(newRange);
      sender.Focus();
    });
  }
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "FORMCLOSE":
      // Closing Form
      tabWizard_Cancel();
      break;

    default:
      break;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>yUFQGePfpEyTBAlyv0kLiw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowPaymentMethods" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccounts" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccountManagers" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccountTypes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowBranches" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowClients" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowClientGroups" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowClientTypes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowDepartments" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowEntities" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowProductTypes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AutoCommit" type="Boolean">
            <BlankTip />
            <Caption>Auto Commit?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="HideValidRows" type="Boolean">
            <BlankTip />
            <Caption>Hide Valid Rows?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ProcessId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>50</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>