<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2025-10-20T02:10:21.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2025-10-13T01:22:02.7900000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2025-10-20T01:07:30.4030000</UpdatedUtcDate>
    <ScriptId>BANKLODGEMENT</ScriptId>
    <Description>Bank Lodgement</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_BankLodgement
Option Explicit On
Option Strict On

' #################################################################
' Bank Lodgements
'
' Version: 1.00 (20/10/2025)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  20/10/2025           J036097   Created
' #################################################################

' Constants
Private Const FORM_KEY As String = "BankLodgement"

' Objects
Private WithEvents mLodgements As finLodgements
Private mCombinedParameters As ISKeyValueList
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus

' Other
Private mAutoCommit As Boolean
Private mDesktopMode As Boolean
Private mIsRefreshing As Boolean
Private mLastCaption As String
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")
    mDesktopMode = .GetBoolean("DesktopMode")    
    mProcessId = .GetString("ProcessId")
  End With
  
  ' Handle Events
  Select Case eventId
    Case ""
      returnValue = ScriptInfo.TemplateText
      
    Case "BackgroundProcess.Refresh"
      Main = BackgroundProcess_Refresh(returnValue)
      
    Case "BackgroundProcess.ExecuteCommit"
      Main = BackgroundProcess_ExecuteCommit(returnValue)
      
    Case "CancelBackgroundProcess"
      Main = CancelBackgroundProcess(returnValue)
      
    Case "DownloadSummary"
      Main = DownloadSummary(returnValue)
      
    Case "Finish"
      Main = Finish(parametersJson, startUpParametersJson, returnValue)
      
    Case "GetBackgroundProcessStatus"
      Main = GetBackgroundProcessStatus(returnValue)
      
    Case "GetCurrentProcesses"
      Main = GetCurrentProcesses(returnValue)      
      
    Case "GetExistingExports"
      Main = GetExistingExports(returnValue)
      
    Case "GetInitialisationInfo"
      Main = GetInitialisationInfo(returnValue)
      
    Case "GetItemPreview"
      Main = GetItemPreview(returnValue)
      
    Case "GetProcessSummary"
      Main = GetProcessSummary(parametersJson, returnValue)
      
    Case "PrintDraftSchedule"
      Main = PrintDraftSchedule(returnValue)
      
    Case "Refresh"
      Main = Refresh(parametersJson, startUpParametersJson, returnValue)
      
    Case "UpdateRefreshData"
      Main = UpdateRefreshData(parametersJson)
      
    Case "WizardValidate"
      Main = WizardValidate(parametersJson, returnValue)
      
    Case Else
      finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
      Main = False
  End Select

End Function

''' &lt;summary&gt;
'''  Background Process 'Refresh' Event.
''' &lt;/summary&gt;
Private Function BackgroundProcess_Refresh(ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True
  
  ' Refreshing Flag
  mIsRefreshing = True
  
  ' Get Background Process
  ' NOTE: This is required to add events and to check to see if the User has attempted to cancel this process (if supported)
  mProcessStatus = DirectCast(ScriptInfo.ContextData.GetObject("ProcessStatus"), finHtmlWidgetBackgroundProcessStatus)

  ' Get Finish Parameters
  Success = GetWizardFinishParameters(mParameters.ToSimpleJsonString(), WizardFinishParameters)

  ' Get Lodgements
  If Success Then
    Success = Me.CreateLodgements(WizardFinishParameters, mLodgements)
  End If
  
  ' Refresh Lodgements
  If Success Then
    Success = mLodgements.Refresh() 
  End If

  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New BankLodgement(mLodgements), returnValue)
  End If

  ' Refreshing Flag
  mIsRefreshing = False
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Background Process 'Execute Commmit' Event.
''' &lt;/summary&gt;
Private Function BackgroundProcess_ExecuteCommit(ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  Dim LodgementData As BankLodgement
  Dim obj As Object
  Dim RefreshData As String
  Dim BankExportId As String = ""
  Dim FileName As String

  ' Assume Success
  Success = True
  
  ' Reset last caption
  mLastCaption = ""
  
  ' Get Process Status
  mProcessStatus = DirectCast(ScriptInfo.ContextData.GetObject("ProcessStatus"), finHtmlWidgetBackgroundProcessStatus)
  mProcessStatus.AddEvent_Information("Starting Lodgement Commit")

  If finBL.HtmlWidgetUtilities.GetBackgroundProcessRefreshData(mProcessStatus.ProcessId, RefreshData) Then
    If String.IsNullOrEmpty(RefreshData) Then
      Success = False
      finBL.Error.ErrorBegin("No Refresh Data available.")
    Else
      If Not finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(RefreshData, GetType(BankLodgement), obj) Then
        Success = False
      Else
        LodgementData = DirectCast(obj, BankLodgement)
      End If
    End If
  Else
    Success = False
  End If
  
  If Success Then
    mProcessStatus.AddEvent_Information("Rebuilding Lodgement from selected items")
    Success = UpdateBankLodgementFromJsonClass(LodgementData, mLodgements)
  End If

  ' Commit Batch
  If Success Then
    mProcessStatus.AddEvent_Information("Committing Lodgement")
    If mLodgements.ExecuteCommit() Then
      BankExportId = mLodgements.BankExportId
    Else
      Success = False
    End If
  End If

  ' Process Update
  If Success AndAlso Not String.IsNullOrEmpty(BankExportId) Then
    mProcessStatus.AddEvent_Information("Lodgement committed successfully. Batch ID: " &amp; BankExportId)    
  End If
  
  ' Generate Lodgement Schedule
  If Success Then
    mProcessStatus.AddEvent_Information("Generating Lodgement Schedule")
    
    If GetReportData(mLodgements, False, True, True, FileName) Then
      ' Attach File
      mProcessStatus.Attachments.AddDataFromFile(FileName, Nothing)
      
      ' Delete Temporary file
      finBL.Runtime.FileUtilities.DeleteFile(FileName)
    End If
  End If

  Return Success
  
End Function

Private Sub mLodgements_Progress(progress As Double, caption As String) Handles mLodgements.Progress

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

Private Sub mLodgements_ProgressRefresh(progress As Double, caption As String) Handles mLodgements.ProgressRefresh

  ' Log Event
  If mIsRefreshing Then
    ' Only log when Refreshing initially. This is required as another Refresh occurs during the commit, we don't want to add events during this secondary refresh
    mProcessStatus.AddEvent_Information(caption)
  End If  
  
End Sub

Private Function GetInitialisationInfo(ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim BankAccountRO As finBankAccountRO
  Dim BankAccount As finBankAccount
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)

  ' Assume Success
  Success = True
  
  ' Initialise
  BankAccount = finBL.CreateBankAccount()
  FormInitialisationInfo = New FormInitialisationInfo()
  
  ' Validate
  Success = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)
  
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ProcessId = mProcessId
      
      .DefaultDateLodged = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())      
      
      ' Bank Accounts with Lodgement services
      For Each BankAccountRO In finBL.BankAccounts
        If HasLodgement(BankAccountRO) Then
          If BankAccount.LoadPk(BankAccountRO.Pk) Then
            .BankAccounts.Add(New BankAccount(BankAccount))
          Else 
            Success = False
            Exit For
          End If          
        End If
      Next
      
      ' Configuration
      .AutoCommit = mAutoCommit
      .ShowCashRegisters = (finBL.Settings.AddOns.BankingAdvanced AndAlso finBL.CashRegisters.Count &lt;&gt; 0)      
    End With
  End If

  ' Get current and recent Background Processes for this User
  If Success Then
    If finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_HtmlWidgetScript(ScriptInfo.ScriptId, True, ProcessStatuses) Then
      FormInitialisationInfo.CurrentProcesses = ProcessStatuses
    Else
      Success = False
    End If
  End If
  
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Indicates if a Bank Account has any active Lodgement Export Services.
''' &lt;/summary&gt;
Private Function HasLodgement(bankAccountRO As finBankAccountRO) As Boolean
  
  For Each ExportServiceRO As finBankAccountExportServiceRO In bankAccountRO.ExportServices
    If (ExportServiceRO.Active AndAlso ExportServiceRO.Lodgement) Then Return True
  Next 
  
  Return False
  
End Function

''' &lt;summary&gt;
'''  Get Existing Bank Lodgement Exports.
''' &lt;/summary&gt;
Private Function GetExistingExports(ByRef returnValue As String) As Boolean

  Dim dv As DataView
  Dim LodgementBatches As New List(Of LodgementBatch)
  Dim Row As DataRow
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  If finBL.Utilities.CreateDataViewFromStandardRange(isefinStandardRange.LodgementBatches, "", True, iseCollectionDataViewTarget.DbCombo, dv, "", "", Nothing) Then
    For Each Row In dv.Table.Rows
      LodgementBatches.Add(New LodgementBatch(Row))
    Next
    LodgementBatches.Sort(AddressOf GetExistingExports_SortComparer)
  Else
    Success = False
  End If

  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(LodgementBatches, returnValue)
  End If
  
  Return Success
  
End Function

Private Function GetExistingExports_SortComparer(x As LodgementBatch, y As LodgementBatch) As Integer

  Return y.CreatedUtcDate.CompareTo(x.CreatedUtcDate)
  
End Function

Private Function GetItemPreview(ByRef returnValue As String) As Boolean

  Dim Success As Boolean = True
  Dim BankTransactionPk As Integer
  Dim Lodgements As finLodgements
  Dim BankAccountId As String
  Dim ServiceId As String
  Dim DateLodged As Date

  ' Initialise ByRef Parameters
  returnValue = ""
  
  ' Parameters
  With mCombinedParameters
    BankTransactionPk = .GetInteger("BankTransactionPk")
    BankAccountId = .GetString("BankAccountId")
    ServiceId = .GetString("ServiceId")
    DateLodged = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateLodged"))
  End With
  
  If BankTransactionPk &lt;&gt; 0 Then
    ' To generate a preview, we need a finLodgements context.
    Lodgements = finBL.CreateLodgements()
    If Lodgements.Load(BankAccountId, ServiceId, DateLodged, BankTransactionPk) Then
      returnValue = finBL.ScriptFunctions.BuiltInLodgementsSummaryScript(Lodgements, iseSummaryPageTarget.WebServices, 0, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
    Else 
      Success = False
    End If
  End If

  If (Not Success) Then
    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 CountIncluded As Integer
  Dim Item As BankTransactionItem
  Dim LodgementData As BankLodgement
  Dim obj As Object
  Dim sb As finHtmlSummaryPage2StringBuilder 
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim TotalCount As Integer
  Dim TotalIncluded As Decimal
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True
  
  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()  

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

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

  If Success Then    
    For Each Item In LodgementData.Items
      TotalCount += 1
      
      If Item.Include Then
        CountIncluded += 1
        TotalIncluded += Item.Value
      End If
    Next

    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText()
      .Columns.AddInteger()
      .Rows.AddSectionHeading2("Lodgement")
      .AddRowCaptionInteger("Included:", CountIncluded)
      .AddRowCaptionInteger("Excluded:", TotalCount - CountIncluded)
      .AddRowCaptionInteger("Total:", TotalCount, , True, iseSummaryTableRowClass.FooterBold)
      
      .Rows.AddSectionHeading2("Value to Process")
      .AddRowCaptionCurrency("Value:", totalIncluded, False, True, iseSummaryTableRowClass.FooterBold)
    End With
  End If

  ' Build Summary
  If Success Then
    sb.Initialise(ScriptInfo)
    sb.HtmlHeaderBegin("ProcessSummary", isefinSummaryPageStyle.Blocks)
    sb.HtmlHeaderEnd()
    
    sb.SectionColumnsBegin("100%")
    sb.ColumnBegin("100%")
    
    sb.BlockBegin("Bank Lodgement Summary", "", isefinSummaryPageBlockHeadingStyle.Main)
    sb.SummaryTableAppend(SummaryTable)
    sb.BlockEnd()
    
    sb.ColumnEnd()
    sb.SectionColumnsEnd()
    sb.HtmlFinalise()
    
    returnValue = sb.ToString(True)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Builds a finLodgements object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateLodgements(parameters As WizardFinishParameters,
                                  ByRef lodgements As finLodgements) As Boolean
                                      
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  lodgements = finBL.CreateLodgements()
  
  ' Update Parameters
  If Success AndAlso parameters IsNot Nothing Then
    With lodgements
      If .Load(parameters.BankAccountId, parameters.ServiceId, finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateLodged), , False) Then
        .LodgementNotes = parameters.Notes
        .RangeCashRegisters = parameters.CashRegisters        
      Else 
        Success = False
      End If
    End With
  End If
  
  Return Success
                                  
End Function

''' &lt;summary&gt;
'''  Cancel the Background Process.
''' &lt;/summary&gt;
Private Function CancelBackgroundProcess(ByRef returnValue As String) As Boolean

  Return finBL.HtmlWidgetUtilities.CancelBackgroundProcess(mCombinedParameters.GetString("ProcessId"))
  
End Function

''' &lt;summary&gt;
'''  Updates a finLodgements object from the JSON class.
''' &lt;/summary&gt;
Private Function UpdateBankLodgementFromJsonClass(lodgementData As BankLodgement, 
                                                  ByRef lodgements As finLodgements) As Boolean

  Dim Lodgement As finLodgement
  Dim LodgementItem As BankTransactionItem  
  Dim MatchedAccountCount As Integer
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  MatchedAccountCount = 0 
  
  ' Initialise
  If lodgements Is Nothing Then
    lodgements = finBL.CreateLodgements()
    Success = lodgements.Load(lodgementData.BankAccountId, lodgementData.ServiceId, finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(lodgementData.DateLodged),, True)
  End If
  
  ' Reset
  If Success Then
    For Each Lodgement In lodgements
      Lodgement.Include = False
    Next 
  End If  
  
  ' Match Items
  If Success Then    
    For Each LodgementItem In lodgementData.Items
      For Each Lodgement In lodgements
        With Lodgement
          If LodgementItem.BankTransactionPk = .BankTransactionPk Then
            MatchedAccountCount += 1
            .Include = LodgementItem.Include
            Exit For
          End If
        End With
      Next 
    Next
  End If
  
  ' Validate
  If Success AndAlso lodgementData.Items.Count &lt;&gt; MatchedAccountCount Then
    Success = False
    finBL.Error.ErrorBegin("Record mismatch. The collection may have changed since it was originally loaded. Please restart the Income Distribution Process again.")
  End If
  
  ' Update Final Details
  If Success Then
    With lodgements
      .LodgementNotes = lodgementData.Notes
      .RangeCashRegisters = lodgementData.CashRegisters
    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,
                         startupParametersJson As String,
                         ByRef returnValue As String) As Boolean
                      
  Dim ProcessId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  ' NOTE: Only required for validation purposes
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Validate
  If Success Then
    ' Not required
  End If
  
  ' Start Background Process to Refresh Data
  If Success Then
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript_Refresh(ScriptInfo.ScriptId, parametersJson, startupParametersJson, mAutoCommit, ProcessId, mDesktopMode)
  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 a Summary of the Bank Lodgement export.
''' &lt;/summary&gt;
Private Function DownloadSummary(ByRef returnValue As String) As Boolean

  Dim BankExportId As String
  Dim IncludeReversed As Boolean 
  Dim Lodgements As finLodgements
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Initialise
  Lodgements = finBL.CreateLodgements()
  
  ' Parameters
  With mCombinedParameters
    BankExportId = mCombinedParameters.GetString("BankExportId")
    IncludeReversed = mCombinedParameters.GetBoolean("IncludeReversed")
  End With
  
  ' Load Existing
  If Success Then
    Success = Lodgements.LoadExisting(BankExportId)
  End If

  If Success Then
    Success = GetReportData(Lodgements, False, IncludeReversed, False, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Run a report, and return the PDF as a downloadable file.
''' &lt;/summary&gt;
Private Function GetReportData(lodgements As finLodgements,
                               draft As Boolean,
                               includeReversed As Boolean,
                               returnFileName As Boolean,
                               ByRef returnValue As String) As Boolean
  
  Dim FileCreated As Boolean
  Dim FileDownloadInfo As finFileDownloadInfo
  Dim Filename As String
  Dim Report As I_ISReportBaseBL
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise ByRef Parameters
  returnValue = ""
  
  ' Initialise Report
  Success = finBL.Reports.CreateReportForScript(isefinReportType.LodgementSchedule, Report, , lodgements)

  ' Update Parameters
  If Success Then
    ' Calculate defaults
    Report.Parameters.CalculateValues(True, False)
    
    ' Update
    With Report.Parameters
      .SetBoolean("Draft", draft)
      .SetBoolean("IncludeReversed", includeReversed)
    End With
    
    ' Recalculate Invisible Parameters
    ' NOTE: This mimics how the User Interface works when a User runs a Report
    Report.Parameters.CalculateValues(False, True)
  End If
  
  ' Run Report
  If Success Then    
    Success = Report.RunForScript()  
  End If
  
  ' Export Report
  If Success Then
    FileName = "LodgementBatch_" &amp; lodgements.BankExportId &amp; "_" &amp; Format(finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime(), "yyyyMMdd_hhmmss")
    FileName = finBL.Runtime.FileUtilities.GetTemporaryFileName(FileName, ".pdf")
    
    If finBL.Reports.ReportFunctions.ExportReportToPdfForScript(Report, FileName) Then
      FileCreated = finBL.Runtime.FileUtilities.FileExists(FileName)
    Else 
      Success = False
    End If
  End If
  
  ' Convert to Download Info
  If Success Then
    If FileCreated Then
      If returnFileName Then
        ' Email Attachment
        returnValue = FileName
      Else 
        ' File Download
        FileDownloadInfo = finBL.CreateFileDownloadInfo()
    
        If FileDownloadInfo.LoadFile(FileName) Then
          returnValue = FileDownloadInfo.ToXmlString()
        Else 
          Success = False
        End If
      End If      
      
      ' Try to delete file
      If Not returnFileName Then
        If Not finBL.Runtime.FileUtilities.DeleteFile(FileName) Then
          ' Ignore errors
        End If
      End If      
    Else 
      Success = False
      finBL.Error.ErrorBegin("Could not get temporary Lodgement Batch Report to download.")
    End If    
  End If
  
  Return Success
  
End Function

Private Function PrintDraftSchedule(ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  Dim LodgementData As BankLodgement
  Dim Lodgements As finLodgements
  Dim obj As Object
  Dim RefreshData As String 
  
  ' Assume Success
  Success = True
  
  ' Parameters
  With mCombinedParameters
    RefreshData = mParameters.GetString("RefreshData")
  End With 
  
  ' Get Lodgement Data from the Refresh data
  If String.IsNullOrEmpty(RefreshData) Then
    Success = False
    finBL.Error.ErrorBegin("No data available to print.")
  Else
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(RefreshData, GetType(BankLodgement), obj) Then
      LodgementData = DirectCast(obj, BankLodgement)
    Else
      Success = False
    End If
  End If
  
  ' Get finLodgements object
  If Success Then
    Success = UpdateBankLodgementFromJsonClass(LodgementData, Lodgements)
  End If
  
  If Success Then    
    Success = GetReportData(Lodgements, True, True, False, returnValue)
  End If
  
  Return Success
  
End Function

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

  Dim CompleteMessage As String
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  ' NOTE: Only required for validation purposes
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Validate
  If Success Then
    ' Not required
  End If
  
  ' Queue Background Process
  If mAutoCommit Then
    ' Queue "Refresh" - Execute Commit will occur automatically
    Success = Me.Refresh(parametersJson, startupParametersJson, returnValue)
  Else 
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript_ExecuteCommit(ScriptInfo.ScriptId, WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData, mDesktopMode)
    If Success Then
      ' Context-specific functionality - not supported
      CompleteMessage = ""
    End If
    
    ' Response
    If Success Then
      Data = New With {
        .ProcessId = WizardFinishParameters.ProcessId,
        .CompleteMessage = CompleteMessage
      }
    End If
  
    ' Finalise
    If Success Then
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
    End If
  End If

  Return Success

End Function

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

  Return finBL.HtmlWidgetUtilities.GetBackgroundProcessStatusIncludingEventsJson(mCombinedParameters.GetString("ProcessId"), mCombinedParameters.GetString("LastEventId"), returnValue)
  
End Function

''' &lt;summary&gt;
'''  Get Current Processes.
''' &lt;/summary&gt;
Private Function GetCurrentProcesses(ByRef returnValue As String) As Boolean
    
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

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

  Dim Success As Boolean = True
  Dim WizardFinishParameters As WizardFinishParameters

  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  If Success Then
    Success = finBL.HtmlWidgetUtilities.UpdateBackgroundProcessRefreshData(WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Wizard Validate.
''' &lt;/summary&gt;
Private Function WizardValidate(parametersJson As String, ByRef returnValue As String) As Boolean

  Dim Success As Boolean = True
  Dim WizardFinishParameters As WizardFinishParameters
  Dim PageId As String = mCombinedParameters.GetString("PageId")
  Dim FailedMessage As String = ""
  Dim FailedControlId As String = ""
  Dim Data As Object = Nothing
  
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)
  
  If Success Then
    Select Case PageId
      Case "General"
        ' No server-side validation needed for this step
        
      Case "Options"
        If String.IsNullOrEmpty(WizardFinishParameters.BankAccountId) Then
          FailedMessage = "A Bank Account must be selected."
          FailedControlId = "cboBankAccount"
        ElseIf String.IsNullOrEmpty(WizardFinishParameters.ServiceId) Then
          FailedMessage = "A Service must be selected."
          FailedControlId = "cboService"
        End If
    End Select
  End If

  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardValidateResponse(Data, FailedMessage, FailedControlId), 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  

  ' Initialise ByRef Parameters
  wizardFinishParameters = Nothing
  
  ' 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;
'''  Wizard Initialisation Information
''' &lt;/summary&gt;
Public Class FormInitialisationInfo
  
  ' Record
  Public ProcessId As String
  Public DefaultDateLodged As Date  
  Public BankAccounts As New List(Of BankAccount)
  Public CurrentProcesses As New List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  
  ' Configuration
  Public AutoCommit As Boolean
  Public ShowCashRegisters As Boolean
  
End Class


''' &lt;summary&gt;
'''  Represents a Bank Account
''' &lt;/summary&gt;
Public Class BankAccount
  
  Public BankAccountId As String
  Public Description As String
  Public ExportServices As New List(Of ExportService)

  Public Sub New(bankAccount As finBankAccount)
    
    Me.BankAccountId = bankAccount.BankAccountId
    Me.Description = bankAccount.Description
    
    For Each row As DataRow In bankAccount.ExportServices.ToDataView(False, True).Table.Rows
      Me.ExportServices.Add(New ExportService(bankAccount.ExportServices.ItemByServiceId(finBLShared.Database.GetFieldString(row("ServiceId")))))
    Next
    
  End Sub
  
End Class


''' &lt;summary&gt;
'''  Represents an Export Service
''' &lt;/summary&gt;
Public Class ExportService
  
  Public ServiceId As String
  Public Description As String
  
  Public Sub New(bankAccountExportService As finBankAccountExportService)
    
    Me.ServiceId = bankAccountExportService.ServiceId
    Me.Description = bankAccountExportService.Description
    
  End Sub
  
End Class


''' &lt;summary&gt;
'''  Represents a Lodgement Batch
''' &lt;/summary&gt;
Public Class LodgementBatch
  
  Public BankExportId As String
  Public [Date] As Date
  Public BankAccountId As String
  Public BankAccountDescription As String
  Public Total As Decimal
  Public Created As Date
  Public CreatedUser As String
  Public CreatedUtcDate As Date
  Public Notes As String

  Public Sub New(row As DataRow)
    
    With finBLShared.Database
      Me.BankExportId = .GetFieldString(row!BankExportId)
      Me.[Date] = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.GetFieldDate(row!Date))
      Me.BankAccountId = .GetFieldString(row!BankAccountId)
      Me.BankAccountDescription = .GetFieldString(row!BankAccountDescription)
      Me.Total = .GetFieldDecimal(row!Total)      
      Me.CreatedUser = .GetFieldString(row!CreatedUser)
      Me.CreatedUtcDate = .GetFieldUtcDate(row!CreatedUtcDate)
      Me.Created =  finBLShared.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(finBLShared.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(Me.CreatedUtcDate))
      Me.Notes = .GetFieldString(row!Notes)
    End With
    
  End Sub
  
End Class


''' &lt;summary&gt;
'''  Represents a Bank Lodgement.
''' &lt;/summary&gt;
Public Class BankLodgement
  
  Public BankAccountId As String
  Public ServiceId As String
  Public DateLodged As Date
  Public CashRegisters As String
  Public Notes As String
  Public Items As New List(Of BankTransactionItem)
  
  Public Sub New()
  End Sub
  
  Public Sub New(lodgements As finLodgements)
    
    Me.BankAccountId = lodgements.BankAccountId
    Me.ServiceId = lodgements.BankAccountServiceId
    Me.DateLodged = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(lodgements.LodgementDate)
    Me.CashRegisters = lodgements.RangeCashRegisters
    Me.Notes = lodgements.LodgementNotes
    
    For Each item As finLodgement In lodgements
      Me.Items.Add(New BankTransactionItem(item))
    Next
  End Sub
  
End Class


''' &lt;summary&gt;
'''  Represents a Bank Transaction Item
''' &lt;/summary&gt;
Public Class BankTransactionItem
  
  Public Include As Boolean
  Public BankTransactionPk As Integer
  Public AccountId As String
  Public AccountName As String
  Public [Date] As Date
  Public Reference As String
  Public Value As Decimal
  Public CashRegisterId As String
  Public PaymentMethodId As String
  Public PayMethodAccountName As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(lodgementItem As finLodgement)
    
    Me.Include = lodgementItem.Include
    Me.BankTransactionPk = lodgementItem.BankTransactionPk
    Me.AccountId = lodgementItem.AccountId
    Me.AccountName = lodgementItem.AccountName
    Me.Date = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(lodgementItem.Date)
    Me.Reference = lodgementItem.Reference
    Me.Value = lodgementItem.Value
    Me.CashRegisterId = lodgementItem.CashRegisterId
    Me.PaymentMethodId = lodgementItem.BankingDetails.PaymentMethodId
    Me.PayMethodAccountName = lodgementItem.BankingDetails.AccountName
    
  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
  
  Public BankAccountId As String
  Public BankExportId As String
  Public CashRegisters As String
  Public DateLodged As Date
  Public IncludeReversed As Boolean
  Public Notes As String
  Public OptionCreate As Boolean
  Public OptionReprint As Boolean
  Public ProcessId As String
  Public RefreshData As String
  Public ServiceId As String
  
End Class


''' &lt;summary&gt;
'''  Wizard Validate Response
''' &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 />
    <PermissionKeyExecute />
    <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;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&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 Lodgements you have processed."&gt;Recent Bank Lodgements&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Create a new Bank Lodgement or select an existing one to download a Schedule."&gt;General&lt;/li&gt;
        &lt;li tabId="Options" tooltipText="Select Lodgement options."&gt;Options&lt;/li&gt;
        &lt;li tabId="Items" tooltipText="Select the Bank Transactions to include in the Lodgement."&gt;Lodgements&lt;/li&gt;
        &lt;li tabId="Confirm" tooltipText="Confirm the Bank Lodgement to begin processing."&gt;Confirmation&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;div class="is-widget-form-body"&gt;
    &lt;div id="pageCurrentProcesses"&gt;
      &lt;div id="gridCurrentProcesses"&gt;&lt;/div&gt;
    &lt;/div&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 Lodgement&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOptionCreate" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblOptionReprint"&gt;Download an existing Lodgement Schedule&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOptionReprint" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr id="rowReprintIncludeReversed" &gt;
                &lt;th colspan="2" class='indent1'&gt;&lt;input id="chkReprintIncludeReversed" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblBankLodgements"&gt;Bank Lodgements&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/div&gt;

        &lt;div style="position:relative; flex-grow:1; max-width:1280px; margin-left:8px"&gt;
          &lt;div id="gridBankLodgements" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    
    &lt;div id="pageOptions"&gt;
       &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBankAccountSelection"&gt;Select the Bank Account and Service to use&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;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblLodgementDetails"&gt;Enter the date of Lodgement and any other Notes&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateDateLodged"&gt;Date Lodged:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateDateLodged" /&gt;&lt;/td&gt;
        &lt;/tr&gt;         
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCashRegisters"&gt;Optionally, enter a range of Cash Registers to filter by&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCashRegisters"&gt;Cash Registers:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCashRegisters" lookupCaption="Cash Registers" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&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;div id="pageConfirm"&gt;
      &lt;div id="wbProcessSummary"&gt;&lt;/div&gt;
    &lt;/div&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;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;Commit&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;

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

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

  //   General
  lblOptionCreate: null,
  chkOptionCreate: null,
  lblOptionReprint: null,
  chkOptionReprint: null,
  chkReprintIncludeReversed: null,
  lblBankLodgements: null,
  gridBankLodgements: null,

  //   Options
  lblBankAccountSelection: null,
  cboBankAccount: null,
  cboService: null,
  lblLodgementDetails: null,
  dateDateLodged: null,
  txtNotes: null,
  lblCashRegisters: null,
  txtCashRegisters: null,  

  //   Lodgements
  gridItems: null,
  divItemsSummary: null,
  wbItemsSummary: null,
  
  //   Confirm
  wbProcessSummary: 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 mFromRecent = false;
var mLastEventId = "";
var mLastProcessStatus = "";
var mLastRefreshParametersJson = "";
var mLastProcessSummaryJson = "";
var mMonitoringExisting = false;
var mProcessId;
var mRequiresRefresh = false;

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

  // Controls
  //   General
  C.lblOptionCreate = widget.UI.Label("lblOptionCreate", {});
  C.chkOptionCreate = widget.UI.CheckBox("chkOptionCreate", {
    caption: "Create a new Lodgement?",
    captionWrap: true,
    cssClass: "is-radio-button",
    onChange: chkOption_Change,
  });
  C.lblOptionReprint = widget.UI.Label("lblOptionReprint", {});
  C.chkOptionReprint = widget.UI.CheckBox("chkOptionReprint", {
    caption: "Download an existing Schedule?",
    captionWrap: true,
    cssClass: "is-radio-button",
    onChange: chkOption_Change,
  });
  C.chkReprintIncludeReversed = widget.UI.CheckBox("chkReprintIncludeReversed", {
    caption: "Include Reversed Transactions?",
    captionWrap: true,
  });
  C.lblBankLodgements = widget.UI.Label("lblBankLodgements", {});

  //   Options
  C.lblBankAccountSelection = widget.UI.Label("lblBankAccountSelection", {});
  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,
  });
  C.lblLodgementDetails = widget.UI.Label("lblLodgementDetails", {});
  C.dateDateLodged = widget.UI.DateBox("dateDateLodged", {
    allowBlank: false,
  });  
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    caption: "Notes:",
    captionWidth: 88,
    multiLine: true,
    rows: 4,
  });
  
  C.lblCashRegisters = widget.UI.Label("lblCashRegisters", {});
  C.txtCashRegisters = widget.UI.TextBox("txtCashRegisters", {
    maxLength: 255,
    onButtonClick: txtRange_ButtonClick,
  });
  
  //   Lodgements
  C.divItemsSummary = $("#divItemsSummary");
  C.wbItemsSummary = widget.UI.PreviewPane("wbItemsSummary", {});

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

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

  // 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.gridBankLodgements = widget.UI.Grid("gridBankLodgements", {
    allowCellSelect: false,
    allowMultiRowSelect: false,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,
    
    onRowDrilldown: gridBankLodgements_RowDrilldown,
    onInitialiseRow: gridBankLodgements_InitialiseRow,
  });

  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
  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");
  cmdHistory = $("#cmdHistory");
  cmdCancel.click(tabWizard_Cancel);
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });
  cmdHistory.click(function() { Form_ExecuteAction("Recent"); });

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

  // Reset
  Form_Reset();
});

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults
  C.chkOptionCreate.Value(true);
  C.chkOptionReprint.Value(false);

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

  // Resize
  Form_Resize();

  // Load Record
  Record_Load();
}

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_BankLodgements = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mBankLodgement = null;

  // Hide content
  frmMain.Visible(false);
  
  // Block UI
  widget.UI.Block("Initialising, please wait...");

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

      // Give Collections ability to lookup by id
      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 Lodgement Processes that you have started and are not yet complete.\n\nYou can review these or use the 'Next &gt;' button to begin a new Bank Lodgement Process.", { heading: "Bank Lodgements still Processing", icon: "MonitorCategory"} );
      }
    },
    // Fail
    function (message) {
      widget.UI.MsgBoxAlert("fail: " + message);
      Fields_Load();
    }
  );
}

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // Current Processes
    gridCurrentProcesses_Refresh();
    
    // General
    C.dateDateLodged.Value(mRecord.DefaultDateLodged);
    C.chkReprintIncludeReversed.Value(true);
  }

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

  // Update Controls
  pageGeneral_Refresh();

  // Update fields
  Fields_Update();
  
  // Refresh Tab
  tabWizard_Refresh();
}

// =============
// Fields Update
// =============
function Fields_Update() {
  // Controls
  if(mRecord) {
    // Show cash registers row if applicable
    C.lblCashRegisters.VisibleRow(mRecord.ShowCashRegisters);
    C.txtCashRegisters.VisibleRow(mRecord.ShowCashRegisters);

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

    // Setup range lookup button for cash registers
    var buttons = [];
    buttons.push({id: "Lookup", icon: "Find", tooltipText: "Lookup"});
    C.txtCashRegisters.ButtonsDefine(buttons);
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess() {
  if (mBankLodgement) {
    C.cboBankAccount.Text(mBankLodgement.BankAccountId);    
    C.cboService.Text(mBankLodgement.ServiceId);
    C.dateDateLodged.Value(mBankLodgement.DateLodged);
    C.txtCashRegisters.Text(mBankLodgement.CashRegisters);
    C.txtNotes.Text(mBankLodgement.Notes);
    
    // Change Events
    cboBankAccount_Change();
  }
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "Options":
        // If there is only one bank account, default that now
        if (!C.cboBankAccount.Text() &amp;&amp; mRecord.BankAccounts.length == 1) {
          C.cboBankAccount.Text(mRecord.BankAccounts[0].BankAccountId);
          cboBankAccount_Change();
        }
        break;
    
      case "Items":
        RefreshLodgements();
        break;
        
      default:
        break;
    }
  }

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

  // Special handling for specific tabs
  switch(tabWizard.SelectedTabId()) {
    case "CurrentProcesses":
      mFromRecent = false;
      mBankLodgement = null;
      mLastRefreshParametersJson = null;
      mProcessId = null;
      break;

    case "Items":
      pageItems_Refresh();
      break;
      
    case "Confirm":
      pageConfirm_Refresh();
      break;
      
    default:
      break;
  }
  
  // Update Heading
  frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));

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

  // Resize Wizard
  tabWizard_Resize();
  
  // Focus
  tabWizard.FocusFirst();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters(includeRefreshData) {
  var params = {
    OptionCreate: C.chkOptionCreate.Value(),
    OptionReprint: C.chkOptionReprint.Value(),
  }

  // Create new Lodgement
  if (params.OptionCreate) {
    params.ProcessId = mProcessId;
    params.BankAccountId = C.cboBankAccount.Text();
    params.ServiceId = C.cboService.Text();
    params.DateLodged = C.dateDateLodged.Value();    
    params.Notes = C.txtNotes.Text();
    
    // Cash Registers
    if (mRecord.ShowCashRegisters) {
      params.CashRegisters = C.txtCashRegisters.Text();
    }    
  }

  // Reprint Schedule
  if (params.OptionReprint) {
    if (C.gridBankLodgements.ActiveDataRowListIndex() != -1) {
      var item = mRecord_BankLodgements[C.gridBankLodgements.ActiveDataRowListIndex()];
      params.BankExportId = item.BankExportId;
      params.IncludeReversed = C.chkReprintIncludeReversed.Value();
    }
  }
  
  // Included items from grid
  if (includeRefreshData &amp;&amp; mBankLodgement) {
    params.RefreshData = JSON.stringify(mBankLodgement);
  }

  return params;
}

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

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  if (cmdFinish.text() == "Stop") {
    widget.UI.MsgBoxConfirm("Are you sure you want to stop this process?", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
  } else if (cmdFinish.text() == "Download") {
    Form_ExecuteAction_Download();
  } else {
    tabWizard_Validate(function () {
      var message = "";
      if (C.chkOptionReprint.Value()) {
          message += "Are you sure you want to download the selected Lodgement Schedule?";
      } else {
          message += "Are you sure you want to Lodge the selected Bank Transactions?";
      }

      if (C.chkOptionCreate.Value()) {
        message += "\n\nNOTE: This may take some time. You can close this form at any time and open it again to monitor progress.";
      }
      
      widget.UI.MsgBoxConfirm(message, {}, function () { Form_ExecuteAction_FinishPost(); }, null);
    });
  }
}

function Form_ExecuteAction_FinishPost() {
  mMonitoringExisting = false;

  if (C.chkOptionReprint.Value()) {
    Form_ExecuteAction_Download();
    return;
  }

  pageProgress_Refresh(true);
  
  // Block UI
  widget.UI.Block("Starting Bank Lodgement, please wait...");

  // Finish
  var params = CreateFinishParameters(true);
  widget.GetString("Finish", params,
    function (data) {
      data = JSON.parse(data);
      mRecord_BackgroundProcessStatus = data;
      mProcessId = data.ProcessId;
      
      // Refresh pages
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();
            
      // Update buttons
      tabWizard_UpdateButtons();
      
      // Unblock UI
      widget.UI.Unblock();
      
      pageProgress_Refresh();
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },
    function (error) {
      widget.UI.MsgBoxAlert(error);
      widget.UI.Unblock();
    }
  );
}

function Form_ExecuteAction_Download() {
  if (C.gridBankLodgements.ActiveDataRowListIndex() == -1) {
    widget.UI.MsgBoxAlert("Please select a Lodgement to download.");
    return;
  }  
  
  // Params
  var item = mRecord_BankLodgements[C.gridBankLodgements.ActiveDataRowListIndex()];
  var params = {
    bankExportId: item.BankExportId,
    includeReversed: C.chkReprintIncludeReversed.Value(),
  }    
  
  // Message
  widget.UI.MsgBoxInfo("Your Report for batch '" + item.BankExportId + "' is being prepared, and will be opened (or prompted for download) when ready.");
  
  // Download
  widget.DownloadFile("DownloadSummary", params);
}

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  if (!mProcessId) return;
  
  // Params
  var params = {
    processId: mProcessId,
    lastEventId: mLastEventId,
  }

  // Get Background Process Status
  widget.GetString("GetBackgroundProcessStatus", params,
    function (data) {
      data = JSON.parse(data);
      
      mRecord_BackgroundProcessStatus = data;
      
      pageProgress_Refresh();
      
      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";
      }
      
      switch(Status) {
        case "Cancelled":
          mRecord_BackgroundProcessStatus = null;
          tabWizard_UpdateButtons();
          
          widget.UI.MsgBoxInfo("Bank Lodgement was successfully cancelled.");
          break;
          
        case "InProgressRefreshComplete":
          mBankLodgement = JSON.parse(mRecord_BackgroundProcessStatus.RefreshData);
          mLastRefreshParametersJson = JSON.stringify(CreateFinishParameters(false));
          
          mRecord_BackgroundProcessStatus = null;
          
          tabWizard.SelectedTabId("Items");
          tabWizard_Refresh();
          break;
          
        case "Complete":
        case "CompleteWithErrors":
        case "CompleteWithWarnings":
          // Complete
          mComplete = true;
          mRecord_BackgroundProcessStatus = null;
          
          tabWizard_UpdateButtons();
          
          widget.UI.MsgBoxInfo("Bank Lodgement is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          break;
          
        case "Failed":
          mRecord_BackgroundProcessStatus = null;
          if (mBankLodgement) mComplete = true;
          tabWizard_UpdateButtons();
          widget.UI.MsgBoxAlert("Bank Lodgement failed to complete.");
          break;
          
        default:
          window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 2500);
          widget.NotifyBusy();
      }
    },
    function (error) {
      widget.UI.MsgBoxAlert(error);
      mRecord_BackgroundProcessStatus = null;
      tabWizard_UpdateButtons();
    }
  );
}

// ====================
// pageCurrentProcesses
// ====================
function pageCurrentProcesses_Refresh() {
  mComplete = false;
  
  // Block UI
  widget.UI.Block("Refreshing Recent Bank Lodgements, please wait...");
  
  // Get Current Processes
  widget.GetString("GetCurrentProcesses", {},
    function (data) {
      mRecord_CurrentProcesses = JSON.parse(data);
      
      // Unblock UI
      widget.UI.Unblock();
      
      tabWizard_UpdateButtons();
      gridCurrentProcesses_Refresh();
    },
    function (error) {
      widget.UI.Unblock();
      widget.UI.MsgBoxAlert(error);
    }
  );
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  var isReprint = C.chkOptionReprint.Value();
  
  // Show/hide based on selection
  $("#rowReprintIncludeReversed").toggle(isReprint);
  C.lblBankLodgements.VisibleRow(isReprint);
  C.gridBankLodgements.Visible(isReprint);

  if (isReprint) {
    gridBankLodgements_Refresh();
  }

  tabWizard_UpdateButtons();
}

// ===========
// pageConfirm
// ===========
function pageConfirm_Refresh() {
  var params = CreateFinishParameters(true);
  if (mLastProcessSummaryJson == JSON.stringify(params)) return;

  C.wbProcessSummary.SetContent("", false);
  widget.UI.Block("Getting Summary, please wait...");
  
  // Get Process Summary
  widget.GetString("GetProcessSummary", params,
    function(data) {
      mLastProcessSummaryJson = JSON.stringify(params);
      C.wbProcessSummary.SetContent(data, false);
      widget.UI.Unblock();
    },
    function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();
      
      // Error
      widget.UI.MsgBoxAlert(errorMessage);
      tabWizard_Move(-1);
    }
  );
}

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

  mLastEventId = widget.UI.BuildBackgroundProcessProgress(C.divProgress, clear, mRecord_BackgroundProcessStatus, mLastEventId);
  tabWizard_UpdateButtons()

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

// ===============
// pageItems
// ===============
function pageItems_Refresh() {
  if (mBankLodgement) {
    gridItems_Refresh();
  }
}

// ====================
// gridCurrentProcesses
// ====================
function gridCurrentProcesses_Refresh() {
  if (C.gridCurrentProcesses.ColumnCount() == 0) {
    C.gridCurrentProcesses.AddColumnDrilldown();
    C.gridCurrentProcesses.AddColumnString("StatusText", { caption: "Status" });
    C.gridCurrentProcesses.AddColumnDateTime("CreatedDate", { caption: "Started" });
    C.gridCurrentProcesses.Actions().Define([{ actionId: "Cancel", caption: "Cancel", tooltipText: "Cancel the selected 'Refresh Complete' row", icon: "Trash" }]);
  }

  var found = false;
  if(mRecord_CurrentProcesses) {
    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);
  
  C.gridCurrentProcesses.VirtualDataRefresh(mRecord_CurrentProcesses);
  C.gridCurrentProcesses.ActiveDataRowIndex(-1);
}

function gridCurrentProcesses_Action(actionId) {
  var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];
  switch (actionId.toUpperCase()) {
    case "CANCEL":
      CancelRefreshCompleteBackgroundProcess(item.ProcessId, false, pageCurrentProcesses_Refresh);
      break;

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

function gridCurrentProcesses_AfterRowActivate(e) {
  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];
  e.row.AutoBind(item);
  
  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);
}

// ===================
// gridBankLodgements
// ===================
function gridBankLodgements_Refresh() {
  widget.GetString("GetExistingExports", {}, function(data) {
    mRecord_BankLodgements = JSON.parse(data);

    if (C.gridBankLodgements.ColumnCount() == 0) {
        C.gridBankLodgements.AddColumnString("BankExportId", { caption: "Bank Export Id" });
        C.gridBankLodgements.AddColumnDate("Date", { caption: "Date" });
        C.gridBankLodgements.AddColumnString("BankAccountId", { caption: "Bank Account" });
        C.gridBankLodgements.AddColumnString("BankAccountDescription", { caption: "Bank Account Description" });
        C.gridBankLodgements.AddColumnCurrency("Total", { caption: "Batch Total" });
        C.gridBankLodgements.AddColumnString("CreatedUser", { caption: "Creator" });
        C.gridBankLodgements.AddColumnDateTime("Created", { caption: "Created" });
        C.gridBankLodgements.AddColumnString("Notes", { caption: "Notes" });
    }

    C.gridBankLodgements.VirtualDataRefresh(mRecord_BankLodgements);
    C.gridBankLodgements.ActivateFirstDataRow(true);
  });
}

function gridBankLodgements_RowDrilldown(e) {
  Form_ExecuteAction_Download();
}

function gridBankLodgements_InitialiseRow(e) {
  var item = mRecord_BankLodgements[e.row.listIndex];
  e.row.AutoBind(item);
}

// =========
// gridItems
// =========
function gridItems_Refresh() {
  if (C.gridItems.ColumnCount() == 0) {
    C.gridItems.AddColumnBoolean("Include", { caption: "Include", allowEdit: true });
    C.gridItems.AddColumnCode("AccountId", { caption: "Account" });
    C.gridItems.AddColumnString("AccountName", { caption: "Name" });
    C.gridItems.AddColumnDate("Date", { caption: "Date" });
    C.gridItems.AddColumnString("Reference", { caption: "Reference" });
    C.gridItems.AddColumnCurrency("Value", { caption: "Value" });
    if (mRecord.ShowCashRegisters) {
      C.gridItems.AddColumnString("CashRegisterId", { caption: "Cash Register" });
    }
    C.gridItems.AddColumnString("PaymentMethodId", { caption: "Pay Method" });
    C.gridItems.AddColumnString("PayMethodAccountName", { caption: "Pay Name" });
  }

  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: "Do not Include selected row(s)", icon: "Checkbox_Unchecked" },
    {},
    { actionId: "Download", tooltipText:"Download a Draft Lodgement Schedule", icon: "Print" },
  ]);

  mBankLodgement.Items.GetCacheKey = function (index) {
    return mBankLodgement.Items[index].BankTransactionPk;
  };
  
  mBankLodgement.Items.GetPreviewFetchParameters = function (index) {
    var o = { 
      bankTransactionPk: mBankLodgement.Items[index].BankTransactionPk,
      bankAccountId: mBankLodgement.BankAccountId,
      serviceId: mBankLodgement.ServiceId,
      dateLodged: mBankLodgement.DateLodged,
    };
    return o;
  };

  C.gridItems.VirtualDataRefresh(mBankLodgement.Items);
  C.gridItems.ActivateFirstDataRow();
  divItemsSummary_Refresh();
}

function gridItems_Action(actionId) {
  var indexes;
  switch (actionId.toUpperCase()) {
    case "REFRESH":
      mLastRefreshParametersJson = "";
      RefreshLodgements(true);
      break;
      
    case "DOWNLOAD":
      widget.DownloadFile("PrintDraftSchedule", { refreshData: JSON.stringify(mBankLodgement) });
      break;
      
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridItems.ActiveDataRowListIndex();
      indexes = [];
      for (var i = 0; i &lt; mBankLodgement.Items.length; i++) {
        if ((actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) || (actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex)) {
          indexes.push(i);
        }
      }
      break;
      
    case "SELECTALL":
      indexes = [];
      for(var i = 0; i &lt; mBankLodgement.Items.length; i++) {
        indexes.push(i)
      };
      break;
      
    case "SELECTNONE":
      indexes = [];
      break;
      
    case "SELECTCHECKED":
    case "SELECTUNCHECKED":
      indexes = [];
      for (var i = 0; i &lt; mBankLodgement.Items.length; i++) {
        if ((actionId.toUpperCase() == "SELECTCHECKED" &amp;&amp; mBankLodgement.Items[i].Include) ||
           (actionId.toUpperCase() == "SELECTUNCHECKED" &amp;&amp; !mBankLodgement.Items[i].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++) {
        mBankLodgement.Items[selectedItems[i]].Include = (actionId.toUpperCase() == "CHECK");
      }
      C.gridItems.VirtualDataRefresh(mBankLodgement.Items, true, { retainSelectedRows: true });
      break;
  }

  if (typeof indexes !== 'undefined') C.gridItems.SetSelectedRowIndexes(indexes, true);
  divItemsSummary_Refresh();
}

function gridItems_AfterRowActivate(e) {
  wbItemsSummary_Preview();
}

function gridItems_BeforeCellUpdate(e) {
  var item = mBankLodgement.Items[e.row.listIndex];
  if (e.columnKey == "Include") {
    item.Include = e.newValue;
  }
  divItemsSummary_Refresh();
}

function gridItems_InitialiseRow(e) {
  var item = mBankLodgement.Items[e.row.listIndex];
  e.row.AutoBind(item);
  e.row.cells.AccountId.hyperlink = "app://FormShow?form=Accounts&amp;id=" + widget.UI.HtmlEncode(item.AccountId);
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  if (mRecord_BackgroundProcessStatus) {
    widget.UI.MsgBoxConfirm("The Bank Lodgement 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\nClose this form?", {}, widget.Close);
  } else if (mProcessId &amp;&amp; mBankLodgement) {
    var list = [];
    list.push({ key: "CLOSE", caption: "Suspend and Close", icon: "Window_Close", details: "This will close the wizard but retain the list which can be reviewed later by re-opening this wizard." });
    list.push({ key: "CANCEL", caption: "Close and Cancel", icon: "Trash", details: "This will close the wizard and cancel this process. The list of Bank Transactions to lodge will not be retained." });
    var options = {
      closeOnEscape: true,
      title: "Close Bank Lodgement",
      showClose: true,
    };
    widget.UI.MsgBoxList("Select an option below to close", list, options, function(key) {
      if (key === "CLOSE") {
        tabWizard_Cancel_Save();
      } else if (key === "CANCEL") {
        CancelRefreshCompleteBackgroundProcess(mProcessId, false, widget.Close);
      }
    });
  } else {
    widget.Close();
  }
}

function tabWizard_Cancel_Save() {
  widget.UI.Block("Saving, please wait...");
  var params = CreateFinishParameters(true);
  widget.GetString("UpdateRefreshData", params, widget.Close, function(errorMessage) {
    widget.UI.Unblock();
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function tabWizard_Move(direction) {
  if (direction &gt; 0) {
    tabWizard_Validate(function () { tabWizard_MovePost(direction); });
  } else {
    tabWizard_MovePost(direction);
  }
}

function tabWizard_MovePost(direction) {
  var newTab = tabWizard.SelectedTabIndex();
  var found = false;
  do {
    newTab += direction;
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "Options":
        found = C.chkOptionCreate.Value();
        break;
        
      case "Items":
        found = (C.chkOptionCreate.Value() &amp;&amp; !mRecord.AutoCommit);
        break;
        
      case "Confirm":
        found = (C.chkOptionCreate.Value() &amp;&amp; !mRecord.AutoCommit);
        break;
        
      default:
        found = true;
        break;
    }
    if (found || newTab &lt;= 0 || newTab &gt;= tabWizard.TabCount() -1) {
      break;
    }
  } while (true);
  
  tabWizard_Refresh(newTab);
}

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "Confirm":
      C.wbProcessSummary.ResizeFromParent();
      break;
      
    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  // Back and Next Buttons?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 0);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 2);
  
  // Finish Button
  if (mRecord.AutoCommit &amp;&amp; tabWizard.SelectedTabId() == "Options") {
    cmdFinish.prop("disabled", false);
    cmdNext.prop("disabled", true);
  }
  else {
    cmdFinish.prop("disabled", true);
    cmdFinish.text("Commit");
  }  

  // Reprint or Generate
  if (C.chkOptionReprint.Value()) {
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
    cmdFinish.text("Download");
  } else if (tabWizard.SelectedTabId() == "Confirm") {
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
  }

  // Status
  if (mRecord_BackgroundProcessStatus) {
    cmdNext.prop("disabled", true);
    cmdBack.prop("disabled", true);
    
    switch(mRecord_BackgroundProcessStatus.Status) {
      case "Pending":
      case "InProgress":
        cmdFinish.prop("disabled", true);
        cmdFinish.addClass("negative");
        break;
        
      default:
        cmdFinish.prop("disabled", true);
        cmdFinish.removeClass("negative");
    }
  } else if(cmdFinish.text() != "Download") {
    cmdFinish.removeClass("negative");
  }

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

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

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

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

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

function tabWizard_Validate(validCallback) {
  var Ok = tabWizard.Validate(true);
  
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "Items":
        var found = false;
        if(mBankLodgement &amp;&amp; mBankLodgement.Items) {
            for (var i = 0; i &lt; mBankLodgement.Items.length; i++) {
              if (mBankLodgement.Items[i].Include) {
                found = true;
                break;
              }
            }
        }
        if (!found) {
          Ok = false;
          widget.UI.MsgBoxAlert("You have not selected any items to lodge.");
        }
        break;
        
       default:
        break;
    }
  }

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

    if (params) {
      frmMain.FormDisable("Validating");
      params.pageId = tabWizard.SelectedTabId();
      widget.GetString("WizardValidate", params,
        function (data) { 
          frmMain.FormEnable();
          var o = JSON.parse(data);
          if (o.FailedMessage) {
            widget.UI.MsgBoxAlert(o.FailedMessage);
            if (o.FailedControlId) {
              $("#" + o.FailedControlId).focus();
            }
          } else {
            validCallback();
          }
        },
        function(err) {
          widget.UI.MsgBoxAlert(err);
          frmMain.FormEnable();
        }
      );
    } else {
      validCallback();
    }
  }
}

// =======
// Refresh
// =======
function RefreshLodgements(fromGridAction) {
  if (mLastRefreshParametersJson == JSON.stringify(CreateFinishParameters(false))) {
    return;
  }
  
  frmMain.Visible(false);
  var message = "&lt;p&gt;Click OK to build a list of Bank Transactions for the Lodgement.&lt;/p&gt;";
  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;";
  if (mBankLodgement &amp;&amp; mProcessId) {
    message += "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Transactions have already been retrieved. Continuing will cancel the existing process, and begin a new one.&lt;/p&gt;"
  }

  widget.UI.MsgBoxConfirm(message, { heading: "Refresh Bank Transactions", messageIsHtml: true, icon: "Table|Refresh" },
    function() {
      if (mBankLodgement &amp;&amp; mProcessId) {
        // Cancel existing then start new
        CancelRefreshCompleteBackgroundProcess(mProcessId, fromGridAction, RefreshLodgements_Post, function() {
          tabWizard_Move(-1);
          frmMain.Visible(true);
        });
      } else {
        RefreshLodgements_Post();
      }
    },
    function() {
      if (!fromGridAction) {
        tabWizard_Move(-1);
      }
      frmMain.Visible(true);
    }
  );
}

function RefreshLodgements_Post() {
  mMonitoringExisting = false;
  mBankLodgement = null;
  mRequiresRefresh = false;

  pageProgress_Refresh(true);
  widget.UI.Block("Starting Bank Lodgement Refresh, please wait...");
  
  var params = CreateFinishParameters(true);
  widget.GetString("Refresh", params,
    function (data) {
      frmMain.Visible(true);
      
      data = JSON.parse(data);
      
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();
      
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;
      
      tabWizard_UpdateButtons();
      
      C.wbItemsSummary.CacheClear();
      
      widget.UI.Unblock();
      
      pageProgress_Refresh();
      
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },
    function (error) {
      widget.UI.MsgBoxAlert(error);
      frmMain.Visible(true);
      widget.UI.Unblock();
    }
  );
}

// ==========================================
// Cancel Refresh Complete Background Process
// ==========================================
function CancelRefreshCompleteBackgroundProcess(processId, noPrompt, callback, cancelCallback) {
  var execute = function() {
    widget.UI.Block("Cancelling Background Process, please wait...");
    widget.GetString("CancelBackgroundProcess", { processId: processId }, 
      function() { 
        widget.UI.Unblock();
        if (callback) {
          callback();
        }
      }, 
      function(errorMessage) {
        widget.UI.Unblock();
        widget.UI.MsgBoxAlert(errorMessage);
      }
    );
  };

  if (noPrompt) {
    execute();
  } else {
    widget.UI.MsgBoxConfirm("Are you sure you want to cancel this Background Process?", {}, execute, cancelCallback);
  }
}

// ===============
// divItemsSummary
// ===============
function divItemsSummary_Refresh() {
  var html = "";
  var value = 0;
  var count = 0;
  
  if (mBankLodgement &amp;&amp; mBankLodgement.Items) {
    for (var i = 0; i &lt; mBankLodgement.Items.length; i++) {
      var item = mBankLodgement.Items[i];
      if (item.Include) {
        value += item.Value;
        count++;
      }
    }
  }

  html += "&lt;div class='value-summary'&gt;";
  if (mRequiresRefresh) {
    html += "&lt;div class='refresh-warning'&gt;One or more items has changed - please Refresh the list&lt;/div&gt;";
  }
  html += "&lt;div&gt;Selected Count: &lt;b&gt;" + count + "&lt;/b&gt;&lt;/div&gt;";
  html += "&lt;div style='padding-left:10px'&gt;Selected Value: &lt;b&gt;" + widget.UI.HtmlEncode(widget.FormatCurrency(value, true)) + "&lt;/b&gt;&lt;/div&gt;";
  html += "&lt;/div&gt;";
  C.divItemsSummary.html(html);
  C.divItemsSummary.show();
}

// ==============================
// A Bank Transaction has changed
// ==============================
function BankTransactionChanged(bankTransactionPk) {
  var found = false;
  if (mBankLodgement &amp;&amp; mBankLodgement.Items) {
    for (var i = 0; i &lt; mBankLodgement.Items.length; i++) {
      if (mBankLodgement.Items[i].BankTransactionPk == bankTransactionPk) {
        found = true;
        break;
      }
    }
  }
  
  if (found) {
    mRequiresRefresh = true;
    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) {
    // Set Information from Process
    mProcessId = item.ProcessId;

    // Reset fields
    ResetControls();

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

// Resets the Parameter entry controls
function ResetControls() {
  C.cboBankAccount.Text("");
  C.cboService.Text("");
  C.dateDateLodged.Value(null);
  C.txtNotes.Text("");
  C.txtCashRegisters.Text("");
}

// ==============
// wbItemsSummary
// ==============
function wbItemsSummary_Preview() {
  C.wbItemsSummary.PreviewFromGridCollection(C.gridItems, mBankLodgement.Items, "GetItemPreview");
}

// ========
// txtRange
// ========
function txtRange_ButtonClick(sender, e) {
  if (e.id == "Lookup") {
    widget.UI.Forms.ShowRangeLookupFromStandardRange("CashRegisters", sender.Text(), { caption: "Lookup Cash Registers"},
      function (newRange) {
        sender.Text(newRange);
        sender.Focus();
      }
    );
  }
}

// =========
// chkOption
// =========
function chkOption_Change(sender, e) {
  C.chkOptionCreate.Value(sender == C.chkOptionCreate);
  C.chkOptionReprint.Value(sender == C.chkOptionReprint);
  pageGeneral_Refresh();
}

// ==============
// cboBankAccount
// ==============
function cboBankAccount_Change(sender, e) {
  // Change Handled
  if (e) e.ChangeHandled = true;
  
  // Get the Bank Account
  var bankAccount = mRecord.BankAccounts.GetItem(C.cboBankAccount.Text());
  
  // Update Controls
  if (bankAccount) {
    C.cboService.Text("");
    C.cboService.RefreshFromCollection(bankAccount.ExportServices, "ServiceId", "Description");
    if (bankAccount.ExportServices.length == 1) {
      C.cboService.Text(bankAccount.ExportServices[0].ServiceId);
    }
  } else {
    C.cboService.Text("");
    C.cboService.ListFromCsvString("");
  }
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "BANKTRANSACTIONS.REFRESH":
      if (data) {
        data = JSON.parse(data);
      }
      if (data &amp;&amp; data.bankTransactionPk != 0) {
        BankTransactionChanged(data.bankTransactionPk);
      }
      break;
      
    case "FORMCLOSE":
      tabWizard_Cancel();
      break;
      
    default:
      break;
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <UniqueId>yy5eZpgrc0qRjdRRVKRgZg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>0</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>BankTransaction_Lodgement</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="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="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <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="DesktopMode" type="Boolean">
            <BlankTip />
            <Caption>Running from Desktop?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>