<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-19T02:11:53.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-11-28T20:28:52.9370000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-19T02:11:35.1930000</UpdatedUtcDate>
    <ScriptId>EBT</ScriptId>
    <Description>Export Bank Transactions</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_BankExportTransactions
Option Explicit On
Option Strict On

' #################################################################
' Export Bank Transactions
'
' Version: 1.04 (19/09/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  06/05/2022  ISS      J024138   Created
'    1.01  29/09/2022  ISS      J029737   Implemented widget.UI.BuildBackgroundProcessProgress
'    1.02  26/01/2023  ISS      J030308   Items Summary Page cache is now cleared after refreshing
'                      ISS      J030232   Improved "Service" list
'          16/03/2023  ISS      J030692   Spelling mistake &amp; defaulting Service ComboBox for existing Background Processes
'    1.03  30/01/2024  ISS      J032804   Add [SEQ#3] tag for Filename
'    1.04  19/09/2024  ISS      J034308   List of existing exports is now limited
' #################################################################

' Constants
Private Const FORM_KEY As String = "BankExportTransactions"

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

' Other
Private mAutoCommit As Boolean
Private mExistingExportBatchLimitDays As Integer
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")
    mExistingExportBatchLimitDays = .GetInteger("ExistingExportBatchLimitDays")
    mHideValidRows = .GetBoolean("HideValidRows")
    mProcessId = .GetString("ProcessId")
  End With

  ' Override Parameters
  If mExistingExportBatchLimitDays &lt; 1 Then
    mExistingExportBatchLimitDays = 30
  End If
  
  ' 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 "DownloadSummary":
      ' Download Export Summary
      Main = DownloadSummary(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 "GetExistingExports"
      ' Get Existing Exports
      Main = GetExistingExports(returnValue)
      
    Case "GetExportOptions"
      ' Get Export Options
      Main = GetExportOptions(parametersJson, 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 BankAccount As finBankAccount
  Dim BankAccountRO As finBankAccountRO
  Dim BankExportCreate As finBankExportCreate
  Dim dvBankInterface As DataView
  Dim dvFileExport As DataView
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim HasBankInterface As Boolean
  Dim HasBankInterfaceMethods As Boolean
  Dim HasFileExport As Boolean
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim ProcessStatusesBankExport As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Row As DataRow
  Dim StatusInformation As finHtmlWidgetUtilities.JsonProcessStatusInformation
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  BankAccount = finBL.CreateBankAccount()
  FormInitialisationInfo = New FormInitialisationInfo()

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

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

  ' Get finBankExportCreate Object
  If Success Then
    Success = CreateBankExportCreate(Nothing, BankExportCreate)
  End If

  ' File Export &amp; Bank Interface
  If Success Then
    HasBankInterfaceMethods = finBL.PaymentMethods.HasBankInterfaceMethods()

    If finBL.BankAccounts.GetDataViewForReadyToExportFileServices(dvFileExport) Then
      If HasBankInterfaceMethods Then
        Success = finBL.BankAccounts.GetDataViewForReadyToExportBankInterfaceServices(dvBankInterface)
      End If
    Else
      Success = False
    End If
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ProcessId = mProcessId
      .BankAccountId = BankExportCreate.BankAccountId
      .DefaultDateTo = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())

      ' Bank Exports
      Success = GetExistingExports(.BankExportsJson)

      ' Bank Accounts
      If Success Then
        For Each BankAccountRO In finBL.BankAccounts
          HasFileExport = False
          HasBankInterface = False

          ' File Export
          For Each Row In dvFileExport.Table.Rows
            If StrComp(BankAccountRO.BankAccountId, finBL.Database.GetFieldString(Row!BankAccountId), CompareMethod.Text) = 0 Then
              HasFileExport = True
              Exit For
            End If
          Next

          ' Bank Interface
          If HasBankInterfaceMethods Then
            For Each Row In dvBankInterface.Table.Rows
              If StrComp(BankAccountRO.BankAccountId, finBL.Database.GetFieldString(Row!BankAccountId), CompareMethod.Text) = 0 Then
                HasBankInterface = True
                Exit For
              End If
            Next
          End If

          ' Add
          If HasFileExport OrElse HasBankInterface Then
            If BankAccount.Load(BankAccountRO.BankAccountId) Then
              .BankAccounts.Add(New BankAccount(BankAccount, HasFileExport, HasBankInterface))
            Else
              Success = False
              Exit For
            End If
          End If
        Next
      End If

      ' 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"
      .ShowPools = mCombinedParameters.GetString("ShowPools") : If Len(.ShowPools) = 0 Then .ShowPools = "Advanced"

      ' Licence
      If Not finBL.Settings.AddOns.Branch Then .ShowBranches = "False"
      If Not finBL.Settings.AddOns.Pool Then .ShowPools = "False"

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

      ' General
      .PageGeneralHasAdvanced = (.ShowAccounts = "Advanced" OrElse .ShowAccountTypes = "Advanced" OrElse .ShowBranches = "Advanced" OrElse
                                 .ShowClients = "Advanced" OrElse .ShowClientGroups = "Advanced" OrElse .ShowClientTypes = "Advanced" OrElse
                                 .ShowPools = "Advanced")

      ' Permissions

      ' Configuration
      .AutoCommit = mAutoCommit
      .EmailWhenComplete = (finBL.CloudConnectFunctions.CloudConnectSettings.ProcessBackgroundEmailUserOnFinish AndAlso Len(finBL.CurrentUserInformation.Email) &lt;&gt; 0)
      .ExistingExportBatchLimitDays = mExistingExportBatchLimitDays
      .HasBankInterfaceMethods = HasBankInterfaceMethods
      .HideValidRows = mHideValidRows
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit

      Select Case finBL.CountryCode
        Case "NZ": .TerminologyBankSortCode = ""
        Case Else : .TerminologyBankSortCode = finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode)
      End Select
    End With

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

    ' Combine
    If Success Then
      For Each StatusInformation In ProcessStatusesBankExport
        ProcessStatuses.Add(StatusInformation)
      Next
      finBL.HtmlWidgetUtilities.SortJsonProcessStatusInformationByCreatedDate(ProcessStatuses, True)

      FormInitialisationInfo.CurrentProcesses = ProcessStatuses
    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 Existing Exports.
''' &lt;/summary&gt;
Private Function GetExistingExports(ByRef returnValue As String) As Boolean
  
  Dim BankExports As List(Of BankExport)
  Dim dv As DataView
  Dim Row As DataRow
  Dim Success As Boolean
  Dim ShowAllExisting As Boolean
  Dim sqlWhere As String
  
  ' Assume Success
  Success = True
  
  ' Initialise
  BankExports = New List(Of BankExport)
  
  ' Parameters
  With mCombinedParameters
    ShowAllExisting = .GetBoolean("ShowAllExisting")
  End With
  
  ' Limit to last x days
  If (Not ShowAllExisting) Then
    With finBL.Database.CreateSqlWhereBuilder()
      .AppendComparisonDate("BankExport.CreatedUtcDate", "&gt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTimePrecise().AddDays(-mExistingExportBatchLimitDays))
      sqlWhere = .SqlWhere
    End With
  End If
  
  ' Get Bank Exports
  If finBL.Utilities.CreateDataViewFromStandardRange(isefinStandardRange.BankExportBatches, sqlWhere, True, iseCollectionDataViewTarget.DbCombo, dv, "", "", Nothing) Then
    For Each Row In dv.Table.Rows
      BankExports.Add(New BankExport(Row))
    Next
    
    ' Sort
    BankExports.Sort(AddressOf GetExistingExports_SortComparer)
  Else 
    Success = False
  End If
  
  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(BankExports, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Existing Exports Sort Comparer.
''' &lt;/summary&gt;
Private Function GetExistingExports_SortComparer(x As BankExport,
                                                 y As BankExport) As Integer

  If x.CreatedUtcDate &lt; y.CreatedUtcDate Then
    Return 1
  ElseIf x.CreatedUtcDate &gt; y.CreatedUtcDate Then
    Return -1
  Else
    Return 0
  End If

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 BankTransactionPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    BankTransactionPk = .GetInteger("BankTransactionPk")
  End With

  ' Get Summary
  If Success Then
    returnValue = finBL.SummaryPageFunctions.BankTransactionSummary(False, False, BankTransactionPk, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
  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 BankExportCreate As finBankExportCreate
  Dim BankExportCreateItem As finBankExportCreateItem
  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 ExportSummaryTable As ISSummaryTable
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim ValueIncluded As Decimal
  Dim Warnings As ISCodeDescriptionList
  Dim WarningsSummaryTable As ISSummaryTable
  Dim WizardFinishParameters As WizardFinishParameters
  Dim ExportServiceDescription As String

  ' Assume Success
  Success = True

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

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

  ' Get finBankExportCreate
  If Success Then
    If CreateBankExportCreate(Nothing, BankExportCreate) Then
      Success = BankExportCreate.FromHtmlWidgetJsonString(WizardFinishParameters.RefreshData)
    Else
      Success = False
    End If
  End If

  ' Calculate Totals
  If Success Then
    For Each BankExportCreateItem In BankExportCreate.BankTransactions
      With BankExportCreateItem
        ' Exportable
        If .CanInclude Then
          ' Included
          If .Include Then
            ValueIncluded += (.Value * -1)

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

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

          ' Add to Errors List
          If Errors.ExistsDescription(.FailedMessage) Then
            Errors(Errors.IndexOfDescription(.FailedMessage)).Code = CStr(CInt(Errors(Errors.IndexOfDescription(.FailedMessage)).Code) + 1)
          Else
            Errors.Add(CStr(1), .FailedMessage)
          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:", BankExportCreate.BankTransactions.CountIncluded)
      .AddRowCaptionInteger("Excluded:", CountExcluded)
      .AddRowCaptionInteger("Cannot Include:", CountCannotInclude,,, iseSummaryTableRowClass.Negative)
      .AddRowCaptionInteger("Total:", BankExportCreate.BankTransactions.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 Bank Transactions.}}")
        Else
          .Rows.AddText("{{info|See below to review **" &amp; CountHasWarnings &amp; " warnings** for included Bank Transactions.}}")
        End If
      End If

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

  ' Export Summary
  If Success Then
    ExportSummaryTable.TableClass = iseSummaryTableClass.Information

    With ExportSummaryTable
      ' Columns
      With ExportSummaryTable.Columns
        .AddText(18)
        .AddText()
      End With

      .Rows.AddSectionHeading2("General")
      If WizardFinishParameters.OptionBankInterface Then
        .AddRowCaptionText("Export Type:", "Bank Interface")
      Else
        .AddRowCaptionText("Export Type:", "File")
      End If
      .AddRowCaptionCodeDescription("Bank Account:", BankExportCreate.BankAccountId, finBL.BankAccounts)
      If WizardFinishParameters.OptionBankInterface Then
        .AddRowCaptionText("Service:", BankExportCreate.BankInterfaceServiceId)
      Else
        If BankExportCreate.ExportService IsNot Nothing Then
          ExportServiceDescription = BankExportCreate.ExportService.Description
        End If
        .AddRowCaptionCodeDescription("Service:", BankExportCreate.ExportServiceId, ExportServiceDescription)
      End If
      .AddRowCaptionDate("Payments to:", BankExportCreate.DateTo)

      If WizardFinishParameters.OptionCreateFile Then
        If WizardFinishParameters.FileDownload Then
          ' finCC File Download
          .Rows.AddSectionHeading2("Download Information")
          .AddRowCaptionDate("Transfer Date:", finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.TransferDate))
          .AddRowCaptionText("File Name:", finBL.Runtime.FileUtilities.GetFileName(WizardFinishParameters.FileName))
        ElseIf WizardFinishParameters.FileLocation Then
          ' File Export
          .Rows.AddSectionHeading2("Export File Information")
          .AddRowCaptionDate("Transfer Date:", finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.TransferDate))
          .AddRowCaptionText("File Name:", WizardFinishParameters.FileName)
        End If
      End If
    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("100%")
    sb.ColumnBegin("50%", "350px")

    sb.BlockBegin("Bank Transaction Export Summary", "", isefinSummaryPageBlockHeadingStyle.Main)
    sb.SummaryTableAppend(SummaryTable)
    sb.BlockEnd()

    sb.ColumnEnd()

    If ExportSummaryTable.HasData Then
      sb.ColumnBegin("50%")

      sb.BlockBegin("Export Summary", "", isefinSummaryPageBlockHeadingStyle.Normal)
      sb.SummaryTableAppend(ExportSummaryTable)
      sb.BlockEnd()

      sb.ColumnEnd()
    End If

    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 Bank Transactions")
      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 finBankExport object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateBankExport(parameters As WizardFinishParameters,
                                  ByRef bankExport As finBankExport) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  bankExport = finBL.CreateBankExport()

  ' Update Parameters
  If Success AndAlso parameters IsNot Nothing Then
    With bankExport
      .BatchCode = parameters.BatchCode
      .BatchSequence = parameters.BatchSequence

      If parameters.FileDownload Then
        .FileName = finBL.Runtime.FileUtilities.GetFileName(parameters.FileName)
      Else
        .FileName = parameters.FileName
      End If

      .IncludeReversed = parameters.IncludeReversed
      .DateTransfer = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.TransferDate)

      ' Re-Export
      If Len(parameters.BankExportId) &lt;&gt; 0 Then
        .BankExportId = parameters.BankExportId
      End If
    End With
  End If

  Return Success

End Function

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

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  bankExportCreate = finBL.CreateBankExportCreate()

  ' Update Parameters
  If Success AndAlso parameters IsNot Nothing Then
    With bankExportCreate
      .BankAccountId = parameters.BankAccountId
      .BatchNotes = parameters.BatchNotes
      .DateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateTo)
      .DateTransfer = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.TransferDate)

      If parameters.OptionCreateFile Then
        Success = .ExportServiceSet(parameters.Service)
      ElseIf parameters.OptionBankInterface Then
        Success = .BankInterfaceServiceSet(parameters.Service)
      End If

      If Success Then
        .RangeAccounts = parameters.RangeAccounts
        .RangeAccountTypes = parameters.RangeAccountTypes
        .RangeBranches = parameters.RangeBranches
        .RangeClientGroups = parameters.RangeClientGroups
        .RangeClients = parameters.RangeClients
        .RangeClientsIncludeAllOwners = parameters.RangeClientsIncludeAllOwners
        .RangeClientTypes = parameters.RangeClientTypes
        .RangePools = parameters.RangePools
      End If
    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 BankExport As finBankExport
  Dim BankExportCreate As finBankExportCreate
  Dim ProcessId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Validate

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get finBankExportCreate Object
  If Success Then
    Success = CreateBankExportCreate(WizardFinishParameters, BankExportCreate)
  End If

  ' Bank Export only applicable at this stage if auto-committing
  If Success AndAlso mAutoCommit AndAlso Not WizardFinishParameters.FileHold AndAlso (WizardFinishParameters.OptionCreateFile OrElse WizardFinishParameters.OptionReExportFile) Then
    Success = CreateBankExport(WizardFinishParameters, BankExport)
  End If

  ' Queue Background Process
  If Success Then
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_BankExportCreate_Refresh(BankExportCreate, mAutoCommit, BankExport, 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;
'''  Download Export Summary.
''' &lt;/summary&gt;
Private Function DownloadSummary(ByRef returnValue As String) As Boolean

  Dim BankExportCreate As finBankExportCreate
  Dim BankExportId As String
  Dim FileDownloadInfo As finFileDownloadInfo
  Dim FileName As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Create Object
  If Success Then
    BankExportCreate = finBL.CreateBankExportCreate()
    Success = BankExportCreate.LoadExisting(BankExportId)
  End If

  ' Create Summary
  If Success Then
    FileName = finBL.Runtime.FileUtilities.GetTemporaryFileName("ExportBankTransactionsSummary", "pdf")
    Success = BankExportCreate.CreateBankExportCreateSummaryPdf(FileName, iseSummaryPageTarget.WebServices)
  End If

  ' Create Download
  If Success Then
    FileDownloadInfo = finBL.CreateFileDownloadInfo()
    With FileDownloadInfo
      If .LoadFile(FileName) Then
        returnValue = .ToXmlString()
      Else
        Success = False
      End If
    End With
  End If

  ' Delete Temporary file
  If Len(FileName) &lt;&gt; 0 Then
    finBL.Runtime.FileUtilities.DeleteFile(FileName)
  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 BankExport As finBankExport
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Queue Background Process
  If Success Then
    If mAutoCommit AndAlso Not WizardFinishParameters.OptionReExportFile Then
      ' Queue "Refresh" - Execute Commit will occur automatically
      Success = Me.Refresh(parametersJson, returnValue)
    Else
      ' Bank Export
      If Success AndAlso Not WizardFinishParameters.FileHold AndAlso (WizardFinishParameters.OptionCreateFile OrElse WizardFinishParameters.OptionReExportFile) Then
        Success = CreateBankExport(WizardFinishParameters, BankExport)
      End If

      ' Queue Background Process
      If Success Then
        If WizardFinishParameters.OptionReExportFile Then
          Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_BankExport(BankExport, WizardFinishParameters.ProcessId)
        Else
          Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_BankExportCreate_ExecuteCommit(WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData, finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.TransferDate), WizardFinishParameters.BatchNotes,BankExport)
        End If
      End If

      ' Finalise
      If Success Then
        Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(WizardFinishParameters.ProcessId), returnValue)
      End If
    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 BankExportId As String
  Dim DownloadSummary As Boolean
  Dim LastEventId As String
  Dim ProcessId As String
  Dim Status As isefinCloudConnectProcessStatus
  Dim Success As Boolean
  Dim Data As Object
  Dim BackgroundProcessJson As String

  ' Assume Success
  Success = True

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

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

  ' If downloading Summary, retrieve Bank Export Id to be used later
  If Success AndAlso DownloadSummary Then
    If finBL.HtmlWidgetUtilities.GetBackgroundProcessStatus(ProcessId, Status) Then
      Select Case Status
        Case isefinCloudConnectProcessStatus.Complete, isefinCloudConnectProcessStatus.CompleteWithErrors, isefinCloudConnectProcessStatus.CompleteWithWarnings
          Success = finBL.HtmlWidgetUtilities.GetBankExportIdFromProcessId(ProcessId, BankExportId)

        Case Else
          ' Process not complete - do not attempt to get Bank Export Id
      End Select
    Else
      Success = False
    End If
  End If

  ' Populate Data
  If Success Then
    Data = New With {
      .BackgroundProcessJson = BackgroundProcessJson,
      .BankExportId = BankExportId
    }
  End If

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

  ' Get current and recent Background Processes that for this User
  If finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_BankExportCreate(True, ProcessStatuses) Then
    Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_BankExport(True, ProcessStatusesBankExport)
  Else
    Success = False
  End If

  ' Combine
  If Success Then
    For Each StatusInformation In ProcessStatusesBankExport
      ProcessStatuses.Add(StatusInformation)
    Next
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Export Options.
''' &lt;/summary&gt;
Private Function GetExportOptions(parametersJson As String,
                                  ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim BankExportCreate As finBankExportCreate
  Dim BankAccountExportService As finBankAccountExportService
  Dim BankExportTypeProperties As ISBankExportTypeProperties
  Dim BankExport As finBankExport
  Dim ShowReversed As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  BankExport = finBL.CreateBankExport()

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

  ' Create Object
  If Success Then
    Success = CreateBankExportCreate(WizardFinishParameters, BankExportCreate)
  End If

  ' Validate
  If Success Then
    If BankExportCreate.BankAccountPk = 0 Then
      Success = False
      finBL.Error.ErrorBegin("A Bank Account must be specified.")
    ElseIf Not finBL.BankAccounts.ExistsPk(BankExportCreate.BankAccountPk) Then
      Success = False
      finBL.Error.ErrorBegin("Invalid Bank Account.")
    ElseIf BankExportCreate.ExportServicePk = 0 AndAlso WizardFinishParameters.OptionCreateFile Then
      Success = False
      finBL.Error.ErrorBegin("A Bank Account Export Service must be specified.")
    ElseIf Len(BankExportCreate.BankInterfaceServiceId) = 0 AndAlso WizardFinishParameters.OptionBankInterface Then
      Success = False
      finBL.Error.ErrorBegin("A Bank Interface Service must be specified.")
    ElseIf Not BankExportCreate.BankAccount.ExportServices.ExistsPk(BankExportCreate.ExportServicePk) AndAlso (WizardFinishParameters.OptionCreateFile OrElse WizardFinishParameters.OptionBankInterface) Then
      Success = False
      finBL.Error.ErrorBegin("Invalid Bank Account Export Service.")
    End If
  End If

  ' Get Export Service and Properties
  If Success Then
    ' Get Export Service
    If Len(WizardFinishParameters.BankExportId) = 0 Then
      ' New File Export
      BankAccountExportService = BankExportCreate.BankAccount.ExportServices.ItemByExportServicePk(BankExportCreate.ExportServicePk)
    Else
      ' Re-Export / Re-Print
      Success = finBL.BankAccountFunctions.GetBankAccountExportServiceFromBankExportId(WizardFinishParameters.BankExportId, Nothing, BankAccountExportService)
    End If

    ' Get Properties from Export Service
    If Success Then
      BankExportTypeProperties = BankExport.GetExportTypeProperties(BankAccountExportService.BankServiceType)
    End If
  End If

  ' Reversed
  If Success Then
    If Not WizardFinishParameters.OptionCreateFile AndAlso Len(WizardFinishParameters.BankExportId) &lt;&gt; 0 Then
      If BankExportCreate.LoadExisting(WizardFinishParameters.BankExportId) Then
        ShowReversed = BankExportCreate.AnyReversed()
      Else
        Success = False
      End If
    End If
  End If

  ' Build Object
  If Success Then
    Data = New With {
      .BatchSequenceCaption = BankExportTypeProperties.BatchSequenceCaption,
      .BatchSequenceLabelText = BankExportTypeProperties.BatchSequenceLabelText,
      .BatchCodeCaption = BankExportTypeProperties.BatchCodeCaption,
      .BatchCodeLength = BankExportTypeProperties.BatchCodeLength,
      .BatchCodeDefaultList = BankExportTypeProperties.BatchCodeDefaultList,
      .BatchCodeInformationListId = BankAccountExportService.BatchCodeInformationListId,
      .DefaultFilename = BankAccountExportService.FileName,
      .DefaultFileExtension = BankExportTypeProperties.DefaultFileExtension,
      .DefaultTransferDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(BankExportCreate.DateTo),
      .FileNameAllowChange = BankAccountExportService.FileNameAllowChange,
      .ShowBatchNotes = WizardFinishParameters.OptionCreateFile,
      .ShowPrintBankExportTransactions = WizardFinishParameters.OptionCreateFile,
      .ShowReversed = ShowReversed,
      .SupportsBatchSequence = BankExportTypeProperties.SupportsBatchSequence,
      .SupportsBatchCode = BankExportTypeProperties.SupportsBatchCode
    }
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, 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 BankExportCreate As finBankExportCreate
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

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

  ' Validate Page
  If Success Then
    Select Case PageId
      Case "General"
        ' General
        ' Create Bank Export Create. NOTE: Setting the Service will also validate
        If Success Then
          Success = CreateBankExportCreate(WizardFinishParameters, BankExportCreate)
        End If

      Case "ExportOptions"
        ' Export Options
        If WizardFinishParameters.OptionCreateFile Then
          If finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.TransferDate) &lt; finBL.TimeZoneFunctions.GetCurrentDatabaseDate() Then
            FailedControlId = "dateTransfer"
            FailedMessage = "Transfer date must be on or after today."
          End If
        End If
    End Select
  End If

  ' 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 DefaultDateTo As Date

  ' Bank Exports
  Public BankExportsJson As String

  ' Bank Accounts
  Public BankAccounts As New List(Of BankAccount)

  ' Advanced
  Public PageGeneralHasAdvanced As Boolean
  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 ShowPools As String
  Public ShowRangesHeading As String

  ' Permissions

  ' Configuration
  Public [ReadOnly] As Boolean
  Public AutoCommit As Boolean
  Public EmailWhenComplete As Boolean
  Public ExistingExportBatchLimitDays As Integer
  Public HasBankInterfaceMethods As Boolean
  Public HideValidRows As Boolean
  Public PromptOnCommit As Boolean
  Public TerminologyBankSortCode As String

End Class



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

  Public BankAccountId As String
  Public BankInterfaces As New List(Of String)
  Public Description As String
  Public HasFileExport As Boolean
  Public HasBankInterfaceExport As Boolean
  Public ExportServices As New List(Of ExportService)

  Public Sub New(bankAccount As finBankAccount,
                 hasFileExport As Boolean,
                 hasBankInterfaceExport As Boolean)

    Dim Row As DataRow
    Dim ServiceId As String

    With bankAccount
      Me.BankAccountId = .BankAccountId
      Me.Description = .Description
    End With
    Me.HasFileExport = hasFileExport
    Me.HasBankInterfaceExport = hasBankInterfaceExport

    ' Bank Interfaces
    If Me.HasBankInterfaceExport Then
      ' Split / Zepto AU
      If finBLShared.BankAccounts(bankAccount.BankAccountId).CostCentreResolved(iseBankInterfaceService.Split) IsNot Nothing Then
        Me.BankInterfaces.Add("Split")
      End If
      
      ' Zepto NZ
      If finBLShared.BankAccounts(bankAccount.BankAccountId).CostCentreResolved(iseBankInterfaceService.ZeptoNZ) IsNot Nothing Then
        Me.BankInterfaces.Add("ZeptoNZ")
      End If
    End If

    ' File Exports
    If Me.HasFileExport Then
      ' Get Filtered DataView
      For Each Row In bankAccount.ExportServices.ToDataView(True, False).Table.Rows
        ServiceId = finBLShared.Database.GetFieldString(Row!ServiceId)

        If bankAccount.ExportServices.Exists(ServiceId) Then
          Me.ExportServices.Add(New ExportService(bankAccount.ExportServices.ItemByServiceId(ServiceId)))
        End If
      Next

      ' Sort Alphabetically
      Me.ExportServices.Sort(AddressOf ExportServices_SortComparer)
    End If

  End Sub

  Private Function ExportServices_SortComparer(x As ExportService,
                                               y As ExportService) As Integer

    Return StrComp(x.ServiceId, y.ServiceId)

  End Function

End Class



''' &lt;summary&gt;
'''  Bank Export.
''' &lt;/summary&gt;
Public Class BankExport

  Public BankAccountDescription As String
  Public BankAccountId As String
  Public BankExportId As String
  Public BatchTotal As Decimal
  Public Creator As String
  Public CreatedUtcDate As Date
  Public Notes As String
  Public Pk As Integer
  Public TransferDate As Date

  Public Sub New(row As DataRow)

    With finBLShared.Database
      Me.BankAccountDescription = .GetFieldString(row!BankAccountDescription)
      Me.BankAccountId = .GetFieldString(row!BankAccountId)
      Me.BankExportId = .GetFieldString(row!BankExportId)
      Me.BatchTotal = .GetFieldDecimal(row!Total)
      Me.Creator = .GetFieldString(row!CreatedUser)
      Me.CreatedUtcDate = .GetFieldUtcDate(row!CreatedUtcDate)
      Me.Notes = .GetFieldString(row!Notes)
      Me.Pk = .GetFieldInteger(row!Pk)
      Me.TransferDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.GetFieldDate(row!Date))
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Export Service.
''' &lt;/summary&gt;
Public Class ExportService

  Public ServiceId As String
  Public Description As String

  Public Sub New(bankAccountExportService As finBankAccountExportService)

    With bankAccountExportService
      Me.ServiceId = .ServiceId
      Me.Description = .Description
    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 DateTo As Date
  Public OptionBankInterface As Boolean
  Public OptionCreateFile As Boolean
  Public OptionReExportFile As Boolean
  Public OptionDownload As Boolean
  Public Service As String

  ' Export
  Public BatchCode As String
  Public BatchNotes As String
  Public BatchSequence As Integer
  Public FileDownload As Boolean
  Public FileHold As Boolean
  Public FileLocation As Boolean
  Public FileName As String
  Public IncludeReversed As Boolean
  Public PrintBankExportTransactions As Boolean
  Public TransferDate As Date?

  ' Re-Export
  Public BankExportId As String

  ' Ranges
  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 RangePools 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 "BankExportTransactions".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
/* Total Summary */
.value-summary {
  display:flex;
  flex-direction:row;

  .refresh-warning {
    padding-right:16px;
    color:red;
    font-weight:bold;
  }

  div {
    font-size:11px;

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

/* Small device portrait */
@media screen and (max-width:640px) {
  .value-summary {
    flex-direction:column;
    font-size:12px;
  }
}
&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 Bank Transaction Exports you have processed."&gt;Recent Bank Transaction Exports&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Create new Bank Export or select an existing Bank Export to Re-Export or Download."&gt;General&lt;/li&gt;
        &lt;li tabId="Items" tooltipText="Select the Bank Transactions to export."&gt;Bank Transactions&lt;/li&gt;
        &lt;li tabId="ExportOptions" tooltipText="Enter Export Details."&gt;Export Details&lt;/li&gt;
        &lt;li tabId="Confirm" tooltipText="Confirm the Bank Transactions to begin exporting."&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;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&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="lblOptionCreate"&gt;Create a new Bank Export&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOptionCreateFile" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOptionCreateBankInterface" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblOptionReExport"&gt;Re-Export or Reprint an existing Bank Export File&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOptionReExportFile" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOptionDownload" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblBankAccount"&gt;Select the Bank Account&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="lblService"&gt;Select the Service&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboService"&gt;Service:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboService" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblProcesses"&gt;Process Bank Transactions due on or before&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="dateDateTo"&gt;Payments to:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateDateTo" /&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="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="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="Pools"&gt;
              &lt;th&gt;&lt;label for="txtRangePools"&gt;Pools:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtRangePools" lookupCaption="Pools" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblBankExportFiles"&gt;Bank Export Files&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/div&gt;

        &lt;!-- Bank Exports --&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1280px; margin-left:8px"&gt;
          &lt;div id="gridBankExports" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&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="gridItems"&gt;&lt;/div&gt;
          &lt;div id="divItemsSummary" 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="wbItemsSummary" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Export Options --&gt;
    &lt;div id="pageExportOptions"&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="lblTransferDate"&gt;Enter the date you want funds to be transferred on&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateTransfer"&gt;Transfer:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateTransfer" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="divDateDueWarning" class="is-info-text info warning"&gt;Changing the transfer date from that originally used is not recommended.&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblFileName"&gt;Select the desired location and name of the file to export&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkFileDownload" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkFileLocation" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkFileHold" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFileName"&gt;File Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFileName" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="divFileName" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBatchSequence"&gt;Enter the Batch Number to appear in the export file&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBatchSequence"&gt;Sequence:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBatchSequence" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBatchCode"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBatchCode" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPrintBankExportTransactions"&gt;Print Bank Transactions Export Summary&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkPrintBankExportTransactions" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="divPrintBankExportTransactions" class="is-info-text info small"&gt;A copy of the Export Summary will be emailed upon completion of this process regardless of the setting above.&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblExportBatch"&gt;Enter any Notes to assign to the Bank Export Batch&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="txtBatchNotes" /&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblExportReversed"&gt;Include Reversed Transactions in Re-export?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeReversed" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&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_BankExports;
var mRecord_CurrentProcesses;

var mBankExportCreate;

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

  //   General
  lblOptionCreate: null,
  chkOptionCreateFile: null,
  chkOptionCreateBankInterface: null,

  lblOptionReExport: null,
  chkOptionReExportFile: null,
  chkOptionDownload: null,

  lblBankAccount: null,
  cboBankAccount: null,

  lblService: null,
  cboService: null,

  lblProcesses: null,
  dateDateTo: null,

  lblRanges: null,
  txtRangeAccounts: null,
  txtRangeAccountTypes: null,
  txtRangeBranches: null,
  txtRangeClients: null,
  chkRangeClientsIncludeAllOwners: null,
  txtRangeClientGroups: null,
  txtRangeClientTypes: null,
  txtRangePools: null,

  lblBankExportFiles: null,
  gridBankExports: null,

  //   Items
  gridItems: null,
  divItemsSummary: null,
  wbItemsSummary: null,

  //   Export Options
  lblTransferDate: null,
  dateTransfer: null,
  divDateDueWarning: null,

  lblFileName: null,
  chkFileDownload: null,
  chkFileLocation: null,
  chkFileHold: null,
  txtFileName: null,
  divFileName: null,

  lblBatchSequence: null,
  numBatchSequence: null,
  cboBatchCode: null,

  lblPrintBankExportTransactions: null,
  chkPrintBankExportTransactions: null,
  divPrintBankExportTransactions: null,

  lblExportBatch: null,
  txtBatchNotes: null,

  lblExportReversed: null,
  chkIncludeReversed: 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 mComplete = false;
var mFromRecent = false;
var mLastRefreshParametersJson = "";
var mLastProcessSummaryJson = "";
var mMonitoringExisting = false;
var mProcessId;
var mRequiresRefresh = false;
var mServiceInformation;
var mShowAllExisting = false;

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

  // Controls
  //   General
  C.lblOptionCreate = widget.UI.Label("lblOptionCreate", {});
  C.chkOptionCreateFile = widget.UI.CheckBox("chkOptionCreateFile", {
    caption: "Create a new Export File?",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: chkOption_Change,
  });
  C.chkOptionCreateBankInterface = widget.UI.CheckBox("chkOptionCreateBankInterface", {
    caption: "Send Bank Transactions via a Bank Interface (Web API) Service?",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: chkOption_Change,
  });

  C.lblOptionReExport = widget.UI.Label("lblOptionReExport", {});
  C.chkOptionReExportFile = widget.UI.CheckBox("chkOptionReExportFile", {
    caption: "Re-Export an existing File?",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: chkOption_Change,
  });
  C.chkOptionDownload = widget.UI.CheckBox("chkOptionDownload", {
    caption: "Download an existing Bank Transactions Export Summary?",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: chkOption_Change,
  });

  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.lblService = widget.UI.Label("lblService", {});
  C.cboService = widget.UI.DBCombo("cboService", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboService_Change,
  });

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

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

  C.lblBankExportFiles = widget.UI.Label("lblBankExportFiles", {});

  //   Items
  C.divItemsSummary = $("#divItemsSummary");
  C.wbItemsSummary = widget.UI.PreviewPane("wbItemsSummary", {});

  //   Export Options
  C.lblTransferDate = widget.UI.Label("lblTransferDate", {});
  C.dateTransfer = widget.UI.DateBox("dateTransfer", {
    allowBlank: false,
  });
  C.divDateDueWarning = $("#divDateDueWarning");

  C.lblFileName = widget.UI.Label("lblFileName", {});
  C.chkFileDownload = widget.UI.CheckBox("chkFileDownload", {
    caption: "finPOWER Connect Cloud Download",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: FileLocation_Change,
  });
  C.chkFileLocation = widget.UI.CheckBox("chkFileLocation", {
    caption: "File Location",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: FileLocation_Change,
  });
  C.chkFileHold = widget.UI.CheckBox("chkFileHold", {
    caption: "Do not generate a file",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: FileLocation_Change,
  });
  C.txtFileName = widget.UI.TextBox("txtFileName", {
    allowBlank: false,
    maxLength: 255,

    onButtonClick: txtFileName_ButtonClick,
  });
  C.divFileName = $("#divFileName");

  C.lblBatchSequence = widget.UI.Label("lblBatchSequence", {});
  C.numBatchSequence = widget.UI.NumberBox("numBatchSequence", {
    decimals: 0,
  });
  C.cboBatchCode = widget.UI.InformationListComboBox("cboBatchCode", {});

  C.lblPrintBankExportTransactions = widget.UI.Label("lblPrintBankExportTransactions", {});
  C.chkPrintBankExportTransactions = widget.UI.CheckBox("chkPrintBankExportTransactions", {
    caption: "Download Bank Transactions Export Summary?",
    captionWrap: true,
  });
  C.divPrintBankExportTransactions = $("#divPrintBankExportTransactions");

  C.lblExportBatch = widget.UI.Label("lblExportBatch", {});
  C.txtBatchNotes = widget.UI.TextBox("txtBatchNotes", {
    multiLine: true,
    rows: 7,
  });

  C.lblExportReversed = widget.UI.Label("lblExportReversed", {});
  C.chkIncludeReversed = widget.UI.CheckBox("chkIncludeReversed", {
    caption: "Include Reversed Transactions?",
    captionWrap: true,
  });

  //   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.gridBankExports = widget.UI.Grid("gridBankExports", {
    allowCellSelect: false,
    allowMultiRowSelect: false,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridBankExports_Action,
    onInitialiseRow: gridBankExports_InitialiseRow,
    onRowDrilldown: gridBankExports_RowDrilldown,
  });

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

    onAction: gridItems_Action,
    onAfterRowActivate: gridItems_AfterRowActivate,
    onBeforeCellUpdate: gridItems_BeforeCellUpdate,
    onInitialiseRow: gridItems_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
  C.chkOptionCreateFile.Value(true);
  C.chkOptionCreateBankInterface.Value(false);
  C.chkOptionReExportFile.Value(false);
  C.chkOptionDownload.Value(false);

  // 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_BankExports = null;
  mRecord_CurrentProcesses = null;
  mAccounts = null;
  mBankExportCreate = null;
  mServiceInformation = 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_BankExports = JSON.parse(mRecord.BankExportsJson);
      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 Bank Transaction exports 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 Bank Transaction Export.", { heading: "Bank Transactions still Exporting", 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.dateDateTo.Value(mRecord.DefaultDateTo);
  }

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

  // Update Controls
  pageGeneral_Refresh();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

  // Lists

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

    // Controls
    C.chkOptionCreateBankInterface.VisibleRow(mRecord.HasBankInterfaceMethods);

    // File Name Tags List
    var o = [];
    o.push({caption: "BankExportId", value: "[BankExportId]"});
    o.push({caption: "BankExportPk", value: "[BankExportPk]"});
    o.push({caption: "Sequence", value: "[SEQ]"});
    o.push({caption: "Sequence #3", value: "[SEQ#3]"});
    o.push({caption: "AppFolder", value: "[AppFolder]"});
    o.push({caption: "DbFolder", value: "[DbFolder]"});
    o.push({caption: "DocumentFolder", value: "[DocumentFolder]"});
    o.push({caption: "ExportFolder", value: "[ExportFolder]"});
    o.push({caption: "TemplateFolder", value: "[TemplateFolder]"});
    o.push({caption: "YMD", value: "[YMD]"});
    o.push({caption: "YYMMDD", value: "[YYMMDD]"});
    o.push({caption: "YMDHM", value: "[YMDHM]"});
    o.push({caption: "YMDHMS", value: "[YMDHMS]"});
    o.push({caption: "HM", value: "[HM]"});
    o.push({caption: "HMS", value: "[HMS]"});
    C.txtFileName.TagsListDefine(o);

    // File Name Buttons
    var buttons = [];
    buttons.push({ id: "AppendExtension", tooltipText: "Append default File Extension for this Service", icon: "Folder_Count" });
    C.txtFileName.ButtonsDefine(buttons);
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess() {
  var service = "";

  // Reset
  C.chkOptionCreateBankInterface.Value(false);
  C.chkOptionCreateFile.Value(false);
  C.chkOptionDownload.Value(false);
  C.chkOptionReExportFile.Value(false);

  // Controls
  if (mBankExportCreate) {
    C.cboBankAccount.Text(mBankExportCreate.BankAccountId);
    if (mBankExportCreate.IsBankInterfaceExport) {
      C.chkOptionCreateBankInterface.Value(true);
      service = mBankExportCreate.BankInterfaceServiceId;
    }
    else {
      C.chkOptionCreateFile.Value(true);      
      service = mBankExportCreate.ExportServiceId;
    }
    C.dateDateTo.Value(mBankExportCreate.DateTo);

    // Ranges
    C.txtRangeAccounts.Text(mBankExportCreate.RangeAccounts);
    C.txtRangeAccountTypes.Text(mBankExportCreate.RangeAccountTypes);
    C.txtRangeBranches.Text(mBankExportCreate.RangeBranches);
    C.txtRangeClientGroups.Text(mBankExportCreate.RangeClientGroups);
    C.txtRangeClients.Text(mBankExportCreate.RangeClients);
    C.chkRangeClientsIncludeAllOwners.Value(mBankExportCreate.RangeClientsIncludeAllOwners);
    C.txtRangeClientTypes.Text(mBankExportCreate.RangeClientTypes);
    C.txtRangePools.Text(mBankExportCreate.RangePools);

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

      if (mBankExportCreate.RangeAccounts &amp;&amp; mBankExportCreate.RangeAccounts.length != 0 &amp;&amp; mRecord.ShowAccounts.toUpperCase() != "TRUE") toggle = true;
      if (mBankExportCreate.RangeAccountTypes &amp;&amp; mBankExportCreate.RangeAccountTypes.length != 0 &amp;&amp; mRecord.ShowAccountTypes.toUpperCase() != "TRUE") toggle = true;
      if (mBankExportCreate.RangeBranches &amp;&amp; mBankExportCreate.RangeBranches.length != 0 &amp;&amp; mRecord.ShowBranches.toUpperCase() != "TRUE") toggle = true;
      if (mBankExportCreate.RangeClientGroups &amp;&amp; mBankExportCreate.RangeClientGroups.length != 0 &amp;&amp; mRecord.ShowClientGroups.toUpperCase() != "TRUE") toggle = true;
      if (mBankExportCreate.RangeClients &amp;&amp; mBankExportCreate.RangeClients.length != 0 &amp;&amp; mRecord.ShowClients.toUpperCase() != "TRUE") toggle = true;
      if (mBankExportCreate.RangeClientsIncludeAllOwners &amp;&amp; mBankExportCreate.RangeClientsIncludeAllOwners &amp;&amp; mRecord.ShowClients.toUpperCase() != "TRUE") toggle = true;
      if (mBankExportCreate.RangeClientTypes &amp;&amp; mBankExportCreate.RangeClientTypes.length != 0 &amp;&amp; mRecord.ShowClientTypes.toUpperCase() != "TRUE") toggle = true;
      if (mBankExportCreate.RangePools &amp;&amp; mBankExportCreate.RangePools.length != 0 &amp;&amp; mRecord.ShowPools.toUpperCase() != "TRUE") toggle = true;

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

  // Refresh Page
  pageGeneral_Refresh();
  
  // Update Controls - must happen after pageGeneral_Refresh as this will try and reset them
  if (service) C.cboService.Text(service);
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "Items":
        if (!mRecord.AutoCommit) {
          RefreshExport();
        }
        break;

      case "ExportOptions":
        pageExportOptions_Refresh();
        break;

      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
      mBankExportCreate = 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 = {
    optionBankInterface: C.chkOptionCreateBankInterface.Value(),
    optionCreateFile: C.chkOptionCreateFile.Value(),
    optionReExportFile: C.chkOptionReExportFile.Value(),
    optionDownload: C.chkOptionDownload.Value(),
  }

  // File or Bank Export
  if (C.chkOptionCreateFile.Value() || C.chkOptionCreateBankInterface.Value()) {
    params.BankAccountId = C.cboBankAccount.Text();
    params.ProcessId = mProcessId;
    params.DateTo = C.dateDateTo.Value();
    params.Service = C.cboService.Text();

    params.RangeAccounts = C.txtRangeAccounts.Text();
    params.RangeAccountTypes = C.txtRangeAccountTypes.Text();
    params.RangeBranches = C.txtRangeBranches.Text();
    params.RangeClientGroups = C.txtRangeClientGroups.Text();
    params.RangeClients = C.txtRangeClients.Text();
    params.RangeClientsIncludeAllOwners = C.chkRangeClientsIncludeAllOwners.Value();
    params.RangeClientTypes = C.txtRangeClientTypes.Text();
    params.RangePools = C.txtRangePools.Text();
  }

  // Items from Grid
  if (C.chkOptionReExportFile.Value() || C.chkOptionDownload.Value()) {
    if (C.gridBankExports.ActiveDataRowListIndex() != -1) {
      var item = mRecord_BankExports[C.gridBankExports.ActiveDataRowListIndex()];

      params.BankAccountId = item.BankAccountId;
      params.BankExportId = item.BankExportId;
      params.TransferDate = item.TransferDate;
    }
  }

  // File Export Options
  if (C.chkOptionCreateFile.Value() || C.chkOptionReExportFile.Value()) {
    params.TransferDate = C.dateTransfer.Value(); // This may override the re-export grid above - this is desired
    params.FileDownload = C.chkFileDownload.Value();
    params.FileLocation = C.chkFileLocation.Value();
    params.FileHold = C.chkFileHold.Value();
    if (params.FileDownload || params.FileLocation) params.FileName = C.txtFileName.Text();

    if (mServiceInformation) {
      if (mServiceInformation.SupportsBatchSequence) params.BatchSequence = C.numBatchSequence.Value();
      if (mServiceInformation.SupportsBatchCode) params.BatchCode = C.cboBatchCode.Text();
      if (mServiceInformation.ShowPrintBankExportTransactions) params.PrintBankExportTransactions = C.chkPrintBankExportTransactions.Value();
      if (mServiceInformation.ShowBatchNotes) params.BatchNotes = C.txtBatchNotes.Text();
      if (mServiceInformation.ShowReversed) params.IncludeReversed = C.chkIncludeReversed.Value();
    }
  }

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

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

      // Build Message
      if (C.chkOptionReExportFile.Value()) {
        var bankExportId = mRecord_BankExports[C.gridBankExports.ActiveDataRowListIndex()].BankExportId;
        message += "Are you sure you want to re-export Batch '" + bankExportId + "'?";
      }
      else {
        message += "Are you sure you want to Export Bank Transactions?";
      }

      // 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 Bank Transaction Exporting, 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_Download(exportId) {
  var BankExportId;

  // Determine Bank Export Id
  if (exportId) {
    BankExportId = exportId
  }
  else if(C.gridBankExports.ActiveDataRowListIndex != -1) {
    BankExportId = mRecord_BankExports[C.gridBankExports.ActiveDataRowListIndex()].BankExportId;
  }

  // Download
  if (BankExportId) {
    // Params
    var params = {
      bankExportId: BankExportId,
    }

    // Download
    widget.DownloadFile("DownloadSummary", params);
  }
}

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;

  // Params
  var params = {
    processId: mProcessId,
    lastEventId: mLastEventId,
    downloadSummary: (C.chkOptionCreateFile.Value() &amp;&amp; C.chkPrintBankExportTransactions.Value()),
  }

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

      // Update Status
      mRecord_BackgroundProcessStatus = JSON.parse(data.BackgroundProcessJson);

      // 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("Bank Transaction Export was sucessfully cancelled.");
          break;

        case "InProgressRefreshComplete":
          // Update Items
          mBankExportCreate = 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("Bank Transaction Export Refresh is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          else {
            var message = "Bank Transaction Export is " + widget.SplitWordsAtCapitals(Status, true, true) + ".";
            if (data.BankExportId) {
              message += "\n\nClick OK to download the Export Summary.";
            }

            widget.UI.MsgBoxInfo(message, {},
              function() {
                Form_ExecuteAction_GetBackgroundProcessStatus_Post(data.BankExportId);
              }
            );
          }
          break;

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

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Bank Transaction Export failed to complete.");
          break;

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

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

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

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

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

function Form_ExecuteAction_GetBackgroundProcessStatus_Post(bankExportId) {
  if (bankExportId) {
    // Download Summary
    var params = {
      bankExportId: bankExportId,
    }

    // Download
    widget.DownloadFile("DownloadSummary", params);
  }
}

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

  // Block UI
  widget.UI.Block("Refreshing Recent Bank Transaction Exports, 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);
    }
  );
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Hide all Controls
  C.lblBankAccount.VisibleRow(false);
  C.cboBankAccount.VisibleRow(false);
  C.lblService.VisibleRow(false);
  C.cboService.VisibleRow(false);
  C.lblProcesses.VisibleRow(false);
  C.dateDateTo.VisibleRow(false);
  C.lblBankExportFiles.VisibleRow(false);
  C.gridBankExports.Visible(false);

  C.lblRanges.VisibleRow(false);
  for(var k in C) {
    if (k.startsWith("txtRange") || k.startsWith("chkRange")) {
      C[k].VisibleRow(false);
    }
  }

  // Show Controls
  if (C.chkOptionCreateFile.Value() || C.chkOptionCreateBankInterface.Value()) {
    // -----------
    // Create File
    // -----------
    C.lblBankAccount.VisibleRow(true);
    C.cboBankAccount.VisibleRow(true);
    C.lblService.VisibleRow(true);
    C.cboService.VisibleRow(true);
    C.lblProcesses.VisibleRow(true);
    C.dateDateTo.VisibleRow(true);

    C.lblRanges.VisibleRow(true);
    for(var k in C) {
      if (k.startsWith("txtRange") || k.startsWith("chkRange")) {
        C[k].VisibleRow(true);
      }
    }

    // Create filtered collection
    var collection = [];
    for (var i = 0; i &lt; mRecord.BankAccounts.length; i++) {
      var item = mRecord.BankAccounts[i];

      if (C.chkOptionCreateFile.Value()) {
        if (item.HasFileExport) collection.push(item);
      }
      else {
        if (item.HasBankInterfaceExport) collection.push(item);
      }
    }

    // Update Dropdowns
    C.cboBankAccount.RefreshFromCollection(collection, "BankAccountId", "Description");

    // Clear value if it is no longer in the list
    if (C.cboBankAccount.Text()) {
      var found = false;
      for (var i = 0; i &lt; collection.length; i++) {
        if (collection[i].BankAccountId == C.cboBankAccount.Text()) found = true;
      }
      if (!found) {
        C.cboBankAccount.Text("");
        C.cboService.Text("");
      }
    }
    
    // Update Controls
    cboBankAccount_Change();
  }
  else if(C.chkOptionReExportFile.Value() || C.chkOptionDownload.Value()) {
    // ---------------------
    // Re-Export or Re-Print
    // ---------------------
    C.lblBankExportFiles.VisibleRow(true);
    C.gridBankExports.Visible(true);

    // Update Grid
    gridBankExports_Refresh();
  }

  // Update Buttons
  tabWizard_UpdateButtons();
}

// ===========
// pageConfirm
// ===========
function pageConfirm_Refresh() {
  // Params
  var params = CreateFinishParameters(true);

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

// =================
// pageExportOptions
// =================
function pageExportOptions_Refresh() {
  // If re-exporting a file, clear service information to force previous export information to be retrieved (as the selected item in the grid may have changed)
  if (C.chkOptionReExportFile.Value()) mServiceInformation = null;

  // Get Export Options
  if (!mServiceInformation) {
    // Hide form
    frmMain.Visible(false);

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

    // Params
    var params = CreateFinishParameters(false);

    // Get Options
    widget.GetString("GetExportOptions", params, pageExportOptions_Refresh_Done, function(errorMessage) {
      // Show form
      frmMain.Visible(true);

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

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

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

function pageExportOptions_Refresh_Done(data) {
  // Parse
  if (data) mServiceInformation = JSON.parse(data);

  // Update Controls
  C.dateTransfer.Value(mServiceInformation.DefaultTransferDate);
  if (C.chkOptionCreateFile.Value()) {
    C.divDateDueWarning.hide();
  }
  else {
    C.divDateDueWarning.show();
  }

  C.chkFileDownload.Value(true);
  C.chkFileLocation.Value(false);
  C.chkFileHold.Value(false);
  C.chkFileHold.VisibleRow(C.chkOptionCreateFile.Value());
  C.txtFileName.Text(mServiceInformation.DefaultFilename);

  C.lblBatchSequence.VisibleRow(mServiceInformation.SupportsBatchSequence || mServiceInformation.SupportsBatchCode);
  if (mServiceInformation.SupportsBatchSequence) {
    C.numBatchSequence.Caption(mServiceInformation.BatchSequenceCaption);
    C.numBatchSequence.VisibleRow(true);
  }
  else {
    C.numBatchSequence.VisibleRow(false);
  }
  if (mServiceInformation.SupportsBatchCode) {
    C.cboBatchCode.Caption(mServiceInformation.BatchCodeCaption);
    C.cboBatchCode.BlankList(mServiceInformation.BatchCodeDefaultList);
    if (mServiceInformation.BatchCodeLength != 0) {
      C.cboBatchCode.OverrideMaxLength(true);
      C.cboBatchCode.MaxLength(mServiceInformation.BatchCodeLength);
    }
    C.cboBatchCode.SetComboFromInformationList(mServiceInformation.BatchCodeInformationListId, true, null, true);
    C.cboBatchCode.VisibleRow(true);
  }
  else {
    C.cboBatchCode.VisibleRow(false);
  }

  C.lblPrintBankExportTransactions.VisibleRow(mServiceInformation.ShowPrintBankExportTransactions);
  C.chkPrintBankExportTransactions.VisibleRow(mServiceInformation.ShowPrintBankExportTransactions);
  if (mServiceInformation.ShowPrintBankExportTransactions &amp;&amp; mRecord.EmailWhenComplete) {
    C.divPrintBankExportTransactions.show();
  }
  else {
    C.divPrintBankExportTransactions.hide();
  }

  C.lblExportBatch.VisibleRow(mServiceInformation.ShowBatchNotes);
  C.txtBatchNotes.VisibleRow(mServiceInformation.ShowBatchNotes);

  C.lblExportReversed.VisibleRow(mServiceInformation.ShowReversed);
  C.chkIncludeReversed.VisibleRow(mServiceInformation.ShowReversed);

  // Update Controls
  FileLocation_Change();

  // Show form
  frmMain.Visible(true);

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

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

// ===============
// pageItems
// ===============
function pageItems_Refresh() {
  // Refresh Grid
  if (mBankExportCreate) {
    gridItems_Refresh();
  }
}

// ====================
// gridCurrentProcesses
// ====================
function gridCurrentProcesses_Refresh() {
  // Add Columns
  if (C.gridCurrentProcesses.ColumnCount() == 0) {
    C.gridCurrentProcesses.AddColumnDrilldown();
    C.gridCurrentProcesses.AddColumnString("StatusText", { caption: "Status" });
    C.gridCurrentProcesses.AddColumnString("ProcessType", { caption: "Process Type" });
    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, false, 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);
}

// ===============
// gridBankExports
// ===============
function gridBankExports_Refresh() {
  var showNotes = false;

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

    // Warnings
    if (item.Notes) showNotes = true;
  }

  // Add Columns
  C.gridBankExports.ClearColumns();
  C.gridBankExports.AddColumnString("BankExportId", { caption: "Bank Export Id", sortable: true, });
  C.gridBankExports.AddColumnDate("TransferDate", { caption: "Funds Transfer Date", sortable: true, });
  C.gridBankExports.AddColumnString("BankAccountId", { caption: "Bank Account", sortable: true, });
  C.gridBankExports.AddColumnString("BankAccountDescription", { caption: "Bank Account Description", sortable: true, });
  C.gridBankExports.AddColumnCurrency("BatchTotal", { caption: "Batch Total", sortable: true, });
  C.gridBankExports.AddColumnString("Creator", { caption: "Creator", sortable: true, });
  C.gridBankExports.AddColumnString("Notes", { caption: "Notes", visible: showNotes, sortable: true, });

  // Actions
  C.gridBankExports.Actions().Define([{ actionId: "ShowAll", caption: "Show all? (If not toggled, only Exports created in the last " + mRecord.ExistingExportBatchLimitDays + " days will be shown)", checked: mShowAllExisting }]);

  // Refresh
  // NOTE: Retain active row when selecting different export options
  C.gridBankExports.VirtualDataRefresh(mRecord_BankExports, true);

  // Select first row
  C.gridBankExports.ActivateFirstDataRow(true);
}

function gridBankExports_InitialiseRow(e) {
  var item = mRecord_BankExports[e.row.listIndex];

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

function gridBankExports_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "SHOWALL":
      mShowAllExisting = !mShowAllExisting;
      
      // Block UI
      widget.UI.Block("Initialising, please wait...");
      
      // Params
      var params = {
        showAllExisting: mShowAllExisting
      }
      
      // Get Data
      widget.GetString("GetExistingExports", params, function(data) {  
        // Parse
        if (data) mRecord_BankExports = JSON.parse(data);
        
        // Refresh Grid
        gridBankExports_Refresh();
        
        // Unblock UI
        widget.UI.Unblock();
      },      
      function(errorMessage) {
        // Unblock UI
        widget.UI.Unblock();
      
        // Error
        widget.UI.MsgBoxAlert(errorMessage);
      });
      break;
  }
}

function gridBankExports_RowDrilldown(e) {
  if (C.chkOptionDownload.Value()) {
    Form_ExecuteAction_Download();
  }
  else if (C.chkOptionReExportFile.Value()) {
    tabWizard_Move(1);
  }
}

// =========
// gridItems
// =========
function gridItems_Refresh() {
  var showWarnings = false;

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

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

  // Add Columns
  C.gridItems.ClearColumns();
  C.gridItems.AddColumnIcon("Icon", { caption: "", visible: showWarnings, sortable: true, });
  C.gridItems.AddColumnBoolean("Include", { caption: "Include", allowEdit: true, sortable: true, });
  C.gridItems.AddColumnString("Source", { caption: "Source", sortable: true, });
  C.gridItems.AddColumnDate("Date", { caption: "Date", sortable: true, });
  C.gridItems.AddColumnCode("AccountId", { caption: "Account", sortable: true, });
  C.gridItems.AddColumnString("Name", { caption: "Name", sortable: true, });
  C.gridItems.AddColumnString("PaymentMethodId", { caption: "Pay Method", sortable: true, });
  C.gridItems.AddColumnString("AccountSortCode", { caption: mRecord.TerminologyBankSortCode, visible: mRecord.TerminologyBankSortCode, sortable: true, });
  C.gridItems.AddColumnString("AccountNumber", { caption: "Account No", sortable: true, });
  C.gridItems.AddColumnString("AccountName", { caption: "Account Name", sortable: true, });
  C.gridItems.AddColumnCurrency("Value", { caption: "Value", sortable: true, });
  C.gridItems.AddColumnString("FailedMessage", { caption: "Invalid Message", visible: showWarnings, sortable: true, });

  // Actions
  C.gridItems.Actions().Define([{ actionId: "Refresh", tooltipText: "Refresh Bank Transactions", icon: "Refresh"},
                                {},
                                { 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" },
                               ]);

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mBankExportCreate.BankTransactions.GetCacheKey = function (index) {
    var item = mBankExportCreate.BankTransactions[index];
    return item.BankTransactionPk;
  };
  mBankExportCreate.BankTransactions.GetPreviewFetchParameters = function (index) {
    var item = mBankExportCreate.BankTransactions[index];
    var o = {};
    o.BankTransactionPk = item.BankTransactionPk;
    o.ProcessId = mProcessId;
    return o;
  };

  // Refresh
  C.gridItems.VirtualDataRefresh(mBankExportCreate.BankTransactions);

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

  // Update Totals
  divItemsSummary_Refresh();
}

function gridItems_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "REFRESH":
      // Clear Cache
      mLastRefreshParametersJson = "";

      // Refresh
      RefreshExport(true);
      break;

    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridItems.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mBankExportCreate.BankTransactions.length; i++) {
        if(mBankExportCreate.BankTransactions[i].CanInclude) {
          if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
            indexes.push(i);
          }
          else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
            indexes.push(i);
          }
        }
      }
      break;

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

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

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

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

        if(item.CanInclude) {
          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.gridItems.GetSelectedRowIndexes(true, true);

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

  // Set Indexes
  if(indexes) {
    C.gridItems.SetSelectedRowIndexes(indexes, true);
  }

  // Update Totals
  divItemsSummary_Refresh();
}

function gridItems_AfterRowActivate(e) {
  // Preview
  wbItemsSummary_Preview();
}

function gridItems_BeforeCellUpdate(e) {
  var item = mBankExportCreate.BankTransactions[e.row.listIndex];

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

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

  // Update Totals
  divItemsSummary_Refresh();
}

function gridItems_InitialiseRow(e) {
  var item = mBankExportCreate.BankTransactions[e.row.listIndex];

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

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

  // Invalid rows cannot be edited
  e.row.readOnly = !item.CanInclude;
  e.row.cells.Include.readOnly = !item.CanInclude;

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

  // Invert Value
  e.row.cells.Value.value = (item.Value * -1);

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

  // 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) {
    // Still Running
    widget.UI.MsgBoxConfirm("Exporting Bank Transactions 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; mBankExportCreate &amp;&amp; mRequiresRefresh) {
    // Items in the collection have changed and therefore the Process must be cancelled
    widget.UI.MsgBoxConfirm("Items have changed and therefore this Process cannot be saved and will be cancelled.\n\nContinue?", { captionOk: "Yes", captionCancel: "No" },
      function() {
        CancelRefreshCompleteBackgroundProcess(mProcessId, false, tabWizard_Cancel_Post);
      }
    );
  }
  else if (mProcessId &amp;&amp; (tabWizard.SelectedTabId() == "Items" || tabWizard.SelectedTabId() == "Confirm" || mBankExportCreate)) {
    // Prompt User to decide whether to keep or cancel the Process
    var list = [];
    var message = "This will close the wizard but retain the list which can be reviewed later by re-opening this wizard.";
    if (C.chkOptionCreateFile.Value() || C.chkOptionReExportFile.Value()) {
      message += "\n\nNOTE: Settings on the 'Export Details' page will not be saved.";
    }

    list.push({ key: "CLOSE", caption: "Suspend and Close", icon: "Window_Close", details: message });
    list.push({ key: "CANCEL", caption: "Close and Cancel", icon: "Trash", details: "This will close the wizard and cancel this process. The list of Bank Transactions to export will not be retained." });

    var options = {
      closeOnEscape: true,
      title: "Close Bank Transaction Export",
      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, false, 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 &amp;&amp; (C.chkOptionCreateFile.Value() || C.chkOptionCreateBankInterface.Value());
          break;

        case "ExportOptions":
          found = (C.chkOptionCreateFile.Value() || C.chkOptionReExportFile.Value());
          break;

        case "Confirm":
          found = (!mRecord.AutoCommit &amp;&amp; mBankExportCreate);
          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 "ExportOptions":
      //C.txtFileName.WidthResizeFromParent();
      break;

    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() == "ExportOptions") {
    // Auto Commit File Exports
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
  }
  else if (mRecord.AutoCommit &amp;&amp; C.chkOptionCreateBankInterface.Value() &amp;&amp; tabWizard.SelectedTabId() == "General") {
    // Auto Commit Bank Interface
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
  }
  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 &amp;&amp; (C.chkOptionCreateFile.Value() || C.chkOptionCreateBankInterface.Value())) 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);
  }

  // Download only
  if (C.chkOptionDownload.Value()) {
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
    cmdFinish.text("Download");
  }

  // Re-Export
  if (C.chkOptionReExportFile.Value() &amp;&amp; tabWizard.SelectedTabId() == "ExportOptions") {
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
  }
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (C.chkOptionCreateBankInterface.Value() || C.chkOptionCreateFile.Value()) {
          // Has server-side validation
        }
        else {
          // No validation
          validCallback();
          return;
        }
        break;

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

        if (!found) {
          Ok = false;
          widget.UI.MsgBoxAlert("At least one item must be included to continue.");
        }
        else if (mRequiresRefresh) {
          var message = "&lt;p&gt;Details may differ from what is displayed in the grid.&lt;/p&gt;";
          message += "&lt;p&gt;Continue?&lt;/p&gt;";
          message += "&lt;p&gt;NOTE: To update the list, select 'No' and click the Refresh button.&lt;/p&gt;";
          widget.UI.MsgBoxConfirm(message, { captionOk: "Yes", captionCancel: "No", messageIsHtml: true }, validCallback);
          return;
        }
        break;

      case "ExportOptions":
        if (C.chkFileLocation.Value()) {
          if (C.txtFileName.Text().indexOf("/") == -1 &amp;&amp; C.txtFileName.Text().indexOf("\\") == -1) {
            Ok = false;
            widget.UI.MsgBoxAlert("A full file name including folder must be specified.");
          }
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
      case "ExportOptions":
        params = CreateFinishParameters(false);
        break;
    }

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

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

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

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

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

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

          // Allow callbacks to continue
          return;
        };
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

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

  // General
  AdvancedInitialiseSection("RangesHeading", mRecord.ShowRangesHeading);
  AdvancedInitialiseSection("Accounts", mRecord.ShowAccounts);
  AdvancedInitialiseSection("AccountTypes", mRecord.ShowAccountTypes);
  AdvancedInitialiseSection("Branches", mRecord.ShowBranches);
  AdvancedInitialiseSection("Clients", mRecord.ShowClients);
  AdvancedInitialiseSection("ClientGroups", mRecord.ShowClientGroups);
  AdvancedInitialiseSection("ClientTypes", mRecord.ShowClientTypes);
  AdvancedInitialiseSection("Pools", mRecord.ShowPools);
}

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 RefreshExport(fromGridAction) {
  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 Bank Transactions to Export.&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 (mBankExportCreate &amp;&amp; mProcessId) {
      message += "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Bank Transactions have already been refreshed. Continuing will cancel the existing process, and begin a new one.&lt;/p&gt;"
    }

    // Confirm
    var options = {
      heading: "Refresh Bank Transactions for Export",
      messageIsHtml: true,
      icon: "Table|Refresh"
    }
    widget.UI.MsgBoxConfirm(message, options,
      function () {
        if (mBankExportCreate &amp;&amp; mProcessId) {
          CancelRefreshCompleteBackgroundProcess(mProcessId, fromGridAction, RefreshExport_Post, function() {
            // Move back a page
            tabWizard_Move(-1);

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

      function() {
        // Move back a page
        if (!fromGridAction) {
          tabWizard_Move(-1);
        }

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

function RefreshExport_Post() {
  // Running new process
  mMonitoringExisting = false;
  mBankExportCreate = null;
  mRequiresRefresh = false;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Bank Transaction Export 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();

      // Clear Summary Page Cache
      C.wbItemsSummary.CacheClear();

      // 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, noPrompt, callback, cancelCallback) {
  if (noPrompt) {
    // Cancel immediately
    CancelRefreshCompleteBackgroundProcess_Execute(processId, callback);
  }
  else {
    // Prompt
    widget.UI.MsgBoxConfirm("Are you sure you want to cancel this Background Process?", {},
      function() {
        CancelRefreshCompleteBackgroundProcess_Execute(processId, callback);
      },

      cancelCallback
    );
  };
}

function CancelRefreshCompleteBackgroundProcess_Execute(processId, callback) {
  // 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);
  });
}

// ===============
// divItemsSummary
// ===============
function divItemsSummary_Refresh() {
  var html = "";
  var value = 0;

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

    if (item.Include &amp;&amp; item.CanInclude) {
      value += item.Value;
    }
  }

  html += "&lt;div class='value-summary'&gt;";

  // Refresh Warning
  if (mRequiresRefresh) {
    html += "&lt;div class='refresh-warning'&gt;One or more items has changed - please Refresh the list&lt;/div&gt;";
  }

  // Message
  html += "&lt;div&gt;Selected: &lt;b&gt;" + widget.UI.HtmlEncode(widget.FormatCurrency(value * -1, true)) + "&lt;/b&gt;&lt;/div&gt;";
  html += "&lt;/div&gt;";
  C.divItemsSummary.html(html);

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

// ==============================
// A Bank Transaction has changed
// ==============================
function BankTransactionChanged(bankTransactionPk) {
  // Only proceed if the changed Bank Transaction is in the current list
  var found = false;
  if (mBankExportCreate &amp;&amp; mBankExportCreate.BankTransactions.length != 0) {
    for (var i = 0; i &lt; mBankExportCreate.BankTransactions.length; i++) {
      var item = mBankExportCreate.BankTransactions[i];

      if (item.BankTransactionPk == bankTransactionPk) {
        found = true;
        break;
      }
    }
  }

  // Proceed with refresh warning if found
  if (found) {
    // Requires Refresh
    mRequiresRefresh = true;

    // Update Summary
    divItemsSummary_Refresh();
  }
}

// ===================================
// 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) {
    // Reset
    mServiceInformation = null;

    // Set Information from Process
    mProcessId = item.ProcessId;

    // Status-dependant
    switch (item.Status) {
      case "InProgressRefreshComplete":
        // Update Items
        mBankExportCreate = 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;
    }
  }
}

// ==============
// wbItemsSummary
// ==============
function wbItemsSummary_Preview() {
  C.wbItemsSummary.PreviewFromGridCollection(C.gridItems, mBankExportCreate.BankTransactions, "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();
    });
  }
}

// ===========
// txtFileName
// ===========
function txtFileName_ButtonClick(sender, e) {
  if (e.id == "AppendExtension") {
    C.txtFileName.Text(C.txtFileName.Text() + "." + mServiceInformation.DefaultFileExtension);
  }
}

// ====================
// File Location Change
// ====================
function FileLocation_Change(sender, e) {
  if (sender &amp;&amp; e) {
    C.chkFileDownload.Value(sender == C.chkFileDownload);
    C.chkFileLocation.Value(sender == C.chkFileLocation);
    C.chkFileHold.Value(sender == C.chkFileHold);
  }

  // Reset Controls
  C.txtFileName.VisibleRow(true);

  // Update Controls and Set Message
  var message = "";
  if (C.chkFileDownload.Value()) {
    message = "Only a File Name (without folder information) is required. If a folder has been specified, it will be ignored.";
  }
  else if(C.chkFileLocation.Value()) {
    message = "A full File Name (including folder) is required and must be available on the server.";
  }
  else if(C.chkFileHold.Value()) {
    C.txtFileName.VisibleRow(false);
    message = "The Batch will be created but not exported.";
  }

  // Override the ability to update the file name
  if (mServiceInformation &amp;&amp; !mServiceInformation.FileNameAllowChange) {
    C.txtFileName.VisibleRow(false);

    if (!C.chkFileHold.Value()) {
      message += "&lt;/br&gt;&lt;/br&gt;Changing the File Name for this Export Service is not allowed.";
    }
  }

  // Default file name button enabled status should match the text box
  C.txtFileName.Buttons().Visible(!C.txtFileName.ReadOnly());

  // Show message
  if (message) {
    C.divFileName.html(message);
    C.divFileName.show();
  }
  else {
    C.divFileName.hide();
  }
}

// =========
// chkOption
// =========
function chkOption_Change(sender, e) {
  C.chkOptionCreateFile.Value(sender == C.chkOptionCreateFile);
  C.chkOptionCreateBankInterface.Value(sender == C.chkOptionCreateBankInterface);
  C.chkOptionReExportFile.Value(sender == C.chkOptionReExportFile);
  C.chkOptionDownload.Value(sender == C.chkOptionDownload);

  // Reset
  mServiceInformation = null;

  // Refresh Page
  pageGeneral_Refresh();
}

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

  // Get Bank Account
  var bankAccount = mRecord.BankAccounts.GetItem(C.cboBankAccount.Text());

  // Update Service dropdown
  if (bankAccount) {
    // Clear existing value
    C.cboService.Text("");

    // Update with new collection
    if (bankAccount.HasFileExport &amp;&amp; C.chkOptionCreateFile.Value()) {
      C.cboService.RefreshFromCollection(bankAccount.ExportServices, "ServiceId", "Description");
    }
    else if(bankAccount.HasBankInterfaceExport &amp;&amp; C.chkOptionCreateBankInterface.Value()) {
      C.cboService.ListFromCsvString(bankAccount.BankInterfaces);
    }

    // Set item if there is only one
    if (bankAccount.ExportServices.length == 1) {
      C.cboService.Text(bankAccount.ExportServices[0].ServiceId);
    }
  }
  else {
    C.cboService.Text("");
    C.cboService.ListFromCsvString("");
  }
}

// ==========
// cboService
// ==========
function cboService_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Reset loaded Service
  mServiceInformation = null;
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "BANKTRANSACTIONS.REFRESH":
      // A Bank Transaction may have changed
      if (data) data = JSON.parse(data);

      // A Bank Transaction has changed
      if (data &amp;&amp; data.bankTransactionPk != 0) {
        BankTransactionChanged(data.bankTransactionPk);
      }
      break;

    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="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="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>Advanced</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="ShowPools" 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>
          <Parameter name="ExistingExportBatchLimitDays" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>