<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-01-29T22:12:41.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-01-29T22:07:25.9920000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-01-29T22:11:31.0940000</UpdatedUtcDate>
    <ScriptId>HWEXPGL</ScriptId>
    <Description>Export General Ledger</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_GLExport
Option Explicit On
Option Strict On

' #################################################################
' Export General Ledger wizard
'
' Version: 1.03 (30/01/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  02/06/2022  ISS      J028576   Created
'    1.01  16/06/2022  ISS      J028844   Limited list of existing GL Export Batches
'    1.02  29/09/2022  ISS      J029737   Implemented widget.UI.BuildBackgroundProcessProgress
'    1.03  30/01/2024  ISS      J032804   Add [SEQ#3] tag for Filename
' #################################################################

' Constants
Private Const FORM_KEY As String = "GLExport"

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

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

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

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

    Case "GetNextBatchId"
      ' Next Batch Id
      Main = GetNextBatchId(returnValue)

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

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

    Case "GetDefaultExportOptions"
      ' Get Default Export Options for an Entity
      Main = GetDefaultExportOptions(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;
'''  Create a finGlExportBatchCreate object.
''' &lt;/summary&gt;
Private Function CreateGlExportBatchCreate(parameters As WizardFinishParameters,
                                           ByRef glExportBatchCreate As finGlExportBatchCreate) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  glExportBatchCreate = finBL.CreateGlExportBatchCreate()

  ' Update
  If Success AndAlso parameters IsNot Nothing Then
    With glExportBatchCreate
      .EntityId = parameters.EntityId
      .GlExportId = parameters.GlExportId
      .GstAccount = parameters.GstAccountId
      .Notes = parameters.Notes

      If finBL.Settings.AddOns.AccountingLedgers AndAlso parameters.ProcessAccountingLedgers Then
        .ProcessAccountingLedgers = True
        .AccountingLedgersDateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.AccountingLedgersDateTo)
      End If

      If parameters.ProcessBankSuspenseItems Then
        .ProcessBankSuspenseItems = True
        .BankSuspenseItemsDateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.BankSuspenseItemsDateTo)
      End If

      If parameters.ProcessBankTransactions Then
        .ProcessBankTransactions = True
        .BankTransactionsDateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.BankTransactionsDateTo)
      End If

      If parameters.ProcessJournalTransactions Then
        .ProcessJournalTransactions = True
        .JournalTransactionsDateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.JournalTransactionsDateTo)
      End If
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create a finGlExportNew object.
''' &lt;/summary&gt;
Private Function CreateGLExportNew(parameters As WizardFinishParameters,
                                   ByRef glExportNew As finGlExportNew) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  glExportNew = finBL.CreateGlExportNew()

  ' Update
  If Success AndAlso parameters IsNot Nothing Then
    With glExportNew
      .AccountStructure = parameters.AccountStructure
      .BatchId = parameters.GlExportId
      .DateClosedTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateClosedTo)
      .ExportType = finBL.Enums.iseGlExportType_FromString(parameters.GlExportType)
      .ExternalUserId = parameters.ExternalUserId
      .ExternalUserPassword = parameters.ExternalUserPassword

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

      .GstAccountId = parameters.GstAccountId
      .IncludeBranch = parameters.IncludeBranch
      .IncludeDepartment = parameters.IncludeDepartment
      .ReExportBatch = (Not parameters.ExportNew)
      .TransactionNarrative = parameters.TransactionNarrative
      .Xero_ManualJournalDraft = parameters.Xero_ManualJournalDraft
    End With
  End If

  Return Success

End Function

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

  Dim GlExportBatchCreate As finGlExportBatchCreate
  Dim GlExportNew As finGlExportNew
  Dim kvl As ISKeyValueList
  Dim ProcessId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Validate

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get finGlExportNew Object and Validate
  If Success AndAlso (Not WizardFinishParameters.ExportNew OrElse Not WizardFinishParameters.FileHold) Then
    If CreateGLExportNew(WizardFinishParameters, GlExportNew) Then
      Success = GlExportNew.Validate(finBL.Enums.iseGlExportType_FromString(WizardFinishParameters.GlExportType))
    Else
      Success = False
    End If
  End If

  ' Queue Background Process
  If Success Then
    If WizardFinishParameters.ExportNew Then
      If CreateGlExportBatchCreate(WizardFinishParameters, GlExportBatchCreate) Then
        Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_GLExportCreate(GlExportBatchCreate, ProcessId, GlExportNew)
      Else
        Success = False
      End If
    Else
      Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_GLExport(GlExportNew, ProcessId)
    End If
  End If

  ' Update User Settings
  If Success AndAlso GlExportBatchCreate IsNot Nothing Then
    kvl = finBL.CreateKeyValueList()
    With kvl
      .SetBoolean("AccountingLedgerTransactions", GlExportBatchCreate.ProcessAccountingLedgers)
      .SetBoolean("BankSuspenseItems", GlExportBatchCreate.ProcessBankSuspenseItems)
      .SetBoolean("BankTransactions", GlExportBatchCreate.ProcessBankTransactions)
      .SetBoolean("JournalTransactions", GlExportBatchCreate.ProcessJournalTransactions)

      If GlExportNew IsNot Nothing Then
        .SetDate("DateClosedTo", GlExportNew.DateClosedTo)
      End If
    End With

    ' Save (ignore error)
    finBL.HtmlWidgetUtilities.UpdateRegistrySettingsUser(FORM_KEY, kvl, True)
  End If

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get 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 ProcessStatusesGLExport As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim StatusInformation As finHtmlWidgetUtilities.JsonProcessStatusInformation
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Export Option Defaults for the selected Entity.
''' &lt;/summary&gt;
Private Function GetDefaultExportOptions(ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim DatabaseName As String
  Dim EntityId As String
  Dim EntityPk As Integer
  Dim ExternalUserId As String
  Dim ExternalUserPassword As String
  Dim GlExportId As String
  Dim IncludeBranch As Boolean
  Dim IncludeDepartment As Boolean
  Dim Success As Boolean
  Dim NewGLExport As Boolean

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    EntityId = .GetString("EntityId")
    GlExportId = .GetString("GlExportId")
    NewGLExport = .GetBoolean("NewGLExport")
  End With

  ' Get Defaults
  If NewGLExport Then
    ' New Batch
    If Len(EntityId) &lt;&gt; 0 AndAlso finBL.Entities.Exists(EntityId) Then
      With finBL.Entities(EntityId)
        DatabaseName = .GlDatabaseNameResolved
        ExternalUserId = .GlExternalUserIdResolved
        ExternalUserPassword = .GlExternalUserPasswordResolved
        IncludeBranch = .GlExportIncludeBranchResolved
        IncludeDepartment = .GlExportIncludeDepartmentResolved
      End With
    End If
  ElseIf Len(GlExportId) &lt;&gt; 0 Then
    ' Existing Batch
    If finBL.AccountingInterface.GetEntityFromGlExportId(GlExportId, EntityPk) Then
      If finBL.Entities.ExistsPk(EntityPk) Then
        With finBL.Entities.ItemByPk(EntityPk)
          DatabaseName = .GlDatabaseNameResolved
          ExternalUserId = .GlExternalUserIdResolved
          ExternalUserPassword = .GlExternalUserPasswordResolved
          IncludeBranch = .GlExportIncludeBranchResolved
          IncludeDepartment = .GlExportIncludeDepartmentResolved
        End With
      End If
    Else
      Success = False
    End If
  End If

  ' Create Json Object
  If Success Then
    Data = New With {
      .DatabaseName = DatabaseName,
      .ExternalUserId = ExternalUserId,
      .ExternalUserPassword = ExternalUserPassword,
      .IncludeBranch = IncludeBranch,
      .IncludeDepartment = IncludeDepartment
    }
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, 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 dv As DataView
  Dim ExportType As String
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim GlExportNew As finGlExportNew
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim ProcessStatusesGlExport As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Row As DataRow
  Dim StatusInformation As finHtmlWidgetUtilities.JsonProcessStatusInformation
  Dim Success As Boolean
  Dim UserSettings As ISKeyValueList

  ' Assume Success
  Success = True

  ' Initialise

  ' Validate
  If finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  ElseIf Not finBL.Settings.UseGeneralLedger Then
    Success = False
    finBL.Error.ErrorBegin("This database is not configured for General Ledger use.")
  ElseIf Not finBL.Settings.UseGeneralLedgerNewInterface Then
    Success = False
    finBL.Error.ErrorBegin("Only the new General Ledger interface is supported via HTML Widget / finPOWER Connect Cloud.")
  ElseIf Not finBL.SettingsUser.Validate() Then
    Success = False
  ElseIf Not finBL.Elements.Validate(True) Then
    Success = False
  ElseIf Not finBL.BankAccounts.Validate(True) Then
    Success = False
  ElseIf Not finBL.AccountTypes.Validate(True) Then
    Success = False
  End If

  ' Get finGlExportNew Object
  If Success Then
    Success = CreateGLExportNew(Nothing, GlExportNew)
  End If

  ' Get User Settings
  If Success Then
    UserSettings = finBL.HtmlWidgetUtilities.GetRegistrySettingsUser(FORM_KEY)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      If finBL.Settings.AddOns.AccountingLedgers Then
        .AccountingLedgerTransactionsDateToDefault = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.Runtime.DateUtilities.EndOfPreviousMonth(finBL.TimeZoneFunctions.GetCurrentDatabaseDate()))
      End If
      If finBL.Entities.Count = 1 Then
        .EntityId = finBL.Entities.ItemByIndex(0).EntityId
      Else
        .EntityId = finBL.SettingsUser.DefaultEntityIdResolved
      End If

      ' Defaults from User Settings
      If finBL.Settings.AddOns.AccountingLedgers Then
        .AccountingLedgerTransactions = UserSettings.GetBoolean("AccountingLedgerTransactions")
      Else
        .AccountingLedgerTransactions = False
      End If
      .BankSuspenseItems = UserSettings.GetBoolean("BankSuspenseItems")
      .BankTransactions = UserSettings.GetBoolean("BankTransactions")
      .JournalTransactions = UserSettings.GetBoolean("JournalTransactions")
      .DateClosedTo = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(UserSettings.GetDate("DateClosedTo"))

      ' Defaults
      .GlDatabaseName = finBL.Settings.GlDatabaseName
      .GlExportAccountStructure = finBL.Settings.GlExportAccountStructure
      .GlExportGstAccountId = finBL.Settings.GlExportGstAccountId
      .GlExportIncludeBranch = finBL.Settings.GlExportIncludeBranch
      .GlExportIncludeDepartment = finBL.Settings.GlExportIncludeDepartment
      .GlExportTransactionNarrative = finBL.Settings.GlExportTransactionNarrative
      .GlExportType = finBL.Settings.GlExportTypeText
      .GlExternalUserId = finBL.Settings.GlExternalUserIdResolved
      .GlExternalUserPassword = finBL.Settings.GlExternalUserPassword
      .GlFileName = finBL.Settings.GlFileName

      ' Lists
      ' GL Exports
      If finBL.AccountingInterface.GetExistingGlExportBatchesDataView(dv, 1000) Then
        For Each Row In dv.ToTable().Rows
          .ExistingBatches.Add(New ExistingBatch(Row))
        Next
      End If
      
      ' Export Types
      For Each ExportType In finBL.Enums.iseGlExportType_GetList(False, True)
        .ExportTypes.Add(New ExportType(finBL.Enums.iseGlExportType_FromString(ExportType)))
      Next

      ' Configuration

      ' Advanced Sections
      .ShowNotes = mCombinedParameters.GetString("ShowNotes") : If Len(.ShowNotes) = 0 Then .ShowNotes = "Advanced"

      ' Has Advanced?
      .PageGeneralHasAdvanced = (.ShowNotes = "Advanced")

      ' Configuration
      .AddonsAccountingLedgers = finBL.Settings.AddOns.AccountingLedgers
      .AddonsEntity = finBL.Settings.AddOns.Entity
      .ReadOnly = finBL.Database.IsReadOnly
      .UseGst = finBL.Settings.UseGst
      .GlAllowUserToModifySettings = finBL.Settings.GlAllowUserToModifySettings

      ' Form Heading
      .FormHeading = ScriptInfo.ScriptCaption
      If Len(.FormHeading) = 0 Then .FormHeading = "Export General Ledger"
    End With
  End If

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

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

    FormInitialisationInfo.CurrentProcesses = ProcessStatuses
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Next Batch Id.
''' &lt;/summary&gt;
Private Function GetNextBatchId(ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim GlExportBatchCreate As finGlExportBatchCreate
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Create Object
  Success = CreateGlExportBatchCreate(Nothing, GlExportBatchCreate)

  ' Get Next Id
  If Success Then
    GlExportBatchCreate.GLExportIdDefault()
  End If

  ' Build Object
  If Success Then
    Data = New With {
      .NextGlExportId = GlExportBatchCreate.GlExportId
    }
  End If

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

  Return Success

End Function

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

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  Dim GlExportBatchCreate As finGlExportBatchCreate
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim GlExportId As String
  Dim PageId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

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

  ' Validate Page
  If Success Then
    Select Case PageId
      Case "General"
        ' General - only runs for new GL Exports (i.e. not existing previous)
        Success = CreateGlExportBatchCreate(WizardFinishParameters, GlExportBatchCreate)

        ' GL Export Id
        If Success Then
          If finBL.AccountingInterface.GlExportExists(GlExportBatchCreate.GlExportId) Then
            FailedControlId = "txtGlExportId"
            FailedMessage = String.Format("GL Export Batch '{0}' already exists in this database.", GlExportBatchCreate.GlExportId)
          End If
        End If

        ' Accounting Ledgers
        If Success AndAlso Len(FailedMessage) = 0 Then
          If finBL.Settings.AddOns.AccountingLedgers AndAlso GlExportBatchCreate.ProcessAccountingLedgers Then
            If GlExportBatchCreate.AccountingLedgersDateTo &gt; finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(60) Then
              FailedControlId = "dateAccountingLedgerTransactionsDateTo"
              FailedMessage = "Account Ledgers cannot be processed more than 60 days in advance."
            End If
          End If
        End If

      Case "ExportType"
        ' Export Type - only runs for new GL Exports (i.e. not existing previous)
        If Len(GlExportId) = 0 Then
          FailedMessage = "A GL Export Id must be specified."
        ElseIf finBL.AccountingInterface.GlExportExists(GlExportId) Then
          FailedMessage = String.Format("GL Export Batch '{0}' already exists. Either Re-Export, or create a new Export on the General page of this wizard.", GlExportId)
        End If

    End Select
  End If

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

  Return Success

End Function



''' &lt;summary&gt;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

  ' Current Processes
  Public CurrentProcesses As New List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)

  ' Record
  Public AccountingLedgerTransactionsDateToDefault As Date
  Public EntityId As String

  Public AccountingLedgerTransactions As Boolean
  Public BankSuspenseItems As Boolean
  Public BankTransactions As Boolean
  Public DateClosedTo As Date?
  Public JournalTransactions As Boolean

  Public GlDatabaseName As String
  Public GlExportAccountStructure As String
  Public GlExportGstAccountId As String
  Public GlExportIncludeBranch As Boolean
  Public GlExportIncludeDepartment As Boolean
  Public GlExportTransactionNarrative As String
  Public GlExportType As String
  Public GlExternalUserId As String
  Public GlExternalUserPassword As String
  Public GlFileName As String

  ' Lists
  Public ExistingBatches As New List(Of ExistingBatch)
  Public ExportTypes As New List(Of ExportType)

  ' Advanced
  Public PageGeneralHasAdvanced As Boolean
  Public ShowNotes As String

  ' Configuration
  Public AddonsAccountingLedgers As Boolean
  Public AddonsEntity As Boolean
  Public FormHeading As String
  Public GlAllowUserToModifySettings As Boolean
  Public [ReadOnly] As Boolean
  Public UseGst As Boolean

End Class



''' &lt;summary&gt;
'''  Existing Batch.
''' &lt;/summary&gt;
Public Class ExistingBatch

  Public GLExportId As String
  Public BatchDate As Date
  Public Creator As String
  Public Notes As String

  Public Sub New(row As DataRow)

    Me.GLExportId = finBLShared.Database.GetFieldString(row!GlExportId)
    Me.BatchDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(finBLShared.Database.GetFieldDate(row!Date))
    Me.Creator = finBLShared.Database.GetFieldString(row!CreatedUser)
    Me.Notes = finBLShared.Database.GetFieldString(row!Notes)

  End Sub

End Class



''' &lt;summary&gt;
'''  Export Type.
''' &lt;/summary&gt;
Public Class ExportType

  Public ConnectsToExternalDatabase As Boolean
  Public DefaultFileExtension As String
  Public ExportType As String
  Public ExportTypeText As String
  Public ExternalApplicationName As String
  Public IsFileBasedExporter As Boolean
  Public RequiresExternalApplicationCredentials As Boolean
  Public SupportsBranches As Boolean
  Public SupportsDepartments As Boolean
  Public SupportsWebServices As Boolean
  Public SupportsWebServicesMessage As String
  Public UsesAccountStructure As Boolean
  Public UsesManualJournalDraft As Boolean
  Public UsesTransactionNarrative As Boolean

  Public Sub New(type As iseGlExportType)

    Dim ExportTypeProperties As ISGlExportTypeProperties

    ' Get Properties
    ExportTypeProperties = finBLShared.AccountingInterface.GetExportTypeProperties(type)

    ' Set Properties
    Me.ExportType = type.ToString()
    Me.ExportTypeText = finBLShared.Enums.iseGlExportType_ToString(type)

    ' File / Database Exports
    If ExportTypeProperties.IsFileBasedExporter Then
      Me.IsFileBasedExporter = True
      Me.ConnectsToExternalDatabase = ExportTypeProperties.ConnectsToExternalDatabase
      Me.ExternalApplicationName = ExportTypeProperties.ExternalDatabaseApplicationName
    Else
      Me.ConnectsToExternalDatabase = False
      Me.IsFileBasedExporter = False
      Me.ExternalApplicationName = ""
    End If

    ' Other
    Me.DefaultFileExtension = ExportTypeProperties.DefaultFileExtension
    Me.RequiresExternalApplicationCredentials = ExportTypeProperties.RequiresExternalApplicationCredentials
    Me.SupportsBranches = ExportTypeProperties.SupportsBranches
    Me.SupportsDepartments = ExportTypeProperties.SupportsDepartments
    Me.SupportsWebServices = ExportTypeProperties.SupportsWebServices
    Me.UsesAccountStructure = (ExportTypeProperties.UsesAccountStructure AndAlso Not finBLShared.Settings.UseGeneralLedgerNewInterface)
    Me.UsesManualJournalDraft = (type = iseGlExportType.Xero)
    Me.UsesTransactionNarrative = ExportTypeProperties.UsesTransactionNarrative

    ' Not Supported
    If Not Me.SupportsWebServices Then
      Me.SupportsWebServicesMessage = String.Format("{0} is not supported via Web Services. Please contact your Administrator for more information on this Export Type.", finBLShared.HtmlEncode(Me.ExportTypeText))
    End If

  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

  ' General
  Public AccountingLedgersDateTo As Date
  Public BankSuspenseItemsDateTo As Date?
  Public BankTransactionsDateTo As Date?
  Public EntityId As String
  Public ExportNew As Boolean
  Public GlExportId As String
  Public JournalTransactionsDateTo As Date?
  Public Notes As String
  Public ProcessAccountingLedgers As Boolean
  Public ProcessBankSuspenseItems As Boolean
  Public ProcessBankTransactions As Boolean
  Public ProcessJournalTransactions As Boolean

  ' Export Type
  Public AccountStructure As String
  Public DateClosedTo As Date?
  Public ExternalUserId As String
  Public ExternalUserPassword As String
  Public FileName As String
  Public FileDownload As Boolean
  Public FileLocation As Boolean
  Public FileHold As Boolean
  Public GlExportType As String
  Public GstAccountId As String
  Public IncludeBranch As Boolean
  Public IncludeDepartment As Boolean
  Public TransactionNarrative As String
  Public Xero_ManualJournalDraft As Boolean

End Class



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

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

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

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

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "GLExport".</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 General Ledger Exports you have processed."&gt;Recent General Ledger Exports&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Create new GL Batch to Export or select existing GL Export Batch."&gt;General&lt;/li&gt;
        &lt;li tabId="ExportType" tooltipText="Enter the Export Type and any options."&gt;Export Type&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

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

    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&gt;
          &lt;table class="is-form"&gt;
            &lt;colgroup&gt;
              &lt;col style="width:8em" /&gt;
              &lt;col /&gt;
            &lt;/colgroup&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblExportOptionNew"&gt;Indicate whether to create a New General Ledger Batch&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewGLBatch" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblExportOptionExisting"&gt;Indicate whether to Re-Export a General Ledger Batch&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkReExportGLBatch" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblGlExportId"&gt;Enter the Export Batch Id to identify this Export&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtGlExportId"&gt;GL Export Id:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtGlExportId" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblEntity"&gt;Select the Entity to Export&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboEntity"&gt;Entity:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboEntity" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblExportOptions"&gt;Export Options&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkProcessBankTransactions" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th class="indent1"&gt;&lt;label for="dateBankTransactionsDateTo"&gt;Dated&amp;nbsp;on/before:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateBankTransactionsDateTo" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkProcessJournalTransactions" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th class="indent1"&gt;&lt;label for="dateJournalTransactionsDateTo"&gt;Dated&amp;nbsp;on/before:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateJournalTransactionsDateTo" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkProcessAccountingLedgerTransactions" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th class="indent1"&gt;&lt;label for="dateAccountingLedgerTransactionsDateTo"&gt;Dated&amp;nbsp;on/before:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateAccountingLedgerTransactionsDateTo" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th class="indent1" colspan="2"&gt;&lt;div id="divAccountingLedgerTransactionsDateTo" class="is-info-text info small"&gt;Non-Bank transactions dated on or prior to this date will be re-dated. This prevents Transactions being posted into closed off Accounting periods.&lt;/div&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkProcessBankSuspenseItems" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th class="indent1"&gt;&lt;label for="dateBankSuspenseItemsDateTo"&gt;Dated&amp;nbsp;on/before:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateBankSuspenseItemsDateTo" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr advancedId="Notes"&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblNotes"&gt;Enter any Notes you wish to record against this Export&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr advancedId="Notes"&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="lblExistingBatches"&gt;Existing General Ledger Batches&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/div&gt;

        &lt;!-- Existing Batches --&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1280px; margin-left:8px"&gt;
          &lt;div id="gridExistingBatches" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Export Type --&gt;
    &lt;div id="pageExportType"&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="lblExportType"&gt;Enter the Type and Location of the file you wish to Export.&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboGLExportType"&gt;Export Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboGLExportType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="divSupportsWebServicesMessage" class="is-info-text info warning"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtDatabaseName"&gt;Database Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDatabaseName" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCredentials"&gt;Enter credentials&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtExternalUserId"&gt;User Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtExternalUserId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtExternalUserPassword"&gt;Password:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtExternalUserPassword" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOtherOptions"&gt;Options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateDateClosedTo"&gt;Closed to Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateDateClosedTo" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAccountStructure"&gt;Account Structure:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAccountStructure" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeBranch" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeDepartment" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtTransactionNarrative"&gt;Summ. Narrative:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtTransactionNarrative" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGstAccountId"&gt;GST Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGstAccountId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkXero_ManualJournalDraft" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&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="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

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

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

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

  //   General
  lblExportOptionNew: null,
  chkNewGLBatch: null,

  lblExportOptionExisting: null,
  chkReExportGLBatch: null,

  lblGlExportId: null,
  txtGlExportId: null,

  lblEntity: null,
  cboEntity: null,

  lblExportOptions: null,
  chkProcessBankTransactions: null,
  dateBankTransactionsDateTo: null,
  chkProcessJournalTransactions: null,
  dateJournalTransactionsDateTo: null,
  chkProcessAccountingLedgerTransactions: null,
  dateAccountingLedgerTransactionsDateTo: null,
  divAccountingLedgerTransactionsDateTo: null,
  chkProcessBankSuspenseItems: null,
  dateBankSuspenseItemsDateTo: null,

  lblNotes: null,
  txtNotes: null,

  lblExistingBatches: null,
  gridExistingBatches: null,

  //   Export Type
  lblExportType: null,
  cboGLExportType: null,
  divSupportsWebServicesMessage: null,
  txtDatabaseName: null,

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

  lblCredentials: null,
  txtExternalUserId: null,
  txtExternalUserPassword: null,

  lblOtherOptions: null,
  dateDateClosedTo: null,
  txtAccountStructure: null,
  chkIncludeBranch: null,
  chkIncludeDepartment: null,
  txtTransactionNarrative: null,
  txtGstAccountId: null,
  chkXero_ManualJournalDraft: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;
var cmdAdvanced;

// Other
var mAdvancedVisible = false;
var mComplete = false;
var mFromRecent = false;
var mMonitoringExisting = false;
var mProcessId;
var mExportType;
var mEntityChanged;

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

  // Controls
  //   General
  C.lblExportOptionNew = widget.UI.Label("lblExportOptionNew", {});
  C.chkNewGLBatch = widget.UI.RadioButton("chkNewGLBatch", {
    caption: "Create a new General Ledger Batch?",
    captionWrap: true,

    onChange: ExportOption_Change,
  });

  C.lblExportOptionExisting = widget.UI.Label("lblExportOptionExisting", {});
  C.chkReExportGLBatch = widget.UI.RadioButton("chkReExportGLBatch", {
    caption: "Re-Export a General Ledger Batch?",
    captionWrap: true,

    onChange: ExportOption_Change,
  });

  C.lblGlExportId = widget.UI.Label("lblGlExportId", {});
  C.txtGlExportId = widget.UI.TextBox("txtGlExportId", {
    allowBlank: false,
    maxLength: 20,

    onButtonClick: txtGlExportId_ButtonClick,
  });
  C.txtGlExportId.ButtonsDefine([{id: "GetNextGLExportId", icon: "Refresh", tooltipText: "Get next GL Export Id" }]);

  C.lblEntity = widget.UI.Label("lblEntity", {});
  C.cboEntity = widget.UI.DBCombo("cboEntity", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,

    onChange: cboEntity_Change,
  });

  C.lblExportOptions = widget.UI.Label("lblExportOptions", {});
  C.chkProcessBankTransactions = widget.UI.CheckBox("chkProcessBankTransactions", {
    caption: "Transfer Bank Transactions?",

    onChange: ExportOptionsNew_Change,
  });
  C.dateBankTransactionsDateTo = widget.UI.DateBox("dateBankTransactionsDateTo", {});
  C.chkProcessJournalTransactions = widget.UI.CheckBox("chkProcessJournalTransactions", {
    caption: "Transfer Journal Transactions?",

    onChange: ExportOptionsNew_Change,
  });
  C.dateJournalTransactionsDateTo = widget.UI.DateBox("dateJournalTransactionsDateTo", {});
  C.chkProcessAccountingLedgerTransactions = widget.UI.CheckBox("chkProcessAccountingLedgerTransactions", {
    caption: "Transfer Accounting Ledger Transactions?",

    onChange: ExportOptionsNew_Change,
  });
  C.dateAccountingLedgerTransactionsDateTo = widget.UI.DateBox("dateAccountingLedgerTransactionsDateTo", {
    allowBlank: false,
  });
  C.divAccountingLedgerTransactionsDateTo = $("#divAccountingLedgerTransactionsDateTo");
  C.chkProcessBankSuspenseItems = widget.UI.CheckBox("chkProcessBankSuspenseItems", {
    caption: "Transfer Bank Suspense Items?",

    onChange: ExportOptionsNew_Change,
  });
  C.dateBankSuspenseItemsDateTo = widget.UI.DateBox("dateBankSuspenseItemsDateTo", {});

  C.lblNotes = widget.UI.Label("lblNotes", {});
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 6,
  });

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

  //   Export Type
  C.lblExportType = widget.UI.Label("lblExportType", {});
  C.cboGLExportType = widget.UI.ComboBox("cboGLExportType", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_25,

    onChange: cboGLExportType_Change,
  });
  C.divSupportsWebServicesMessage = $("#divSupportsWebServicesMessage");
  C.txtDatabaseName = widget.UI.TextBox("txtDatabaseName", {
    allowBlank: false,
    maxLength: 255,
  });

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

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

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

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

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

  C.lblCredentials = widget.UI.Label("lblCredentials", {});
  C.txtExternalUserId = widget.UI.TextBox("txtExternalUserId", {
    allowBlank: false,
    maxLength: 60,
    width: widget.UI.FIELD_WIDTH_CODE_25,
  });
  C.txtExternalUserPassword = widget.UI.TextBox("txtExternalUserPassword", {
    maxLength: 60,
    width: widget.UI.FIELD_WIDTH_CODE_25,
  });

  C.lblOtherOptions = widget.UI.Label("lblOtherOptions", {});
  C.dateDateClosedTo = widget.UI.DateBox("dateDateClosedTo", {});
  C.txtAccountStructure = widget.UI.TextBox("txtAccountStructure", {
    maxLength: 60,
  });
  C.chkIncludeBranch = widget.UI.CheckBox("chkIncludeBranch", {
    caption: "Include Branch?",
  });
  C.chkIncludeDepartment = widget.UI.CheckBox("chkIncludeDepartment", {
    caption: "Include Department?",
  });
  C.txtTransactionNarrative = widget.UI.TextBox("txtTransactionNarrative", {
    maxLength: 60,
  });
  C.txtGstAccountId = widget.UI.TextBox("txtGstAccountId", {
    maxLength: 60,
    width: widget.UI.FIELD_WIDTH_CODE_25,
  });
  C.chkXero_ManualJournalDraft = widget.UI.CheckBox("chkXero_ManualJournalDraft", {
    caption: "Create Manual Journals with a status of Draft?",
    captionWrap: true,
  });

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

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

    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

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

    onInitialiseRow: gridExistingBatches_InitialiseRow,
    onRowDrilldown: gridExistingBatches_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"); });

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

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

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  mEntityChanged = true;

  C.chkNewGLBatch.Value(true);
  C.chkReExportGLBatch.Value(false);
  C.chkFileDownload.Value(true);
  C.chkFileLocation.Value(false);
  C.chkFileHold.Value(false);

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_ExistingBatches = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mExportType = 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_ExistingBatches = mRecord.ExistingBatches;
      mRecord_CurrentProcesses = mRecord.CurrentProcesses;

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

      // 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 General Ledger Exports 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 General Ledger Export.", { heading: "General Ledger Export Still Running", icon: "MonitorCategory"} );
      }
    },

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

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

    //   General
    if (mRecord.EntityId) C.cboEntity.Text(mRecord.EntityId);
    if (mRecord.AccountingLedgerTransactionsDateToDefault) C.dateAccountingLedgerTransactionsDateTo.Value(mRecord.AccountingLedgerTransactionsDateToDefault);
    C.chkProcessBankTransactions.Value(mRecord.BankTransactions);
    C.chkProcessJournalTransactions.Value(mRecord.JournalTransactions);
    C.chkProcessAccountingLedgerTransactions.Value(mRecord.AccountingLedgerTransactions);
    C.chkProcessBankSuspenseItems.Value(mRecord.BankSuspenseItems);

    //   Export Type
    C.cboGLExportType.Text(mRecord.GlExportType);
    C.txtFileName.Text(mRecord.GlFileName);
    C.txtDatabaseName.Text(mRecord.GlDatabaseName);

    C.txtExternalUserId.Text(mRecord.GlExternalUserId);
    C.txtExternalUserPassword.Text(mRecord.GlExternalUserPassword);

    C.dateDateClosedTo.Value(mRecord.DateClosedTo);
    C.txtAccountStructure.Text(mRecord.GlExportAccountStructure);
    C.chkIncludeBranch.Value(mRecord.GlExportIncludeBranch);
    C.chkIncludeDepartment.Value(mRecord.GlExportIncludeDepartment);
    C.txtTransactionNarrative.Text(mRecord.GlExportTransactionNarrative);
    C.txtGstAccountId.Text(mRecord.GlExportGstAccountId);
  }

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

  // Update fields
  Fields_Update();

  // Update Controls
  pageGeneral_Refresh();
  cboGLExportType_Change();
  FileLocation_Change();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  // Not used by this HTML Widget
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    widget.SetHeading(mRecord.FormHeading);
  }

  // Information Lists

  // Lists
  if (mRecord) {
    C.cboEntity.RefreshFromStandardRange("Entities");
    C.cboGLExportType.ListFromCollection(mRecord.ExportTypes, "ExportTypeText");
  }

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

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

    // Transaction Narrative
    var o = [];
    o.push({caption: "GlExportId", value: "[GlExportId]"});
    C.txtTransactionNarrative.TagsListDefine(o);

    // User cannot modify settings
    if (!mRecord.GlAllowUserToModifySettings) {
      C.cboGLExportType.ReadOnly(true);
      C.txtFileName.ReadOnly(true);
      C.txtDatabaseName.ReadOnly(true);
      C.txtExternalUserId.ReadOnly(true);
      C.txtExternalUserPassword.ReadOnly(true);
      C.dateDateClosedTo.ReadOnly(true);
      C.txtTransactionNarrative.ReadOnly(true);
      C.txtAccountStructure.ReadOnly(true);
      C.chkIncludeBranch.ReadOnly(true);
      C.chkIncludeDepartment.ReadOnly(true);
      C.txtGstAccountId.ReadOnly(true);
      C.chkXero_ManualJournalDraft.ReadOnly(true);
    }

    // Initialise Advanced
    AdvancedInitialise();
  }

  // Auto-format
  tabWizard.AutoFormatPage();

  // Update Buttons
  tabWizard_UpdateButtons();

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) frmMain.FormReadOnly(C, true);

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

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

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

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

  // Finish Button
  cmdFinish.prop("disabled", (mExportType &amp;&amp; !mExportType.SupportsWebServices) || tabWizard.SelectedTabId() != "ExportType" || (mRecord &amp;&amp; mRecord.ReadOnly));

  // Page Exceptions
  if (mRecord_BackgroundProcessStatus) {
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
    cmdBack.prop("disabled", true);
    cmdHistory.prop("disabled", true);

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

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

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

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // General
      for(var k in C) {
        if (k.startsWith("txtRange")) {
          C[k].WidthResizeFromParent();
        }
      }
      break;

    default:
      break;
  }
}

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

// ===========
// Refresh Tab
// ===========
function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "ExportType":
        pageExportType_Refresh();
        break;

      default:
        break;
    }
  }

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

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "CurrentProcesses":
      // Reset from recent flag
      mFromRecent = false;
      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;
  }
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        if (C.chkNewGLBatch.Value()) {
          if (!C.chkProcessAccountingLedgerTransactions.Value() &amp;&amp; !C.chkProcessBankSuspenseItems.Value() &amp;&amp; !C.chkProcessBankTransactions.Value() &amp;&amp; !C.chkProcessJournalTransactions.Value()) {
            Ok = false;
            widget.UI.MsgBoxAlert("At least one Export Option must be selected.", {}, function() { C.chkProcessBankTransactions.Focus(); });
          }
        }
        break;

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

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (C.chkNewGLBatch.Value()) {
          params = CreateFinishParameters();
        }
        break;

      case "ExportType":
        if (C.chkNewGLBatch.Value()) {
          var params = {
            glExportId: C.txtGlExportId.Text(),
          }
        }
        break;

      default:
        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":
      case "ExportType":
        // General
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

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

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

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  if (cmdFinish.text() == "Stop") {
    // Stop Process?
    widget.UI.MsgBoxConfirm("Are you sure you want to stop this process?\n\nNOTE: This may not take affect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
  }
  else {
    // Validate
    tabWizard_Validate(function () {
      // Confirmation Message
      var message = "";

      // Build Message
      message += "Are you sure you want to Export the General Ledger?";

      // Background Process
      message += "\n\nNOTE: You can close this form and any time and open it again to monitor the status of this process.";

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

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

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting General Ledger Export, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();

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

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

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

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

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

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

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  // 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("General Ledger Export was successfully cancelled.");
          break;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("General Ledger Export is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          break;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("General Ledger Export failed to complete.");
          break;

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

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

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

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

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

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Hide by default
  C.lblGlExportId.VisibleRow(false);
  C.txtGlExportId.VisibleRow(false);

  C.lblEntity.VisibleRow(false);
  C.cboEntity.VisibleRow(false);

  C.lblExportOptions.VisibleRow(false);
  C.chkProcessBankTransactions.VisibleRow(false);
  C.chkProcessJournalTransactions.VisibleRow(false);
  C.chkProcessAccountingLedgerTransactions.VisibleRow(false);
  C.chkProcessBankSuspenseItems.VisibleRow(false);

  C.lblNotes.VisibleRow(false);
  C.txtNotes.VisibleRow(false);

  C.lblExistingBatches.VisibleRow(false);
  C.gridExistingBatches.Visible(false);

  // Update Controls
  if (C.chkNewGLBatch.Value()) {
    // New Batch
    C.lblGlExportId.VisibleRow(true);
    C.txtGlExportId.VisibleRow(true);

    C.lblEntity.VisibleRow(mRecord.AddonsEntity);
    C.cboEntity.VisibleRow(mRecord.AddonsEntity);

    C.lblExportOptions.VisibleRow(true);
    C.chkProcessBankTransactions.VisibleRow(true);
    C.chkProcessJournalTransactions.VisibleRow(true);
    C.chkProcessAccountingLedgerTransactions.VisibleRow(mRecord.AddonsAccountingLedgers);
    C.chkProcessBankSuspenseItems.VisibleRow(true);

    if (mRecord.ShowNotes.toUpperCase() != "FALSE") {
      C.lblNotes.VisibleRow(true);
      C.txtNotes.VisibleRow(true);
    }
  }
  else if (C.chkReExportGLBatch.Value()) {
    // Re-Export existing Batch
    C.lblExistingBatches.VisibleRow(true);
    C.gridExistingBatches.Visible(true);

    // Update Grid
    gridExistingBatches_Refresh();
  }

  // Update Controls
  ExportOptionsNew_Change();

  // Update Buttons
  tabWizard_UpdateButtons();
}

// ==============
// pageExportType
// ==============
function pageExportType_Refresh() {
  // Hide all
  C.txtDatabaseName.VisibleRow(false);
  C.divSupportsWebServicesMessage.hide();

  C.lblFileName.VisibleRow(false);
  C.chkFileDownload.VisibleRow(false);
  C.chkFileLocation.VisibleRow(false);
  C.chkFileHold.VisibleRow(false);
  C.txtFileName.VisibleRow(false);
  C.divFileName.hide();

  C.lblCredentials.VisibleRow(false);
  C.txtExternalUserId.VisibleRow(false);
  C.txtExternalUserPassword.VisibleRow(false);

  C.lblOtherOptions.VisibleRow(false);
  C.dateDateClosedTo.VisibleRow(false);
  C.txtAccountStructure.VisibleRow(false);
  C.chkIncludeBranch.VisibleRow(false);
  C.chkIncludeDepartment.VisibleRow(false);
  C.txtTransactionNarrative.VisibleRow(false);
  C.txtGstAccountId.VisibleRow(false);
  C.chkXero_ManualJournalDraft.VisibleRow(false);

  // Get Defaults for Entity (only if Entity has changed)
  if (mEntityChanged) {
    mEntityChanged = false;

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

    // Params
    var params = {
      entityId: C.cboEntity.Text(),
      newGLExport: C.chkNewGLBatch.Value(),
    }

    // Existing
    if (C.chkReExportGLBatch.Value() &amp;&amp; C.gridExistingBatches.ActiveDataRowListIndex() != -1) {
      var item = mRecord_ExistingBatches[C.gridExistingBatches.ActiveDataRowListIndex()];
      params.GlExportId = item.GLExportId;
    }

    // Get Defaults
    widget.GetString("GetDefaultExportOptions", params, pageExportType_Refresh_Done, function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();

      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }
  else {
    pageExportType_Refresh_Done();
  }
}

function pageExportType_Refresh_Done(data) {
  var toolTip = "";

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

  // Set Defaults
  if (data) {
    if (data.DatabaseName) C.txtDatabaseName.Text(data.DatabaseName);
    if (data.ExternalUserId) C.txtExternalUserId.Text(data.ExternalUserId);
    if (data.ExternalUserPassword) C.txtExternalUserPassword.Text(data.ExternalUserPassword);
    C.chkIncludeBranch.Value(data.IncludeBranch);
    C.chkIncludeDepartment.Value(data.IncludeDepartment);
  }

  // Show Controls
  if (mExportType) {
    // File or Database
    if (mExportType.SupportsWebServices &amp;&amp; mExportType.IsFileBasedExporter) {
      if (mExportType.ConnectsToExternalDatabase) {
        C.txtDatabaseName.VisibleRow(true);
      }
      else {
        C.lblFileName.VisibleRow(true);
        C.chkFileDownload.VisibleRow(true);
        C.chkFileLocation.VisibleRow(true);
        C.chkFileHold.VisibleRow(C.chkNewGLBatch.Value());

        C.txtFileName.VisibleRow(true);
      }

      // Update Controls
      FileLocation_Change();
    }

    // Credentials
    if (mExportType.SupportsWebServices &amp;&amp; mExportType.RequiresExternalApplicationCredentials) {
      C.lblCredentials.VisibleRow(true);
      C.txtExternalUserId.VisibleRow(true);
      C.txtExternalUserPassword.VisibleRow(true);
    }

    // Other Options
    if (mExportType.SupportsWebServices) {
      C.lblOtherOptions.VisibleRow(true);
      C.dateDateClosedTo.VisibleRow(true);
      if (mExportType.UsesAccountStructure) C.txtAccountStructure.VisibleRow(true);
      if (mExportType.SupportsBranches) C.chkIncludeBranch.VisibleRow(true);
      if (mExportType.SupportsDepartments) C.chkIncludeDepartment.VisibleRow(true);
      if (mExportType.UsesTransactionNarrative) C.txtTransactionNarrative.VisibleRow(true);
      if (mRecord.UseGst) C.txtGstAccountId.VisibleRow(true);
      if (mExportType.UsesManualJournalDraft) C.chkXero_ManualJournalDraft.VisibleRow(true);

      // Tooltips
      toolTip = "Date Closed To:\nAll Transactions dated on or before this date will be re-dated to the day after this date. This prevents transactions being created for a closed off Accounting Period.";
      if (mExportType.UsesAccountStructure) toolTip += "\n\nAccount Structure:\nDefine the Account code structure to send. Include 'A' for a GL Account, 'B' for Department and 'D' for Department. E.g. BB-DD-AAAAAA.";
      if (mExportType.UsesTransactionNarrative) toolTip += "\n\nSumm. Narrative:\nThe Transaction Narrative used for summarised Journal Transactions. The GL Export Id can be inserted as a special tag.";
    }

    // Not Supported by Web Services (and therefore this HTML Widget)
    if (!mExportType.SupportsWebServices &amp;&amp; mExportType.SupportsWebServicesMessage) {
      C.divSupportsWebServicesMessage.html(mExportType.SupportsWebServicesMessage);
      C.divSupportsWebServicesMessage.show();
    }
  }

  // Set Label Tooltip
  C.lblOtherOptions.TooltipText(toolTip);

  // Update Buttons
  tabWizard_UpdateButtons();

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

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

  // Block UI
  widget.UI.Block("Refreshing Recent General Ledger Exports, please wait...");

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

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

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

// ============
// 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.AddColumnString("ProcessType", { caption: "Process Type" });
    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();
}

// ===================
// gridExistingBatches
// ===================
function gridExistingBatches_Refresh() {
  // Add Columns
  C.gridExistingBatches.ClearColumns();
  C.gridExistingBatches.AddColumnString("GLExportId", { caption: "GL Export Id", width: "18em" });
  C.gridExistingBatches.AddColumnDateTime("BatchDate", { caption: "Date", longTime: true });
  C.gridExistingBatches.AddColumnString("Creator", { caption: "Creator", width: "18em" });
  C.gridExistingBatches.AddColumnString("Notes", { caption: "Notes" });

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

  // Select last (newest) row
  C.gridExistingBatches.ActivateLastDataRow(true);
}

function gridExistingBatches_InitialiseRow(e) {
  var item = mRecord_ExistingBatches[e.row.listIndex];

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

function gridExistingBatches_RowDrilldown(e) {
  tabWizard_Move(1);
}

// ===========
// txtFileName
// ===========
function txtFileName_ButtonClick(sender, e) {
  switch (e.id) {
    case "AppendExtension":
      if (mExportType) {
        if (mExportType.DefaultFileExtension) {
          C.txtFileName.Text(C.txtFileName.Text() + "." + mExportType.DefaultFileExtension);
        }
        else {
          widget.UI.MsgBoxAlert("Unknown File Extension for " + mExportType.ExportTypeText + ".");
        }
      }
      break;

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

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params;

  // Parameters
  params = {
    exportNew: C.chkNewGLBatch.Value(),
    glExportType: C.cboGLExportType.Text(),
    dateClosedTo: C.dateDateClosedTo.Value(),
    entityId: C.cboEntity.Text(),
    notes: C.txtNotes.Text(),
  }

  // New Export
  if (C.chkNewGLBatch.Value()) {
    params.GlExportId = C.txtGlExportId.Text();

    if (C.chkProcessAccountingLedgerTransactions.Value()) {
      params.ProcessAccountingLedgers = true;
      params.AccountingLedgersDateTo = C.dateAccountingLedgerTransactionsDateTo.Value();
    }
    if (C.chkProcessBankSuspenseItems.Value()) {
      params.ProcessBankSuspenseItems = true;
      params.BankSuspenseItemsDateTo = C.dateBankSuspenseItemsDateTo.Value();
    }
    if (C.chkProcessBankTransactions.Value()) {
      params.ProcessBankTransactions = true;
      params.BankTransactionsDateTo = C.dateBankTransactionsDateTo.Value();
    }
    if (C.chkProcessJournalTransactions.Value()) {
      params.ProcessJournalTransactions = true;
      params.JournalTransactionsDateTo = C.dateJournalTransactionsDateTo.Value();
    }
  }

  // Existing Exports
  if (C.chkReExportGLBatch.Value()) {
    if (C.gridExistingBatches.ActiveDataRowListIndex() != -1) {
      var item = mRecord_ExistingBatches[C.gridExistingBatches.ActiveDataRowListIndex()];

      params.GlExportId = item.GLExportId;
    }
  }

  // Export Type specific
  if (mExportType) {
    // File or Database
    if (mExportType.IsFileBasedExporter) {
      if (mExportType.ConnectsToExternalDatabase) {
        params.FileName = C.txtDatabaseName.Text();
      }
      else {
        params.FileDownload = C.chkFileDownload.Value();
        params.FileLocation = C.chkFileLocation.Value();
        params.FileHold = C.chkFileHold.Value();
        params.FileName = C.txtFileName.Text();
      }
    }

    // Credentials
    if (mExportType.RequiresExternalApplicationCredentials) {
      params.ExternalUserId = C.txtExternalUserId.Text();
      params.ExternalUserPassword = C.txtExternalUserPassword.Text();
    }

    // Other
    if (mExportType.SupportsBranches) params.IncludeBranch = C.chkIncludeBranch.Value();
    if (mExportType.SupportsDepartments) params.IncludeDepartment = C.chkIncludeDepartment.Value();
    if (mExportType.UsesAccountStructure) params.AccountStructure = C.txtAccountStructure.Text();
    if (mExportType.UsesTransactionNarrative) params.TransactionNarrative = C.txtTransactionNarrative.Text();
    if (mExportType.UsesManualJournalDraft) params.Xero_ManualJournalDraft = C.chkXero_ManualJournalDraft.Value();
  }

  return params;
}

// =============
// Export Option
// =============
function ExportOption_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Check boxes
  C.chkNewGLBatch.Value(sender == C.chkNewGLBatch);
  C.chkReExportGLBatch.Value(sender == C.chkReExportGLBatch);

  // Refresh Page
  pageGeneral_Refresh();
}

// =====================
// New GL Export Options
// =====================
function ExportOptionsNew_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Date Boxes
  if (C.chkNewGLBatch.Value()) {
    C.dateBankTransactionsDateTo.VisibleRow(C.chkProcessBankTransactions.Value());
    C.dateJournalTransactionsDateTo.VisibleRow(C.chkProcessJournalTransactions.Value());

    if (mRecord.AddonsAccountingLedgers &amp;&amp; C.chkProcessAccountingLedgerTransactions.Value()) {
      C.dateAccountingLedgerTransactionsDateTo.VisibleRow(true);
      C.divAccountingLedgerTransactionsDateTo.show();
    }
    else {
      C.dateAccountingLedgerTransactionsDateTo.VisibleRow(false);
      C.divAccountingLedgerTransactionsDateTo.hide();
    }

    C.dateBankSuspenseItemsDateTo.VisibleRow(C.chkProcessBankSuspenseItems.Value());
  }
  else {
    C.dateBankTransactionsDateTo.VisibleRow(false);
    C.dateJournalTransactionsDateTo.VisibleRow(false);
    C.dateAccountingLedgerTransactionsDateTo.VisibleRow(false);
    C.divAccountingLedgerTransactionsDateTo.hide();
    C.dateBankSuspenseItemsDateTo.VisibleRow(false);
  }
}

// ====================
// File Location Change
// ====================
function FileLocation_Change(sender, e) {
  // Using Database?
  var UsingDatabase = (mExportType &amp;&amp; mExportType.IsFileBasedExporter &amp;&amp; mExportType.ConnectsToExternalDatabase);

  // Update Values
  if (sender &amp;&amp; e) {
    C.chkFileDownload.Value(sender == C.chkFileDownload);
    C.chkFileLocation.Value(sender == C.chkFileLocation);
    C.chkFileHold.Value(sender == C.chkFileHold);
  }

  // Reset Controls
  if (!UsingDatabase) C.txtFileName.VisibleRow(true);

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

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

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

// =============
// txtGlExportId
// =============
function txtGlExportId_ButtonClick(source, e) {
  switch(e.id) {
    case "GetNextGLExportId":
      GetNextGLExportId();
      break;
  }
}

function GetNextGLExportId() {
  // Block
  widget.UI.Block("Getting next GL Export Id, please wait...");

  // Get Id
  widget.GetString("GetNextBatchId", {},
    function(data) {
      // Parse
      data = JSON.parse(data);

      // Unblock
      widget.UI.Unblock();

      // Set Textbox
      if (data.NextGlExportId) {
        C.txtGlExportId.Text(data.NextGlExportId);
      }
      else {
        widget.UI.MsgBoxAlert("Could not determine next GL Export Id.");
      }
    },

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

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

// =========
// cboEntity
// =========
function cboEntity_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Flag for new defaults
  mEntityChanged = true;
}

// ===============
// cboGLExportType
// ===============
function cboGLExportType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Get selected Export Type
  mExportType = mRecord.ExportTypes.GetItem(C.cboGLExportType.Text());

  // Refresh
  pageExportType_Refresh();
}

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

  // General
  AdvancedInitialiseSection("Notes", mRecord.ShowNotes);
}

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

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

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

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

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

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

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

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "FORMCLOSE":
      // Closing Form
      if (mRecord &amp;&amp; mRecord.WorkflowId &amp;&amp; !mSearchResult) {
        widget.UI.MsgBoxConfirm("Closing this form without performing a Search will not action the Workflow Item.\n\nAre you sure you want to close this form?", {}, tabWizard_Cancel);
      }
      else {
        tabWizard_Cancel();
      }
      break;

    default:
      break;
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>u4Ci2KJ+tUGDoH2xTthKiA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>900</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="ShowNotes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>