<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-28T03:53:46.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-03-03T20:28:11.4470000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-28T03:53:25.5970000</UpdatedUtcDate>
    <ScriptId>IMPBANKTRANS</ScriptId>
    <Description>Import Bank Transactions</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_BankImport
Option Explicit On
Option Strict On

' #################################################################
' Import Bank Transactions wizard
'
' Version: 2.02 (28/08/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  28/04/2020  ISS                Created
'    2.00  15/11/2022  ISS      J028882   Re-written to use Background Processes
'    2.01  25/06/2024  ISS      J033793   'Service' dropdown now defaults if there is only a single item in the list
'    2.02  28/08/2024  ISS      J034170   'ShowAutoCommit' and 'AutoCommit' Parameters now default to False
' #################################################################

' Constants
Private Const FORM_KEY As String = "BankImport"

' Common Parameters
Private mBankAccountId As String
Private mServiceId As String
Private mShowAutoCommit As Boolean
Private mAutoCommit As Boolean

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

Public Function Main(eventId As String, parametersJson As String, startUpParametersJson As String, hostingContext As isefinHtmlWidgetHostingContext, requestInfo As finScriptRequestInfo, ByRef returnValue As String) As Boolean

  ' Assume Success
  Main = True

    ' Get Parameters
  mParameters = finBL.CreateKeyValueList()
  mParameters.FromSimpleJsonString(parametersJson)
  mStartupParameters = finBL.CreateKeyValueList()
  mStartupParameters.FromSimpleJsonString(startUpParametersJson)

  ' Get Combined Parameters (Startup Parameters updated with event Parameters)
  mCombinedParameters = mStartupParameters.Clone()
  mCombinedParameters.UpdateFromKeyValueList(mParameters, True)

  ' Get Common Parameters
  With mCombinedParameters
    mBankAccountId = .GetString("BankAccountId")
    mServiceId = .GetString("ServiceId")
    mShowAutoCommit = .GetBoolean("ShowAutoCommit")
    mAutoCommit = .GetBoolean("AutoCommit")
  End With

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return initial HTML content (excluding html and body tags)
      returnValue = ScriptInfo.TemplateText

    Case "CancelBackgroundProcess"
      ' Cancel a Process
      Main = CancelBackgroundProcess(returnValue)

    Case "CommitBatch"
      ' Commit Batch
      Main = CommitBatch(returnValue)

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

    Case "GetAutoBatchId"
      ' Get Auto-Generated Batch Id
      Main = GetAutoBatchId(returnValue)

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

    Case "GetBankAccountServices"
      ' Get Import Services for a Bank Account
      Main = GetBankAccountServices(returnValue)

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

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

    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;
'''  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 finBankImport object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateBankImport(parameters As WizardFinishParameters,
                                  ByRef bankImport As finBankImport,
                                  ByRef bankAccount As finBankAccount,
                                  ByRef bankAccountImportService As finBankAccountImportService) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  bankImport = finBL.CreateBankImport()

  ' Update
  If Success Then
    If parameters IsNot Nothing Then
      ' Create Bank Account
      bankAccount = finBL.CreateBankAccount()
      Success = bankAccount.Load(parameters.BankAccountId)

      ' Get Import Service
      If Success AndAlso Len(parameters.ServiceId) &lt;&gt; 0 Then
        bankAccountImportService = bankAccount.ImportServices.ItemByServiceId(parameters.ServiceId)
        If bankAccountImportService Is Nothing Then
          Success = False
          finBL.Error.ErrorBegin("Invalid Import Service.")
        End If
      End If

      ' Update Bank Import
      If Success Then
        With BankImport
          ' Refresh
          If .RefreshFromBankAccountService(parameters.BankAccountId, parameters.ServiceId) Then
            If bankAccountImportService.BatchIdAllowEntry OrElse Not finBL.TransactionTypes(bankAccountImportService.TransactionTypeId).HasAutoSequencedBatchId Then
              .BatchId = parameters.BatchId
              .BatchNotes = parameters.BatchNotes

              .AutoCommitBatch = parameters.AutoCommit
            End If
          Else
            Success = False
          End If
        End With
      End If
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Import Bank Transactions.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim BankAccount As finBankAccount
  Dim BankAccountImportService As finBankAccountImportService
  Dim BankImport As finBankImport
  Dim BankImportTypeProperties As ISBankImportTypeProperties
  Dim Data As Object
  Dim obj As Object
  Dim ProcessId As String
  Dim Success As Boolean
  Dim TempFileName As String
  Dim TempFileNameExtension As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Bank Import object
  If Success Then
    Success = CreateBankImport(WizardFinishParameters, BankImport, BankAccount, BankAccountImportService)
  End If

  ' Get Import Service Properties
  If Success Then
    BankImportTypeProperties = BankImport.GetImportTypeProperties(BankAccountImportService.BankServiceType)
  End If

  ' Validate
  If Success Then
    If BankImportTypeProperties.BankServiceMethod = iseBankServiceMethod.File AndAlso requestInfo.Files.Count = 0 Then
      Success = False
      finBL.Error.ErrorBegin("No file was selected to import.")
    End If
  End If

  ' Save Temp File
  If Success AndAlso BankImportTypeProperties.BankServiceMethod = iseBankServiceMethod.File Then
    TempFileName = requestInfo.Files(0).FileName
    
    ' Preference is to save temp file to Export Data Folder. This is to avoid issues with Windows Temporary Folders for Users / ISS when running within finC
    If Len(finBL.Settings.ExportDataFolder) = 0 Then
      TempFileNameExtension = finBL.Runtime.FileUtilities.GetFileExtension(TempFileName)
      TempFileName = Replace(TempFileName, "." &amp; TempFileNameExtension, "")
      TempFileName = finBL.Runtime.FileUtilities.GetTemporaryFileName(TempFileName, TempFileNameExtension)
    ElseIf Right(finBL.Settings.ExportDataFolder, 1) = System.IO.Path.DirectorySeparatorChar Then
      TempFileName = finBL.Settings.ExportDataFolder &amp; TempFileName
    Else 
      TempFileName = finBL.Settings.ExportDataFolder &amp; System.IO.Path.DirectorySeparatorChar &amp; TempFileName
    End If

    ' Ensure file is unique
    TempFileName = finBL.Runtime.FileUtilities.GetFileNameUnique(TempFileName)
    
    ' Write File
    If finBL.Runtime.FileUtilities.WriteFileFromByteArray(TempFileName, requestInfo.Files(0).FileData) Then
      BankImport.FileName = TempFileName
    Else
      Success = False
    End If
  End If

  ' Commit Bank Import
  If Success Then
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_BankImport(BankImport, ProcessId)
  End If

  ' Process Id
  If Success Then
    Data = New With {
      .ProcessId = ProcessId
    }
  End If

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

  Return Success

End Function

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

  Dim BatchBank As finBatchBank
  Dim BatchBankTransaction As finBatchBankTransaction
  Dim BatchId As String
  Dim Success As Boolean
  Dim TransactionCount As Integer
  Dim TransactionCountCommitted As Integer
  Dim TransactionCountFailed As Integer

  ' Assume Success
  Success = True

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

  ' Validate

  ' Load Batch
  If Success Then
    BatchBank = finBL.CreateBatchBank()
    If BatchBank.Load(batchId) Then
      TransactionCount = BatchBank.Transactions.Count
    Else
      Success = False
    End If
  End If

  ' Commit Batch
  If Success Then
    If BatchBank.ExecuteCommit(True) Then
      ' Count Committed
      For Each BatchBankTransaction In BatchBank.Transactions
        With BatchBankTransaction
          If .IsCommitted Then
            TransactionCountCommitted += 1
          Else
            TransactionCountFailed += 1
          End If
        End With
      Next
    Else
      Success = False
    End If
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(batchId, TransactionCount, TransactionCountCommitted, TransactionCountFailed), returnValue)
  End If

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

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

  If Success Then
    ' Initialise
    BankImport = finBL.CreateBankImport()

    ' Form Initialisation Info
    If Success Then
      FormInitialisationInfo = New FormInitialisationInfo()
      With FormInitialisationInfo
        ' Record
        If Len(mBankAccountId) = 0 Then
          .BankAccountId = BankImport.BankAccountId
          .ServiceId = BankImport.ServiceId
        Else
          .BankAccountId = mBankAccountId
          .ServiceId = mServiceId
        End If

        ' General
        .AutoCommit = mAutoCommit

        ' Configuration
        .BankAccountsSqlWhere = finBL.BankAccounts.GetDataViewFilter(False, False, True, True, False, False, True, True)
        .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
        .ReadOnly = finBL.Database.IsReadOnly
        .ShowAutoCommit = mShowAutoCommit
      End With

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

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

  Return Success

End Function

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

  Dim BankAccount As finBankAccount
  Dim BankAccountImportService As finBankAccountImportService
  Dim BankImport As finBankImport
  Dim BankImportTypeProperties As ISBankImportTypeProperties
  Dim ConfirmList As New List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim obj As Object
  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

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

  ' Validate
  If Success Then
    Select Case PageId
      Case "General"
        ' Create Bank Import object
        Success = CreateBankImport(WizardFinishParameters, BankImport, BankAccount, BankAccountImportService)

        ' Get Import Service Options
        If Success Then
          BankImportTypeProperties = BankImport.GetImportTypeProperties(BankAccountImportService.BankServiceType)
          Data = New With {
            .BankServiceMethod = BankImportTypeProperties.BankServiceMethod,
            .ShowBatchId = BankAccountImportService.BatchIdAllowEntry OrElse Not finBL.TransactionTypes(BankAccountImportService.TransactionTypeId).HasAutoSequencedBatchId,
            .AllowAutoSequenceBatchId = finBL.TransactionTypes(BankAccountImportService.TransactionTypeId).HasAutoSequencedBatchId
          }
        End If
    End Select
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Auto-Generated Batch Id.
''' &lt;/summary&gt;
Public Function GetAutoBatchId(ByRef returnValue As String) As Boolean

  Dim BankAccount As finBankAccount
  Dim BankAccountImportService As finBankAccountImportService
  Dim BankAccountId As String
  Dim ServiceId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate

  ' Generate Batch Id
  If Success Then
    BankAccount = finBL.CreateBankAccount()

    If BankAccount.Load(BankAccountId) Then
      BankAccountImportService = BankAccount.ImportServices.ItemByServiceId(ServiceId)
      If BankAccountImportService Is Nothing Then
        Success = False
        finBL.Error.ErrorBegin("Invalid Import Service.")
      Else
        returnValue = finBL.BatchFunctions.GetNextBatchIdFromTransactionType(BankAccountImportService.TransactionTypeId)
      End If

    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Background Process Status.
''' &lt;/summary&gt;
Private Function GetBackgroundProcessStatus(ByRef returnValue As String) As Boolean

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

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Bank Account Import Services.
''' &lt;/summary&gt;
Public Function GetBankAccountServices(ByRef returnValue As String) As Boolean

  Dim BankAccountServices As ISCodeDescriptionList
  Dim BankAccount As finBankAccount
  Dim BankAccountId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate

  ' Get Import Services
  If Success Then
    BankAccount = finBL.CreateBankAccount()

    If BankAccount.Load(BankAccountId) Then
      BankAccountServices = BankAccount.ImportServices.ToCodeDescriptionList()
    Else
      Success = False
    End If
  End If

  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(BankAccountServices.ToJsonObject(), 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 Success As Boolean

  ' Assume Success
  Success = True

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

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ProcessStatuses, 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)

  ' Record
  Public BankAccountId As String
  Public ServiceId As String

  Public AutoCommit As Boolean

  ' Configuration
  Public BankAccountsSqlWhere As String
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean
  Public ShowAutoCommit As Boolean

End Class



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

  Public BatchId As String

  Public TransactionCount As Integer
  Public TransactionCountCommitted As Integer
  Public TransactionCountFailed As Integer

  Public Sub New(batchId As String)

    Me.BatchId = batchId

  End Sub

  Public Sub New(batchId As String,
                 transactionCount As Integer,
                 transactionCountCommitted As Integer,
                 transactionCountFailed As Integer)

    With Me
      .BatchId = batchId
      .TransactionCount = transactionCount
      .TransactionCountCommitted = transactionCountCommitted
      .TransactionCountFailed = transactionCountFailed
    End With

  End Sub

End Class



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

  Public BankAccountId As String
  Public ServiceId As String

  Public BatchId As String
  Public BatchNotes As String

  Public AutoCommit As Boolean

End Class



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

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

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

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

  End Sub

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

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

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent Bank Transaction Imports you have run."&gt;Recent Bank Transaction Imports&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Select the Bank Account and Service to use for this import."&gt;General&lt;/li&gt;
        &lt;li tabId="Options" tooltipText="Specify import options."&gt;Options&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Current Processes --&gt;
    &lt;div id="pageCurrentProcesses"&gt;
      &lt;div id="gridCurrentProcesses"&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBankAccount"&gt;Select the Bank Account and Service&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&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;/table&gt;
    &lt;/div&gt;


    &lt;!-- Options --&gt;
    &lt;div id="pageOptions"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:6em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tbody id="tbOptionsFile"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblFile"&gt;Select a file to import&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;label for="fileFile"&gt;After importing, consider moving this file to a separate folder.&lt;/label&gt;
              &lt;input id="fileFile" type="file" accept="*/*" max-files="1"/&gt;
            &lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="tbBankBatch"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblBankBatch"&gt;Enter details to assign to the new Bank Batch&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtBatchId"&gt;Batch ID:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtBatchId" /&gt; &lt;button id="cmdBatchId" class="is-button small" icon="Refresh"&gt;Generate Batch ID&lt;/button&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtBatchNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtBatchNotes" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="tbAutoCommit"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAutoCommit"&gt;Commit the new Bank Batch&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkAutoCommit" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&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="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;&amp;lt; Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next &amp;gt;&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Finish&lt;/button&gt;  &lt;/footer&gt;
&lt;/div&gt;

&lt;script&gt;
// Record
var mRecord;
var mRecord_ServiceImportOptions;
var mRecord_BackgroundProcessStatus;
var mRecord_CurrentProcesses;

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

  //   General
  lblBankAccount: null,
  cboBankAccount: null,
  cboService: null,

  //   Options
  tbOptionsFile: null,

  tbBankBatch: null,
  lblBankBatch: null,
  txtBatchId: null,
  cmdBatchId: null,
  txtBatchNotes: null,

  tbAutoCommit: null,
  lblAutoCommit: null,
  chkAutoCommit: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;

// Other
var mComplete = false;
var mComplete_Information;
var mFromRecent = false;
var mMonitoringExisting = false;
var mProcessId;

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

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

  //   Options
  C.tbOptionsFile = $("#tbOptionsFile");

  C.tbBankBatch = $("#tbBankBatch");
  C.lblBankBatch = widget.UI.Label("lblBankBatch", {});
  C.txtBatchId = widget.UI.TextBox("txtBatchId", {
    allowBlank: false,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.cmdBatchId = $("#cmdBatchId");
  C.cmdBatchId.click(cmdBatchId_Click);
  C.txtBatchNotes = widget.UI.TextBox("txtBatchNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });

  C.tbAutoCommit = $("#tbAutoCommit");
  C.lblAutoCommit = widget.UI.Label("lblAutoCommit", {});
  C.chkAutoCommit = widget.UI.CheckBox("chkAutoCommit", {
    caption: "Automatically commit imported Bank Batch?",
  });

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

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

    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

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

  // Reset Form
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_ServiceImportOptions = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mComplete_Information = null;

  // Hide content
  frmMain.Visible(false);

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

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

      // Load Fields
      Fields_Load();

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

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

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

    // General
    C.cboBankAccount.Text(mRecord.BankAccountId);
    C.cboService.Text(mRecord.ServiceId);

    // Options
    C.chkAutoCommit.Value(mRecord.AutoCommit);
  }

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

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

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

  // Clear Service
  if (sender) C.cboService.Text("");
  C.cboService.ReadOnly(true);

  // Update Services list
  if (C.cboBankAccount.Text()) {
    widget.GetString("GetBankAccountServices", { bankAccountId: C.cboBankAccount.Text() },
      function (data) {
        cboBankAccount_Change_Done(C.cboBankAccount.Text(), data);
      },
      cboBankAccount_Change_Fail);
  }
}

function cboBankAccount_Change_Done(bankAccountId, data) {
  if (bankAccountId == C.cboBankAccount.Text()) {
    var list = JSON.parse(data);
    
    C.cboService.RefreshFromCodeDescriptionList(list);
    C.cboService.ReadOnly(false);
    
    // If there is only 1 item, default to that
    if (list.length == 1) C.cboService.Text(list[0].Code);
  }
  else {
    // Bank Account has been changed
  }
}

function cboBankAccount_Change_Fail(error) {
  widget.UI.MsgBoxAlert(error);
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    bankAccountId: C.cboBankAccount.Text(),
    serviceId: C.cboService.Text(),

    batchId: C.txtBatchId.Text(),
    batchNotes: C.txtBatchNotes.Text(),

    autoCommit: (mRecord.ShowAutoCommit &amp;&amp; C.chkAutoCommit.Value()),
  }

  return params;
}

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

  // Lists
  if (mRecord) {
    C.cboBankAccount.RefreshFromStandardRange("BankAccounts", "");
  }

  // Controls
  if (mRecord) {
    if (!mRecord.ShowAutoCommit) C.tbAutoCommit.hide();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

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

    case "RECENT":
      // Recent
      tabWizard_Refresh(0);
      break;

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

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 affect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
  }
  else {
    // Validate
    tabWizard_Validate(function() {
      if (true) { //mRecord.PromptOnCommit) {
        // Confirm (ignore setting since prompt contains summary information we always want to show)
        var heading = "Import Bank Transactions";
        var message = "&lt;p&gt;Are you sure you want to import the selected file?&lt;/p&gt;&lt;p&gt;A new, saved Batch will be created with the following details:&lt;/p&gt;";
        message += "&lt;ul&gt;";
        message += "&lt;li&gt;Bank Account: &lt;b&gt;" + widget.UI.HtmlEncode(C.cboBankAccount.Text()) + "&lt;/b&gt;, &lt;b&gt;" + widget.UI.HtmlEncode(C.cboBankAccount.GetDescription()) + "&lt;/b&gt;&lt;/li&gt;";
        message += "&lt;li&gt;Service: &lt;b&gt;" + widget.UI.HtmlEncode(C.cboService.Text()) + "&lt;/b&gt;, &lt;b&gt;" + widget.UI.HtmlEncode(C.cboService.GetDescription()) + "&lt;/b&gt;&lt;/li&gt;";
        if (mRecord_ServiceImportOptions.ShowBatchId &amp;&amp; C.txtBatchId.Text()) {
          message += "&lt;li&gt;Batch ID: &lt;b&gt;" + widget.UI.HtmlEncode(C.txtBatchId.Text()) + "&lt;/b&gt;&lt;/li&gt;";
        }
        else {
          message += "&lt;li&gt;Batch ID: &lt;b&gt;auto-generate&lt;/b&gt;&lt;/li&gt;";
        }
        message += "&lt;/ul&gt;";
        if (C.chkAutoCommit.Value()) message += "&lt;p&gt;&lt;b&gt;NOTE: &lt;/b&gt;The new Bank Batch will be committed once the import is complete.&lt;/p&gt;";

        // Background Process
        message += "&lt;p&gt;NOTE: You can close this form and any time and open it again to monitor the status of this process.&lt;/p&gt;";

        // Confirm
        widget.UI.MsgBoxConfirm(message,
                                {
                                  heading: heading,
                                  icon: "Import",
                                  messageIsHtml: true,
                                },
                                Form_ExecuteAction_FinishPost,
                                null);
      }
      else {
        // Commit without prompting
        Form_ExecuteAction_FinishPost();
      }
    });
  }
}

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

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Bank Transaction Import, please wait...");

  // Get Parameters
  var params = CreateFinishParameters();

  // Finish
  widget.UploadFiles("Finish", params, fileFile,
    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 (data) {
      // Show Error
      widget.UI.MsgBoxAlert(data);

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

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

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

function Form_ExecuteAction_FinishPost_AutoCommit(batchId) {
  // Block UI
  widget.UI.Block("Committing Batch, please wait...");

  // Commit
  widget.GetString("CommitBatch", { batchId: batchId },
    function (data) {
      // Parse
      data = JSON.parse(data)

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

      // Summary
      var message = "&lt;p&gt;Bank Batch '&lt;b&gt;" + widget.UI.HtmlEncode(data.BatchId) + "&lt;/b&gt;' committed.";
      message += "&lt;p&gt;";
      message += "&lt;ul&gt;";
      message += "&lt;li&gt;Total Transactions: &lt;b&gt;" + data.TransactionCount + "&lt;/b&gt;&lt;/li&gt;";
      message += "&lt;li&gt;Committed: &lt;b&gt;" + data.TransactionCountCommitted + "&lt;/b&gt;&lt;/li&gt;";
      if (data.TransactionCountFailed != 0) {
        message += "&lt;li&gt;Failed: &lt;b style='color:red'&gt;" + data.TransactionCountFailed + "&lt;/b&gt;&lt;/li&gt;";
      }
      message += "&lt;/ul&gt;";
      message += "&lt;/p&gt;";

      // Prompt
      if (data.TransactionCountFailed == 0) {
        widget.UI.MsgBoxInfo(message, { heading: "Batch Committed", messageIsHtml: true },
          function () {
            // Close
            widget.Close();
          }
        );
      }
      else {
        widget.UI.MsgBoxConfirm(message + "&lt;p&gt;Would you like to open the Bank Entry wizard now?&lt;/p&gt;&lt;p&gt;This will allow you to view error information for each transaction that fails to commit.&lt;/p&gt;", { heading: "Batch Committed with Failures", icon: "Warning", messageIsHtml: true, captionOk: "Yes", captionCancel: "No" },
          function () {
            // Unblock UI
            widget.UI.Unblock();

            // Close
            widget.Close();

            // Show Bank Entry
            widget.ExecuteApplicationShortcutUrl("app://FormShow?form=BankEntry&amp;batchId=" + encodeURIComponent(batchId));
          },

          function () {
            // Close
            widget.Close();
          }
        );
      }
    },

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

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

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

      // Update Status
      mRecord_BackgroundProcessStatus = data;

      // Refresh Progress
      pageProgress_Refresh();

      // Status
      var Status = mRecord_BackgroundProcessStatus.Status;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Bank Transaction Import was successfully cancelled.");
          break;

        case "Complete":
        case "CompleteWithErrors":
        case "CompleteWithWarnings":
          // Complete
          mComplete = true;
          if (mRecord_BackgroundProcessStatus.Details) mComplete_Information = JSON.parse(mRecord_BackgroundProcessStatus.Details);
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          var message = "Bank Transaction Import is ";
          if (mComplete_Information) message = "Bank Transaction Import Batch '" + mComplete_Information.BatchId + "' is ";          
          widget.UI.MsgBoxInfo(message += widget.SplitWordsAtCapitals(Status, true, true) + ".", {}, Form_ExecuteAction_GetBackgroundProcessStatus_Complete_Post);
          break;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Bank Transaction Import 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_Complete_Post() {
  // Show Bank Entry?
  if (mComplete_Information &amp;&amp; mComplete_Information.PromptForBankEntry) {
    widget.UI.MsgBoxConfirm("Would you like to view the imported Bank Batch", { captionOk: "Yes", captionCancel: "No" },
      function () {
        // Close
        widget.Close();

        // Show Bank Entry
        widget.ExecuteApplicationShortcutUrl("app://FormShow?form=BankEntry&amp;batchId=" + encodeURIComponent(mComplete_Information.BatchId));
      }
    );
  }
}

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

  // Block UI
  widget.UI.Block("Refreshing Recent Bank Transaction Imports, please wait...");

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  // Switch to Progress Page
  mFromRecent = true;
  mMonitoringExisting = true;
  mProcessId = item.ProcessId;
  tabWizard_Refresh(3);
  pageProgress_Refresh(true);

  // Start monitoring
  Form_ExecuteAction_GetBackgroundProcessStatus();
}

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

  // Tab
  tabWizard_Resize();
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Import 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 {
    tabWizard_Cancel_Post();
  }
}

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

// ===========
// Wizard Move
// ===========
function tabWizard_Move(direction) {
  var Ok;

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        default:
          found = true;
          break;
      }

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

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

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "Options":
        // Allow Batch Id?
        if (mRecord_ServiceImportOptions.ShowBatchId) {
          C.tbBankBatch.show();
          if (mRecord_ServiceImportOptions.AllowAutoSequenceBatchId) {
            C.cmdBatchId.show();
            C.txtBatchId.AllowBlank(true);
          }
          else {
            C.cmdBatchId.hide();
            C.txtBatchId.AllowBlank(false);
          }
        }
        else {
          C.tbBankBatch.hide();
        }

        switch(mRecord_ServiceImportOptions.BankServiceMethod) {
          case "File":
            // File Import
            C.tbOptionsFile.show();
            break;

          default:
            window.alert("Unsupported Bank Service Method '" + mRecord_ServiceImportOptions.BankServiceMethod + "'");
        }
        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;
      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;
  }
}

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

    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  // Back, Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();

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

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

  // 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");
    cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
    cmdHistory.prop("disabled", false);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        mRecord_ServiceImportOptions = o.Data;
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ==========
// cmdBatchId
// ==========
function cmdBatchId_Click() {
  if (C.txtBatchId.Text()) {
   widget.UI.MsgBoxConfirm("Are you sure you want to overwrite this Batch ID with a new, auto-generated Batch ID?\n\nNOTE: Misusing this button may cause gaps to appear in Batch ID sequences.", { heading: "Auto-Generate Batch ID"}, cmdBatchId_Click_Done);
  }
  else {
    cmdBatchId_Click_Done();
  }
}

function cmdBatchId_Click_Done() {
  // Block UI
  widget.UI.Block("Generating Batch ID, please wait...");

  widget.GetString("GetAutoBatchId", { bankAccountId: C.cboBankAccount.Text(), serviceId: C.cboService.Text() },
    function (data) {
      // Unblock UI
      widget.UI.Unblock();

      // Update
      C.txtBatchId.Text(data);

      // Focus
      C.txtBatchId.Focus();

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

      widget.UI.MsgBoxAlert(error);
    });
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>R-ETZtnBYkalDlxYsjMM-Q</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>640</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowAutoCommit" type="Boolean">
            <BlankTip />
            <Caption>Show Auto Commit option?</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="AutoCommit" type="Boolean">
            <BlankTip />
            <Caption>Auto Commit Batch?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="BankAccountId" type="Range">
            <BlankTip />
            <Caption>BankAccountId</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>BankAccounts</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="ServiceId" type="Text">
            <BlankTip />
            <Caption>ServiceId</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>10</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>