<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-22T00:33:14.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-08-22T00:30:51.4290000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-22T00:32:38.6750000</UpdatedUtcDate>
    <ScriptId>PDW</ScriptId>
    <Description>Publish Documents</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_DocumentsPublish
Option Explicit On
Option Strict On

' #################################################################
' Publish Documents
'
' Version: 1.06 (22/08/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes unless 'DesktopMode' is checked
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  04/09/2023  ISS      J031190   Created
'    1.01  26/09/2023  ISS      J031986   Unused &lt;style&gt; block removed
'    1.02  08/02/2024  ISS      J032054   Script Timeout set to unlimited
'    1.03  07/05/2024  ISS      J032452   Changed Document Manager Validation to use IsAvailableResolved instead of IsAvailable. Removed commented out code.
'          09/05/2024  ISS      J033085   Permission key to allow cancel plus show Notes column
'    1.04  19/06/2024  ISS      J033741   Emailing not allowed if Exchange but not SMTP was configured
'    1.05  21/06/2024  ISS      J033721   Enhancements to prevent large numbers of record from running out of memory
'          21/06/2024  ISS      J033767   Compacting grid removes the first character of Notes
'    1.06  22/08/2024  ISS      J034139   Email options were hidden if using Exchange instead of SMTP
' #################################################################

' Constants
Private Const FORM_KEY As String = "DocumentsPublish"

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

' Other
Private mAutoCommit As Boolean
Private mAutoPublishOpen As Boolean
Private mDesktopMode As Boolean
Private WithEvents mLogPublishItems As finLogPublishItems
Private mPermissionKeyCancel As String
Private mProcessId As String
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus
Private mRefreshItemLimit As Integer
Private mShowLogNotes As Boolean

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")
    mAutoPublishOpen = .GetBoolean("AutoPublishOpen")
    mDesktopMode = .GetBoolean("DesktopMode")
    mPermissionKeyCancel = .GetString("PermissionKeyCancel")
    mProcessId = .GetString("ProcessId")
    mShowLogNotes = .GetBoolean("ShowLogNotes", True)
    mRefreshItemLimit = .GetInteger("RefreshItemLimit"): If mRefreshItemLimit &lt;= 0 Then mRefreshItemLimit = 2500    
  End With

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

    Case "BackgroundProcess.ExecuteCommit"
      ' Called by Web Services to execute a Background Process that was initially queued in the Widget's UI (via the Finish event)
      Main = BackgroundProcess_ExecuteCommit(returnValue)

    Case "BackgroundProcess.Refresh"
      ' Called by Web Services to execute a Background Process to refresh data that was initially queued in the Widget's UI
      Main = BackgroundProcess_Refresh(returnValue)

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

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

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

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

    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)
      
    Case "Refresh"
      ' Refresh (and Execute Commit, if in Auto Commit mode)
      Main = Refresh(parametersJson, startupParametersJson, returnValue)
      
    Case "Save"
      ' Save Log Status Changes
      Main = Save(parametersJson, startUpParametersJson, returnValue)

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

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

End Function

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

  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim LogPublishItems As finLogPublishItems
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

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

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

  ' Get finLogPublishItems Object
  If Success Then
    Success = CreateLogPublishItems(Nothing, LogPublishItems, False)
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ProcessId = mProcessId      
      .RepublishFromDateDefault = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime().AddDays(-1))
      .RepublishToDateDefault = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime())
      
      ' Lists
      .LogClassesList = finBL.Enums.isefinLogClass_GetListPublishable().ToCsvString()
      .LogFileTypesList = finBL.Enums.iseDocumentFileType_GetList(finBL.Settings.AddOns.Messaging, True).ToCsvString(True)
      .LogPublishStatusesList = finBL.Enums.isefinLogPublishItemStatus_ToString(isefinLogPublishItemStatus.Published) &amp; "," &amp; finBL.Enums.isefinLogPublishItemStatus_ToString(isefinLogPublishItemStatus.Failed)
      .LogPublishStatusesGridList = finBL.Enums.isefinLogPublishItemStatus_ToString(isefinLogPublishItemStatus.Open) &amp; "," &amp; finBL.Enums.isefinLogPublishItemStatus_ToString(isefinLogPublishItemStatus.ToSend) &amp; "," &amp; finBL.Enums.isefinLogPublishItemStatus_ToString(isefinLogPublishItemStatus.NotIssued) &amp; "," &amp; finBL.Enums.isefinLogPublishItemStatus_ToString(isefinLogPublishItemStatus.Cancel)
        
      ' Advanced      
      .ShowAccountManagers = mCombinedParameters.GetString("ShowAccountManagers") : If Len(.ShowAccountManagers) = 0 Then .ShowAccountManagers = "Advanced"
      .ShowAccounts = mCombinedParameters.GetString("ShowAccounts") : If Len(.ShowAccounts) = 0 Then .ShowAccounts = "Advanced"
      .ShowAccountApps = mCombinedParameters.GetString("ShowAccountApps") : If Len(.ShowAccountApps) = 0 Then .ShowAccountApps = "Advanced"
      .ShowAccountAppTypes = mCombinedParameters.GetString("ShowAccountAppTypes") : If Len(.ShowAccountAppTypes) = 0 Then .ShowAccountAppTypes = "Advanced"
      .ShowBranches = mCombinedParameters.GetString("ShowBranches") : If Len(.ShowBranches) = 0 Then .ShowBranches = "True"      
      .ShowClientGroups = mCombinedParameters.GetString("ShowClientGroups") : If Len(.ShowClientGroups) = 0 Then .ShowClientGroups = "True"
      .ShowClients = mCombinedParameters.GetString("ShowClients") : If Len(.ShowClients) = 0 Then .ShowClients = "True"      
      .ShowClientTypes = mCombinedParameters.GetString("ShowClientTypes") : If Len(.ShowClientTypes) = 0 Then .ShowClientTypes = "True"      
      .ShowDepartments = mCombinedParameters.GetString("ShowDepartments") : If Len(.ShowDepartments) = 0 Then .ShowDepartments = "Advanced"
      .ShowEntities = mCombinedParameters.GetString("ShowEntities") : If Len(.ShowEntities) = 0 Then .ShowEntities = "Advanced"
      .ShowExternalPartiesDealers = mCombinedParameters.GetString("ShowExternalPartiesDealers") : If Len(.ShowExternalPartiesDealers) = 0 Then .ShowExternalPartiesDealers = "Advanced"
      .ShowMonitorCategoriesAccountsA = mCombinedParameters.GetString("ShowMonitorCategoriesAccountsA") : If Len(.ShowMonitorCategoriesAccountsA) = 0 Then .ShowMonitorCategoriesAccountsA = "Advanced"      
      .ShowMonitorCategoriesAccountsB = mCombinedParameters.GetString("ShowMonitorCategoriesAccountsB") : If Len(.ShowMonitorCategoriesAccountsB) = 0 Then .ShowMonitorCategoriesAccountsB = "Advanced"      
      .ShowMonitorCategoriesAccountsC = mCombinedParameters.GetString("ShowMonitorCategoriesAccountsC") : If Len(.ShowMonitorCategoriesAccountsC) = 0 Then .ShowMonitorCategoriesAccountsC = "Advanced"      
      .ShowPools = mCombinedParameters.GetString("ShowPools") : If Len(.ShowPools) = 0 Then .ShowPools = "True"
      .ShowProductTypes = mCombinedParameters.GetString("ShowProductTypes") : If Len(.ShowProductTypes) = 0 Then .ShowProductTypes = "Advanced"
      .ShowUserGroups = mCombinedParameters.GetString("ShowUserGroups") : If Len(.ShowUserGroups) = 0 Then .ShowUserGroups = "Advanced"      
      .ShowUsers = mCombinedParameters.GetString("ShowUsers") : If Len(.ShowUsers) = 0 Then .ShowUsers = "Advanced"
      
      ' General
      
      ' Parameters

      ' Licence
      If Not finBL.Settings.AddOns.AccountApplication Then
        .ShowAccountApps = "False"
        .ShowAccountAppTypes = "False"
      End If
      If Not finBL.Settings.AddOns.Branch Then .ShowBranches = "False"
      If Not finBL.Settings.AddOns.Entity Then .ShowEntities = "False"
      If Not finBL.Settings.MonitorCategoryAUse Then .ShowMonitorCategoriesAccountsA = "False"
      If Not finBL.Settings.MonitorCategoryBUse Then .ShowMonitorCategoriesAccountsB = "False"
      If Not finBL.Settings.MonitorCategoryCUse Then .ShowMonitorCategoriesAccountsC = "False"        
      If Not finBL.Settings.AddOns.Pool Then .ShowPools = "False"
      If Not finBL.Settings.AddOns.ExternalPartyDealers Then .ShowExternalPartiesDealers = "False"

      ' Permissions

      ' Configuration
      If Len(mPermissionKeyCancel) = 0 Then
        .AllowCancel = True
      Else
        .AllowCancel = finBL.CurrentUser.Permissions.Allow(mPermissionKeyCancel)
      End If
      
      .AutoCommit = mAutoCommit
      .AutoPublishOpen = mAutoPublishOpen
      .MonitorCategoryADescription = Replace("Monitor Category A (" &amp; finBL.Settings.MonitorCategoryADescriptionResolved &amp; "):", " ", Chr(160))
      .MonitorCategoryBDescription = Replace("Monitor Category B (" &amp; finBL.Settings.MonitorCategoryBDescriptionResolved &amp; "):", " ", Chr(160))
      .MonitorCategoryCDescription = Replace("Monitor Category C (" &amp; finBL.Settings.MonitorCategoryCDescriptionResolved &amp; "):", " ", Chr(160))
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    End With

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Request that a Background Process is Cancelled.
''' &lt;/summary&gt;
Private Function CancelBackgroundProcess(ByRef returnValue As String) As Boolean

  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ProcessId = mCombinedParameters.GetString("ProcessId")

  ' Request Cancel
  Success = finBL.HtmlWidgetUtilities.CancelBackgroundProcess(processId)

  Return Success

End Function

''' &lt;summary&gt;
'''  Builds a finLogPublishItems object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateLogPublishItems(parameters As WizardFinishParameters,
                                       ByRef logPublishItems As finLogPublishItems,
                                       refresh As Boolean) As Boolean

  Dim RefreshParameters As ISParameters
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  logPublishItems = finBL.CreateLogPublishItems()

  ' Update Parameters
  ' NOTE: Unlike most BL objects, this does not have separate properties for filter criteria; it uses an ISParameters object that is passed into the respective Refresh method
  If Success AndAlso parameters IsNot Nothing Then
    With logPublishItems
      ' General
      .LogTimeZoneId = parameters.LogTimeZoneId
      If parameters.Republish
        ' Republish
        .LogPublishedDateFrom = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(parameters.LogPublishedDateFrom)
        .LogPublishedDateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(parameters.LogPublishedDateTo)
        
        RefreshParameters = .CreateParametersForRepublish()
        RefreshParameters.SetString("PublishedUsers", parameters.RangePublishedUsers)
      Else
        ' Publish
        .LogPublishOnTzDateOnOrBefore = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(parameters.LogPublishOnDateOnOrBefore)
        If .LogPublishOnTzDateOnOrBefore = Nothing Then
          .LogPublishOnTzDateOnOrBefore = finBL.TimeZoneFunctions.GetCurrentTimeZoneDateTime(.LogTimeZoneId)
        End If
        
        RefreshParameters = .CreateParametersForPublish()
      End If
      
      RefreshParameters.SetString("LogClasses", parameters.LogClasses)
      RefreshParameters.SetString("LogFileTypes", parameters.LogFileTypes)
      RefreshParameters.SetString("LogStatuses", parameters.LogStatuses)
      
      ' Ranges
      RefreshParameters.SetString("Documents", parameters.RangeDocuments)
      RefreshParameters.SetString("AccountManagers", parameters.RangeAccountManagers)
      RefreshParameters.SetString("Accounts", parameters.RangeAccounts)
      RefreshParameters.SetString("AccountApps", parameters.RangeAccountApps)
      RefreshParameters.SetString("AccountAppTypes", parameters.RangeAccountAppTypes)
      RefreshParameters.SetString("Branches", parameters.RangeBranches)
      RefreshParameters.SetString("ClientGroups", parameters.RangeClientGroups)
      RefreshParameters.SetString("Clients", parameters.RangeClients)
      RefreshParameters.SetString("ClientTypes", parameters.RangeClientTypes)
      RefreshParameters.SetString("Departments", parameters.RangeDepartments)
      RefreshParameters.SetString("ExternalPartiesDealers", parameters.RangeExternalPartiesDealers)
      RefreshParameters.SetString("Entities", parameters.RangeEntities)
      RefreshParameters.SetString("MonitorCategoriesA", parameters.RangeMonitorCategoriesA)
      RefreshParameters.SetString("MonitorCategoriesB", parameters.RangeMonitorCategoriesB)
      RefreshParameters.SetString("MonitorCategoriesC", parameters.RangeMonitorCategoriesC)
      RefreshParameters.SetString("Pools", parameters.RangePools)
      RefreshParameters.SetString("ProductTypes", parameters.RangeProductTypes)
      RefreshParameters.SetString("UserGroups", parameters.RangeUserGroups)
      RefreshParameters.SetString("Users", parameters.RangeUsers)
      
      ' Maximum grid items
      If Not mAutoCommit Then
        LogPublishItems.RefreshItemLimit = mRefreshItemLimit
      End If
      
      ' Refresh
      If refresh Then
        If parameters.Republish Then
          ' Republish
          Success = LogPublishItems.RefreshForRepublish(RefreshParameters)
        Else
          ' Publish
          Success = LogPublishItems.RefreshForPublish(RefreshParameters)
        End If
      End If
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Refresh, i.e., Queue Background Process.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Refresh(parametersJson As String,
                         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
  End If
  
  ' Start Background Process to Refresh Data
  ' NOTE: If mDesktopMode is True then the desktop User Interface will handle this rather than Web Services Background Processes (for this Widget, this just makes testing easier)
  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;
'''  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
  ' NOTE: If mDesktopMode is True then the desktop User Interface will handle this rather than Web Services Background Processes (for this Widget, this just makes testing easier)
  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

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

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

  ' Get current and recent Background Processes that for this User
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_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;
'''  Get Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef wizardFinishParameters As WizardFinishParameters) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  Return Success

End Function

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

  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Save Log Status updates.
''' &lt;/summary&gt;
Private Function Save(parametersJson As String,
                      startupParametersJson As String,
                      ByRef returnValue As String) As Boolean

  Dim LogPublishItems As finLogPublishItems                      
  Dim Found As Boolean
  Dim obj As Object
  Dim PublishItems As PublishItems
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' NOTE: This is not currently performed as a Background Process since it is unlikely to take that long

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Refresh Logs
  If Success Then
    Success = CreateLogPublishItems(WizardFinishParameters, LogPublishItems, True)
  End If
  
  ' Get Publish Items collection (as displayed in the grid)
  If Success Then
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(WizardFinishParameters.RefreshData, GetType(PublishItems), obj) Then
      PublishItems = DirectCast(obj, PublishItems)
    Else 
      Success = False
    End If
  End If
  
  ' Update Log Items from our Publish Items collection
  ' NOTE: Ensure we exclude any items that were not in the original refresh
  If Success Then
    For Each LogPublishItem As finLogPublishItem In LogPublishItems
      With LogPublishItem
        ' Locate and update item
        Found = False
        For Each PublishItem As PublishItem In PublishItems.Items
          If .LogPk = PublishItem.LogPk AndAlso .LogClass = PublishItem.LogClass Then
            ' Update
            Found = True
            .Include = PublishItem.Include
            .Fee = PublishItem.Fee
            .StatusText = PublishItem.LogPublishStatus
          End If
        Next
        
        ' Exclude if not found
        If Not Found Then
          LogPublishItem.Include = False
        End If
      End With
    Next
  End If
  
  ' Save
  If Success Then
    Success = LogPublishItems.Save()
  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 ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate Page
  Select Case PageId
    Case "General"      
      ConfirmList = New List(Of String)
      Data = ConfirmList
      
    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unhandled page '{0}' in WizardValidate.", PageId)
  End Select

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

  Return Success

End Function

Private Function BackgroundProcess_Refresh(ByRef returnValue As String) As Boolean

  Dim LogPublishItems As finLogPublishItems
  Dim ParameterDetails As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = 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)
  
  ' Parse Parameters
  Success = GetWizardFinishParameters(mParameters.ToSimpleJsonString(), WizardFinishParameters)
  
  ' Notify
  If Success Then
    ParameterDetails = finBL.Utilities.KeyValueListToText(mParameters, False, False)
    
    If WizardFinishParameters.Republish
      mProcessStatus.AddEvent_Information("Refreshing Logs for Document Republish", ParameterDetails)
    Else
      mProcessStatus.AddEvent_Information("Refreshing Logs for Document Publish", ParameterDetails)
    End If
  End If
  
  ' Refresh Logs
  If Success Then
    Success = CreateLogPublishItems(WizardFinishParameters, LogPublishItems, True)
  End If
  
  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New PublishItems(LogPublishItems, mShowLogNotes), returnValue)
  End If
  
  Return Success  
  
End Function

Private Function BackgroundProcess_ExecuteCommit(ByRef returnValue As String) As Boolean
  
  'Dim Cancelled As Boolean
  Dim Found As Boolean
  Dim obj As Object
  Dim PublishItems As PublishItems
  Dim RefreshData As String
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = 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)

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

  ' Notify
  If WizardFinishParameters.Republish Then
    mProcessStatus.AddEvent_Information("Starting Republish")    
  Else
    mProcessStatus.AddEvent_Information("Starting Publish")    
  End If
  
  ' Refresh Logs
  If Success Then
    Success = CreateLogPublishItems(WizardFinishParameters, mLogPublishItems, True)
  End If
  
  ' Notify
  If Success Then
    If WizardFinishParameters.Republish
      mProcessStatus.AddEvent_Information("Refreshing Logs for Document Republish")
    Else
      mProcessStatus.AddEvent_Information("Refreshing Logs for Document Publish")
    End If
  End If  
  
  ' Get Refresh Data (i.e., what appeared in the grid)
  If Success Then
    If finBL.HtmlWidgetUtilities.GetBackgroundProcessRefreshData(mProcessStatus.ProcessId, RefreshData) Then
      If Len(RefreshData) = 0 Then
        Success = False
        finBL.Error.ErrorBegin("No Refresh Data available.")
      Else 
        If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(RefreshData, GetType(PublishItems), obj) Then
          PublishItems = DirectCast(obj, PublishItems)
        Else 
          Success = False
        End If
      End If
    Else 
      Success = False
    End If
  End If

  ' Update Log Items from our Publish Items collection
  ' NOTE: Ensure we exclude any items that were not in the original refresh
  If Success Then
    ' Notify
    mProcessStatus.AddEvent_Information("Updating Log Publish Items")
  
    ' Update
    For Each LogPublishItem As finLogPublishItem In mLogPublishItems
      With LogPublishItem
        ' Locate and update item
        Found = False
        For Each PublishItem As PublishItem In PublishItems.Items
          If .LogPk = PublishItem.LogPk AndAlso .LogClass = PublishItem.LogClass Then
            ' Update
            Found = True
            .Include = PublishItem.Include
            .Fee = PublishItem.Fee
            .StatusText = PublishItem.LogPublishStatus
            
            ' Publish 'Open'?
            If mAutoPublishOpen AndAlso .Status = isefinLogPublishItemStatus.Open Then
              .Status = isefinLogPublishItemStatus.ToSend
            End If
          End If
        Next
        
        ' Exclude if not found
        If Not Found Then
          LogPublishItem.Include = False
        End If
      End With
    Next
  End If
  
  ' Save changes to Logs
  If Success AndAlso mLogPublishItems.IsDirty Then
    ' Notify
    mProcessStatus.AddEvent_Information("Saving changes to Logs")
    
    Success = mLogPublishItems.Save()
  End If

  ' Notify
  If Success Then
    If WizardFinishParameters.Republish Then
      If mLogPublishItems.CountIncluded &lt;&gt; 0 Then
        mProcessStatus.AddEvent_Information("Starting Republish")
      Else
        mProcessStatus.AddEvent_Information("No Logs remain to Republish")
      End If
    Else
      If mLogPublishItems.CountIncludedToSend &lt;&gt; 0 Then
        mProcessStatus.AddEvent_Information("Starting Publish")
      Else
        mProcessStatus.AddEvent_Information("No Logs remain to Publish")
      End If
    End If
  End If
  
  ' Publish
  If Success AndAlso mLogPublishItems.CountIncluded &lt;&gt; 0 Then
    ' Must flag as 'Unattended', i.e., no User Interface is available
    mLogPublishItems.UnattendedPublish = True
    
    ' Publish
    If WizardFinishParameters.Republish Then
      Success = mLogPublishItems.ExecutePublish(isefinLogPublishType.Republish, False, False)
    Else
      Success = mLogPublishItems.ExecutePublish(isefinLogPublishType.Publish, False, False)
    End If
    
    ' Commit
    If Success Then
      If mLogPublishItems.ExecutePublishCommit(Warning) Then
        ' Notify of any warning generated
        If Len(Warning) &lt;&gt; 0 Then
          mProcessStatus.AddEvent_Warning("Changes were committed but the following warning was given:" &amp; vbNewLine &amp; vbNewLine &amp; Warning)          
        End If
      Else
        Success = False
      End If
    End If
  End If
  
  ' Notify
  If WizardFinishParameters.Republish Then
    mProcessStatus.AddEvent_Information("Republish complete")
  Else
    mProcessStatus.AddEvent_Information("Publish complete")
  End If
  
  Return Success  
  
End Function

Private Sub mLogPublishItems_AfterPublishItem(sender As Object, e As finLogPublishItemEventArgs) Handles mLogPublishItems.AfterPublishItem

  ' Notify
  With e.LogPublishBatchItem
    If .PublishSuccess Then
      mProcessStatus.AddEvent_Information(String.Format("   Published {0} Log #{1} for '{2}'", .LogClass, .LogPk, .Id))
    Else
      mProcessStatus.AddEvent_Warning(String.Format("   Failed to publish {0} Log #{1} for '{2}'", .LogClass, .LogPk, .Id), .PublishError)
    End If
  End With

End Sub

Private Sub mLogPublishItems_BeforePublishItem(sender As Object, e As finLogPublishItemEventArgs) Handles mLogPublishItems.AfterPublishItem

  ' Notify
  With e.LogPublishBatchItem
    mProcessStatus.AddEvent_Information(String.Format("   Publishing Document '{0}' for {1} Log #{2} for '{3}'", .DocumentId, .LogClass, .LogPk, .Id))
  End With

End Sub

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

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

  ' Record
  Public RepublishFromDateDefault As Date?
  Public RepublishToDateDefault As Date?

  ' Lists
  Public LogClassesList As String
  Public LogFileTypesList As String
  Public LogPublishStatusesList As String
  Public LogPublishStatusesGridList As String

  ' Advanced
  Public ShowAccountManagers As String
  Public ShowAccounts As String
  Public ShowAccountApps As String
  Public ShowAccountAppTypes As String
  Public ShowBranches As String
  Public ShowClientGroups As String
  Public ShowClients As String
  Public ShowClientTypes As String  
  Public ShowDepartments As String
  Public ShowExternalPartiesDealers As String  
  Public ShowEntities As String
  Public ShowMonitorCategoriesAccountsA As String
  Public ShowMonitorCategoriesAccountsB As String
  Public ShowMonitorCategoriesAccountsC As String
  Public ShowPools As String
  Public ShowProductTypes As String
  Public ShowUserGroups As String
  Public ShowUsers As String
  
  ' Permissions

  ' Configuration
  Public AllowCancel As Boolean
  Public AutoCommit As Boolean
  Public AutoPublishOpen As Boolean
  Public MonitorCategoryADescription As String
  Public MonitorCategoryBDescription As String
  Public MonitorCategoryCDescription As String
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean

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 Republish As Boolean
  
  Public LogTimeZoneId As String
  Public LogPublishOnDateOnOrBefore As Date?
  Public LogPublishedDateFrom As Date?
  Public LogPublishedDateTo As Date?
  Public RangePublishedUsers As String

  Public LogClasses As String
  Public LogFileTypes As String
  Public LogStatuses As String
  
  ' Ranges
  Public RangeDocuments As String
  Public RangeAccountManagers As String
  Public RangeAccounts As String
  Public RangeAccountApps As String
  Public RangeAccountAppTypes As String
  Public RangeBranches As String
  Public RangeClientGroups As String
  Public RangeClients As String
  Public RangeClientTypes As String
  Public RangeDepartments As String
  Public RangeExternalPartiesDealers As String
  Public RangeEntities As String
  Public RangeMonitorCategoriesA As String
  Public RangeMonitorCategoriesB As String
  Public RangeMonitorCategoriesC As String
  Public RangePools As String
  Public RangeProductTypes As String
  Public RangeUserGroups As String
  Public RangeUsers As String

  ' Other
  Public ProcessId As String
  Public RefreshData As String

End Class



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

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

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

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

  End Sub

End Class



''' &lt;summary&gt;
'''  Publish Items.
''' &lt;/summary&gt;
Public Class PublishItems
  
  ' Properties
  Public RefreshItemLimit As Integer
  Public RefreshUnlimitedItemCount As Integer
  
  ' Items
  Public Items As New List(Of PublishItem)
  
  Public Sub New()
  End Sub
  
  Public Sub New(logPublishItems As finLogPublishItems,
                 includeNotes As Boolean)
    
    With logPublishItems
      Me.RefreshItemLimit = .RefreshItemLimit
      Me.RefreshUnlimitedItemCount = .RefreshUnlimitedItemCount 

      ' Items
      For Each LogPublishItem As finLogPublishItem In logPublishItems
        Me.Items.Add(New PublishItem(LogPublishItem, includeNotes))
      Next
    End With
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Publish Items.
''' &lt;/summary&gt;
Public Class PublishItem
  
  ' Properties
  Public AccountStatus As String
  Public CanPublish As Boolean
  Public ChargeFee As Boolean
  Public DocumentFileType As iseDocumentFileType  
  Public DocumentId As String
  Public Fee As Decimal
  Public Include As Boolean
  Public LogClass As isefinLogClass
  Public LogDate As Date
  Public LogNotes As String
  Public LogPk As Integer
  Public LogPublishStatus As String  
  Public LogSubject As String
  Public SourceId As String
  Public Name As String
  Public Warning As String  
  
  Public Sub New()
  End Sub
  
  Public Sub New(logPublishItem As finLogPublishItem,
                 includeNotes As Boolean)
    
    With logPublishItem
      Me.AccountStatus = .AccountStatusText
      Me.ChargeFee = .Document.ChargeFee
      Me.DocumentFileType = .Document.FileType 
      Me.DocumentId = .DocumentId 
      Me.Fee = .Fee 
      Me.Include = .Include 
      Me.LogClass = .LogClass 
      Me.LogDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(.LogDbDate)
      Me.LogPk = .LogPk
      Me.LogPublishStatus = .StatusText
      Me.LogSubject = .LogSubject
      Me.SourceId = .SourceId 
      Me.Name = .Name
      
      ' Log Notes
      If includeNotes Then
        If .LogNotes = .LogSubject Then
          ' Ignore Notes if they are the same as the Subject
        Else
          Me.LogNotes = .LogNotes
        End If
      End If
      
      ' Can Publish?
      Select Case Me.DocumentFileType
        Case iseDocumentFileType.Email
          If Not finBLShared.SettingsUser.EmailIsUnattendedAvailable() Then
            Me.Warning = "No SMTP or Exchange server is configured"
          Else
            Me.CanPublish = True
          End If
          
          Case iseDocumentFileType.ExcelWorkbook 
            If finBLShared.DocumentManager.IsAvailableResolved Then
              Me.CanPublish = True
            Else
              Me.Warning = "Document Manager is not available"
            End If
            
          Case iseDocumentFileType.Html 
            Me.CanPublish = True
            
          Case iseDocumentFileType.Log 
            Me.CanPublish = True
            
          Case iseDocumentFileType.Script
            Me.CanPublish = True
            
          Case iseDocumentFileType.Sms
            If Not finBLShared.Settings.AddOns.Messaging Then
              Me.Warning = "You are not licensed for the Messaging Add-On"
            ElseIf Not finBLShared.Messaging.IsMessagingAvailable Then
              Me.Warning = "Messaging is not available"
            Else
              Me.CanPublish = True
            End If
            
          Case iseDocumentFileType.WordDocument
            If finBLShared.DocumentManager.IsAvailableResolved Then
              Me.CanPublish = True
            Else
              Me.Warning = "Document Manager is not available"
            End If

          Case iseDocumentFileType.ExcelVba, iseDocumentFileType.WordVba
            Me.Warning = "VBA Documents cannot be published from this interface"
            
          Case Else
            Me.Warning = "Cannot be published from this interface"
      End Select
      
      ' Exclude if cannot publish
      If Not Me.CanPublish Then
        Me.Include= False        
        Me.LogPublishStatus = ""
      End If
    End With
    
  End Sub
  
End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "DocumentsPublish".</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 Document Publishes you have processed."&gt;Recent Document Publishes&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Select Document Publish options."&gt;Publish Options&lt;/li&gt;
        &lt;li tabId="Parameters" tooltipText="Enter more Document Selection criteria."&gt;Document Selection&lt;/li&gt;
        &lt;li tabId="Items"&gt;Documents&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

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



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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPublishOption"&gt;Do you want to Publish or Republish Documents?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkPublish" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRepublish" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPublishDates"&gt;Specify Document Log date options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateLogPublishOnDateOnOrBefore"&gt;Log Publish Date to:&lt;/label&gt;&lt;/th&gt;        
          &lt;td&gt;&lt;div id="dateLogPublishOnDateOnOrBefore"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateLogPublishedDateFrom"&gt;Log Published from:&lt;/label&gt;&lt;/th&gt;        
          &lt;td&gt;&lt;div id="dateLogPublishedDateFrom"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateLogPublishedDateTo"&gt;To:&lt;/label&gt;&lt;/th&gt;        
          &lt;td&gt;&lt;div id="dateLogPublishedDateTo"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRangePublishedUsers"&gt;Published&amp;nbsp;by&amp;nbsp;Users:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangePublishedUsers" lookupCaption="Users" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

       &lt;tr&gt;
         &lt;th colspan="2"&gt;&lt;label id="lblLogTypes"&gt;Specify Log types to include&lt;/label&gt;&lt;/th&gt;
       &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="lstLogClasses"&gt;Classes:&lt;/label&gt;&lt;/th&gt;        
          &lt;td&gt;&lt;div id="lstLogClasses"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="lstLogFileTypes"&gt;File Types:&lt;/label&gt;&lt;/th&gt;        
          &lt;td&gt;&lt;div id="lstLogFileTypes"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="lstLogStatuses"&gt;Publish&amp;nbsp;Statuses:&lt;/label&gt;&lt;/th&gt;        
          &lt;td&gt;&lt;div id="lstLogStatuses"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    
    &lt;!-- Parameters --&gt;
    &lt;div id="pageParameters"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:14em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        
        &lt;tr advancedId="RangesHeading"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRanges"&gt;Enter ranges to filter information&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRangeDocuments"&gt;Documents:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeDocuments" lookupCaption="Documents" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountManagers"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountManagers"&gt;Account&amp;nbsp;Managers:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountManagers" lookupCaption="Account Managers" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Accounts"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccounts"&gt;Accounts:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccounts" lookupCaption="Accounts" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountApps"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountApps"&gt;Account&amp;nbsp;Applications:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountApps" lookupCaption="Account Applications" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountAppTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountAppTypes"&gt;Application&amp;nbsp;Types:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountAppTypes" lookupCaption="Account Application Types" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Branches"&gt;
          &lt;th&gt;&lt;label for="txtRangeBranches"&gt;Branches:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeBranches" lookupCaption="Branches" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ClientGroups"&gt;
          &lt;th&gt;&lt;label for="txtRangeClientGroups"&gt;Client&amp;nbsp;Groups:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClientGroups" lookupCaption="Client Groups" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Clients"&gt;
          &lt;th&gt;&lt;label for="txtRangeClients"&gt;Clients:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClients" lookupCaption="Clients" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ClientTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeClientTypes"&gt;Client&amp;nbsp;Types:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClientTypes" lookupCaption="Client Types" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Departments"&gt;
          &lt;th&gt;&lt;label for="txtRangeDepartments"&gt;Departments:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeDepartments" lookupCaption="Departments" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ExternalPartiesDealers"&gt;
          &lt;th&gt;&lt;label for="txtRangeExternalPartiesDealers"&gt;Dealers:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeExternalPartiesDealers" lookupCaption="Dealers" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Entities"&gt;
          &lt;th&gt;&lt;label for="txtRangeEntities"&gt;Entities:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeEntities" lookupCaption="Entities" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="MonitorCategoriesAccountsA"&gt;
          &lt;th&gt;&lt;label for="txtRangeMonitorCategoriesA"&gt;MonitorCategoryA:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeMonitorCategoriesA" lookupCaption="Monitor Categories A" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="MonitorCategoriesAccountsB"&gt;
          &lt;th&gt;&lt;label for="txtRangeMonitorCategoriesB"&gt;MonitorCategoryB:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeMonitorCategoriesB" lookupCaption="Monitor Categories B" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="MonitorCategoriesAccountsC"&gt;
          &lt;th&gt;&lt;label for="txtRangeMonitorCategoriesC"&gt;MonitorCategoryC:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeMonitorCategoriesC" lookupCaption="Monitor Categories C" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Pools"&gt;
          &lt;th&gt;&lt;label for="txtRangePools"&gt;Pools:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangePools" lookupCaption="Pools" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ProductTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeProductTypes"&gt;Product&amp;nbsp;Types:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeProductTypes" lookupCaption="Product Types" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="UserGroups"&gt;
          &lt;th&gt;&lt;label for="txtRangeUserGroups"&gt;User&amp;nbsp;Groups:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeUserGroups" lookupCaption="User Groups" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Users"&gt;
          &lt;th&gt;&lt;label for="txtRangeUsers"&gt;Users:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeUsers" lookupCaption="Users" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Items --&gt;
    &lt;div id="pageItems"&gt;
      &lt;div id="gridItems"&gt;&lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Progress --&gt;
    &lt;div id="pageProgress" style="display:flex"&gt;
      &lt;div id="divProgress" class="progress-events"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdHistory" class="is-button" style="float:left"&gt;Recent&lt;/button&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

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

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

var mLogsToPublish;

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

  //   General
  lblPublishOption: null,
  chkPublish: null,
  chkRepublish: null,
  
  lblPublishDates: null,
  dateLogPublishOnDateOnOrBefore: null,
  dateLogPublishedDateFrom: null,
  dateLogPublishedDateTo: null,
  txtRangePublishedUsers: null,
  
  lblLogTypes: null,
  lstLogClasses: null,
  lstLogFileTypes: null,
  lstLogStatuses: null,  
  
  //   Parameters
  lblRanges: null,
  txtRangeDocuments: null,
  txtRangeAccountManagers: null,
  txtRangeAccounts: null,
  txtRangeAccountApps: null,
  txtRangeAccountAppTypes: null,  
  txtRangeBranches: null,  
  txtRangeClientGroups: null,
  txtRangeClients: null,
  txtRangeClientTypes: null,
  txtRangeDepartments: null,
  txtRangeExternalPartiesDealers: null,
  txtRangeEntities: null,
  txtRangeMonitorCategoriesA: null,
  txtRangeMonitorCategoriesB: null,
  txtRangeMonitorCategoriesC: null,
  txtRangePools: null,
  txtRangeProductTypes: null,
  txtRangeUserGroups: null,
  txtRangeUsers: null,

  //   Items
  gridItems: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;
var cmdAdvanced;

// Other
var mAccounts;
var mAdvancedVisible = false;
var mCompactView = false;
var mComplete = false;
var mFromRecent = false;
var mLastEventId = "";
var mLastProcessStatus = "";
var mLastRefreshParametersJson = "";
var mLastProcessSummaryJson = "";
var mMonitoringExisting = false;
var mPageParametersHasAdvanced = false;
var mProcessId;

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

  // Controls
  //   General
  C.lblPublishOption = widget.UI.Label("lblPublishOption", {});
  C.chkPublish = widget.UI.RadioButton("chkPublish", {
    caption: "Publish new Documents?",
    
    onChange: chkPublish_Change,
  });
  C.chkRepublish = widget.UI.RadioButton("chkRepublish", {
    caption: "Republish existing Documents?",
    
    onChange: chkPublish_Change,
  });

  
  C.lblPublishDates = widget.UI.Label("lblPublishDates", {});
  C.dateLogPublishOnDateOnOrBefore = widget.UI.DateTimeZone("dateLogPublishOnDateOnOrBefore", {
    allowBlank: true,
  });
  C.dateLogPublishedDateFrom = widget.UI.DateTimeZone("dateLogPublishedDateFrom", {
    allowBlank: false,
  });
  C.dateLogPublishedDateTo = widget.UI.DateTimeZone("dateLogPublishedDateTo", {
    allowBlank: false,
    timeZoneVisible: false,
  });
  
  C.lblLogTypes = widget.UI.Label("lblLogTypes", {});
  C.lstLogClasses = widget.UI.CheckList("lstLogClasses", {
    allowBlank: false,
  });
  C.lstLogFileTypes = widget.UI.CheckList("lstLogFileTypes", {
    allowBlank: false,
  });
  C.lstLogStatuses = widget.UI.CheckList("lstLogStatuses", {
    allowBlank: false,
  });
  
  //   Parameters
  C.lblRanges = widget.UI.Label("lblRanges", {});
  //     Ranges
  for(var k in C) {
    if (k.startsWith("txtRange")) {
      C[k] = widget.UI.TextBox(k, {
        maxLength: 255,
        onButtonClick: txtRange_ButtonClick,
      });
      var buttons = [];

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

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

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

    onAction: gridItems_Action,
    onAfterRowActivate: gridItems_AfterRowActivate,
    onBeforeCellUpdate: gridItems_BeforeCellUpdate,
    onInitialiseRow: gridItems_InitialiseRow,
  });

  // Create Widget form
  // NOTE: Hide by default for a cleaner startup
  frmMain = new widget.UI.Form("frmMain", { visible: false });

  // Create Tabs
  tabWizard = new widget.UI.Tabs("tabWizard", { style: "wizard" });

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdBack = $("#cmdBack");
  cmdNext = $("#cmdNext");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabWizard_Cancel);
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  cmdHistory = $("#cmdHistory");
  cmdHistory.click(function() { Form_ExecuteAction("Recent"); });

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

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

  // Reset
  Form_Reset();
});

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults
  chkPublish_Change(C.chkPublish);

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

  // Resize
  Form_Resize();

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

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mAccounts = null;
  mLogsToPublish = null;

  // Hide content
  frmMain.Visible(false);

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

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

      // Give Collections ability to lookup by code

      // 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 Document Publish 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 instance of Document Publish.", { heading: "Document Publish still Processing", icon: "MonitorCategory"} );
      }
    },

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

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

    // General
    C.dateLogPublishedDateFrom.Value(mRecord.RepublishFromDateDefault);
    C.dateLogPublishedDateTo.Value(mRecord.RepublishToDateDefault);
    
    C.lstLogClasses.Text(mRecord.LogClassesList);
    C.lstLogFileTypes.Text(mRecord.LogFileTypesList);
    C.lstLogStatuses.Text("Published");
  }

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

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

  // Lists
  if (mRecord) {
    C.lstLogClasses.ListFromCsvString(mRecord.LogClassesList);
    C.lstLogFileTypes.ListFromCsvString(mRecord.LogFileTypesList);
    C.lstLogStatuses.ListFromCsvString(mRecord.LogPublishStatusesList);
  }

  // Controls
  if(mRecord) {
    // Parameters
    C.txtRangeMonitorCategoriesA.Caption(mRecord.MonitorCategoryADescription);
    C.txtRangeMonitorCategoriesB.Caption(mRecord.MonitorCategoryBDescription);
    C.txtRangeMonitorCategoriesC.Caption(mRecord.MonitorCategoryCDescription);
  
    // Initialise Advanced
    // NOTE: Performed in tabWizard_Refresh for this Widget
    //AdvancedInitialise();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess(params) {
  if (params) {
    // General
    if (params.Republish) {
      chkPublish_Change(C.chkRepublish);
      
      C.dateLogPublishedDateFrom.TimeZoneId(params.LogTimeZoneId);
      C.dateLogPublishedDateFrom.Value(params.LogPublishedDateFrom);
      C.dateLogPublishedDateTo.Value(params.LogPublishedDateTo);
    }
    else {
      chkPublish_Change(C.chkPublish);
      
      C.dateLogPublishOnDateOnOrBefore.TimeZoneId(params.LogTimeZoneId);
      C.dateLogPublishOnDateOnOrBefore.Value(params.LogPublishOnDateOnOrBefore);
    }
    
    C.lstLogClasses.Text(params.LogClasses);
    C.lstLogFileTypes.Text(params.LogFileTypes);
    C.lstLogStatuses.Text(params.LogStatuses);
    
    // Ranges
    C.txtRangeDocuments.Text(params.RangeDocuments);
    C.txtRangeAccountManagers.Text(params.RangeAccountManagers);
    C.txtRangeAccounts.Text(params.RangeAccounts);
    C.txtRangeAccountApps.Text(params.RangeAccountApps);
    C.txtRangeAccountAppTypes.Text(params.RangeAccountAppTypes);
    C.txtRangeBranches.Text(params.RangeBranches);
    C.txtRangeClientGroups.Text(params.RangeClientGroups);
    C.txtRangeClients.Text(params.RangeClients);
    C.txtRangeClientTypes.Text(params.RangeClientTypes);
    C.txtRangeDepartments.Text(params.RangeDepartments);
    C.txtRangeExternalPartiesDealers.Text(params.RangeExternalPartiesDealers);
    C.txtRangeEntities.Text(params.RangeEntities);
    C.txtRangeMonitorCategoriesA.Text(params.RangeMonitorCategoriesAccountsA);
    C.txtRangeMonitorCategoriesB.Text(params.RangeMonitorCategoriesAccountsB);
    C.txtRangeMonitorCategoriesC.Text(params.RangeMonitorCategoriesAccountsC);
    C.txtRangePools.Text(params.RangePools);
    C.txtRangeProductTypes.Text(params.RangeProductTypes);
    C.txtRangeUserGroups.Text(params.RangeUserGroups);
    C.txtRangeUsers.Text(params.RangeUsers);

//    // Advanced
//    if (!mAdvancedVisible) {
//      var toggle = false;
      
//      if (mLogsToPublish.RangeAccountManagers &amp;&amp; mLogsToPublish.RangeAccountManagers.length != 0 &amp;&amp; mRecord.ShowAccountManagers.toUpperCase() != "TRUE") toggle = true;
//      if (mLogsToPublish.RangeAccounts &amp;&amp; mLogsToPublish.RangeAccounts.length != 0 &amp;&amp; mRecord.ShowAccounts.toUpperCase() != "TRUE") toggle = true;   
//      if (mLogsToPublish.RangeAccountTypes &amp;&amp; mLogsToPublish.RangeAccountTypes.length != 0 &amp;&amp; mRecord.ShowAccountTypes.toUpperCase() != "TRUE") toggle = true;   
//      if (mLogsToPublish.RangeBranches &amp;&amp; mLogsToPublish.RangeBranches.length != 0 &amp;&amp; mRecord.ShowBranches.toUpperCase() != "TRUE") toggle = true;            
//      if (mLogsToPublish.RangeDepartments &amp;&amp; mLogsToPublish.RangeDepartments.length != 0 &amp;&amp; mRecord.ShowDepartments.toUpperCase() != "TRUE") toggle = true;      
//      if (mLogsToPublish.RangeEntities &amp;&amp; mLogsToPublish.RangeEntities.length != 0 &amp;&amp; mRecord.ShowEntities.toUpperCase() != "TRUE") toggle = true;      
//      if (mLogsToPublish.RangeExternalPartiesBrokers &amp;&amp; mLogsToPublish.RangeExternalPartiesBrokers.length != 0 &amp;&amp; mRecord.ShowExternalPartiesBrokers.toUpperCase() != "TRUE") toggle = true;    
//      if (mLogsToPublish.RangeExternalPartiesDealers &amp;&amp; mLogsToPublish.RangeExternalPartiesDealers.length != 0 &amp;&amp; mRecord.ShowExternalPartiesDealers.toUpperCase() != "TRUE") toggle = true;    
//      if (mLogsToPublish.RangePools &amp;&amp; mLogsToPublish.RangePools.length != 0 &amp;&amp; mRecord.ShowPools.toUpperCase() != "TRUE") toggle = true;   
//      if (mLogsToPublish.RangeProductTypes &amp;&amp; mLogsToPublish.RangeProductTypes.length != 0 &amp;&amp; mRecord.ShowProductTypes.toUpperCase() != "TRUE") toggle = true;   

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

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "Parameters":
        // Show only ranges applicable to selected Log Classes
        var arrClasses = C.lstLogClasses.Text().split(",");
        var includeAccount = false, includeAccountApp = false, includeClient = false, includeUser = false;
        for (var i = 0; i &lt; arrClasses.length; i++) {
          switch (arrClasses[i].toUpperCase()) {
            case "ACCOUNT":
              includeAccount = true;
              break;
              
            case "ACCOUNT APPLICATION":
              includeAccountApp = true;
              break;
              
            case "CLIENT":
              includeClient = true;
              break;
              
            case "USER":
              includeUser = true;
              break;
          }
        }
        AdvancedInitialise(includeAccount, includeAccountApp, includeClient, includeUser);
        break;
        
      default:
        break;
    }
  }

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

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

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

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

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

    default:
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Items":
      if (C.chkPublish.Value()) {
        if (mRecord.AutoPublishOpen) {
          frmMain.RefreshHeading("Documents to Publish", "Select Documents to publish. Logs with a publish status of either 'To Send' or 'Open' will be published.");
        }
        else {
          frmMain.RefreshHeading("Documents to Publish", "Select Documents to publish. Only Logs with a publish status of 'To Send' will be published.");
        }
      }
      else {
        frmMain.RefreshHeading("Documents to Republish", "Select Documents to republish.");
      }
      break;
      
    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

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

  // Resize Wizard
  tabWizard_Resize();

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

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters(includeRefreshData) {
  var params = {
    processId: mProcessId,
    
    // General
    Republish: C.chkRepublish.Value(),
    
    LogTimeZoneId: C.chkPublish.Value() ? C.dateLogPublishOnDateOnOrBefore.TimeZoneId() : C.dateLogPublishedDateFrom.TimeZoneId(),
    LogPublishOnDateOnOrBefore: C.dateLogPublishOnDateOnOrBefore.Value(),
    LogPublishedDateFrom: C.dateLogPublishedDateFrom.Value(),
    LogPublishedDateTo: C.dateLogPublishedDateTo.Value(),
    RangePublishedUsers: C.txtRangePublishedUsers.Text(),
    
    LogClasses: C.lstLogClasses.Text(),
    LogFileTypes: C.lstLogFileTypes.Text(),
    LogStatuses: C.lstLogStatuses.Text(),
    
    // Ranges
    RangeDocuments: C.txtRangeDocuments.Text(),
    RangeAccountManagers: C.txtRangeAccountManagers.Text(),
    RangeAccounts: C.txtRangeAccounts.Text(),
    RangeAccountApps: C.txtRangeAccountApps.Text(),
    RangeAccountAppTypes: C.txtRangeAccountAppTypes.Text(),
    RangeBranches: C.txtRangeBranches.Text(),
    RangeClientGroups: C.txtRangeClientGroups.Text(),
    RangeClients: C.txtRangeClients.Text(),
    RangeClientTypes: C.txtRangeClientTypes.Text(),
    RangeDepartments: C.txtRangeDepartments.Text(),
    RangeExternalPartiesDealers: C.txtRangeExternalPartiesDealers.Text(),
    RangeEntities: C.txtRangeEntities.Text(),
    RangeMonitorCategoriesA: C.txtRangeMonitorCategoriesA.Text(),
    RangeMonitorCategoriesB: C.txtRangeMonitorCategoriesB.Text(),
    RangeMonitorCategoriesC: C.txtRangeMonitorCategoriesC.Text(),
    RangePools: C.txtRangePools.Text(),
    RangeProductTypes: C.txtRangeProductTypes.Text(),
    RangeUserGroups: C.txtRangeUserGroups.Text(),
    RangeUsers: C.txtRangeUsers.Text(),
  }

  // Set Refresh Data
  if (includeRefreshData &amp;&amp; mLogsToPublish) {
    params.RefreshData = JSON.stringify(mLogsToPublish);
  }

  return params;
}

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

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

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

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

      // Build Message
      var publishTerminology = C.chkPublish.Value() ? "Publish" : "Republish";
      var countCancel = 0;
      var countIncluded = 0;
      var countToPublish = 0;
      if (mRecord.AutoCommit) {
        message += "&lt;p&gt;Are you sure you want to " + publishTerminology + " all applicable documents?&lt;/p&gt;";
      }
      else {
        for (var i = 0; i &lt; mLogsToPublish.Items.length; i++) {
          var item = mLogsToPublish.Items[i];
          if (item.LogPublishStatus == "Cancel") countCancel += 1;          
          if (item.Include) {
            countIncluded += 1;
            if (C.chkPublish.Value()) {
              if (item.LogPublishStatus == "To Send" || (mRecord.AutoPublishOpen &amp;&amp; item.LogPublishStatus == "Open")) countToPublish += 1;
            }
            else {
              countToPublish += 1;
            }
          }
        }
        if (C.chkPublish.Value()) {
          switch(countToPublish) {
            case 1:
              message += "&lt;p&gt;Are you sure you want to publish &lt;b&gt;1&lt;/b&gt; document?&lt;/p&gt;";
              break;
              
            default:
              message += "&lt;p&gt;Are you sure you want to publish &lt;b&gt;" + countToPublish + "&lt;/b&gt; documents?&lt;/p&gt;";
              break;
          }
        }
      }
      if (!C.chkRepublish.Value()) {
        if (mRecord.AutoPublishOpen) {
          message += "&lt;p&gt;Logs with a publish status of either &lt;b&gt;To Send&lt;/b&gt; or &lt;b&gt;Open&lt;/b&gt; will be published.&lt;/p&gt;";        
        }
        else {
          message += "&lt;p&gt;Only Logs with a publish status of &lt;b&gt;To Send&lt;/b&gt; will be published.&lt;/p&gt;";
        }
      }
      
      // Warnings
      if (countCancel != 0) {
        message += "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Logs with a publish status of 'Cancel' will be deleted.&lt;/p&gt;";
      }

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

      // Confirm
      widget.UI.MsgBoxConfirm(message, { title: publishTerminology + " Documents", messageIsHtml: true }, 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 Document Publish Processing, please wait...");

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

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

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

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

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

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

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

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  var InProgressRefreshComplete = false;

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

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

      // Update Status
      mRecord_BackgroundProcessStatus = data;

      // Refresh Progress
      pageProgress_Refresh();

      // Status
      var Status = mRecord_BackgroundProcessStatus.Status;

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

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Document Publish was successfully cancelled.");
          break;

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

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

          // Refresh Complete
          mRecord_BackgroundProcessStatus = null;

          // Set Tab
          tabWizard.SelectedTabId("Items");
          tabWizard_Refresh();
          
          // Limited results warning
          if (mLogsToPublish.RefreshUnlimitedItemCount &gt; mLogsToPublish.RefreshItemLimit) {
            widget.UI.MsgBoxInfo("&lt;p&gt;For performance reasons, only &lt;b&gt;" + mLogsToPublish.RefreshItemLimit + "&lt;/b&gt; of &lt;b&gt;" + mLogsToPublish.RefreshUnlimitedItemCount + "&lt;/b&gt; items are included in this grid.&lt;/p&gt;&lt;p&gt;This means you will need to run this wizard multiple times to publish all available Documents.&lt;/p&gt;&lt;p&gt;Consider using the filters available on the previous pages to limit the number of Documents to review.&lt;/p&gt;", { messageIsHtml: true })
          }
          break;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          if (InProgressRefreshComplete) {
            widget.UI.MsgBoxInfo("Document Publish Refresh is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          else {
            widget.UI.MsgBoxInfo("Document Publish is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          break;

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

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Document Publish 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();
    }
  );
}

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

  // Block UI
  widget.UI.Block("Refreshing Recent Document Publish Processes, please wait...");

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

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

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

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

  // Stop button valid?
  tabWizard_UpdateButtons()

  // Update Heading
  if (tabWizard.SelectedTabId() == "Progress") {
    if (mLastProcessStatus &amp;&amp; mLastProcessStatus.length != 0) {
      frmMain.RefreshHeading(mLastProcessStatus, "Processing progress.");
    }
    else {
      frmMain.RefreshHeading("Progress", "Processing progress.");
    }
  }
}

function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

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

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

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

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

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

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

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

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

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

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

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

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

  C.gridCurrentProcesses.RefreshButtons();
}

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

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

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

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

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

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

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

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

// =========
// gridItems
// =========
function gridItems_Refresh() {
  // Determine columns to show
  var hasAccounts = false;
  var hasNotes = false;
  var hasWarnings = false;
  for (var i = 0; i &lt; mLogsToPublish.Items.length; i++) {
    var item = mLogsToPublish.Items[i];
    
    if (item.LogClass == "Account") hasAccounts = true;
    if (item.LogNotes) hasNotes = true;
    if (item.Warning) hasWarnings = true;
  }

  // Add Columns
  C.gridItems.ClearColumns();  
  C.gridItems.AddColumnBoolean("Include", { caption: "Include", allowEdit: true, sortable: true });
  C.gridItems.AddColumnDate("LogDate", { caption: "Date", sortable: true });
  C.gridItems.AddColumnIcon("LogClass", { caption: "", sortable: true });
  C.gridItems.AddColumnCode("SourceId", { caption: "ID", sortable: true });
  C.gridItems.AddColumnString("Name", { caption: "Name", sortable: true });
  C.gridItems.AddColumnCode("AccountStatus", { caption: "Status", sortable: true, noWrap: true, visible: hasAccounts });
  C.gridItems.AddColumnCode("DocumentId", { caption: "Document", sortable: true });
  C.gridItems.AddColumnIcon("DocumentFileTypeIcon", { caption: "", sortable: true });  
  C.gridItems.AddColumnString("LogSubject", { caption: "Subject", sortable: true });
  C.gridItems.AddColumnString("LogPublishStatus", { caption: "Publish", width: "6em", sortable: true, allowEdit: true, listCsv: mRecord.LogPublishStatusesGridList });
  C.gridItems.AddColumnCurrency("Fee", { caption: "Fee", sortable: true, allowEdit: true, visible: hasAccounts });
  C.gridItems.AddColumnString("LogNotes", { caption: "Notes", sortable: true, visible: hasNotes });  
  C.gridItems.AddColumnString("Warning", { caption: "Warning", sortable: true, visible: hasWarnings });

  // Actions
  
  C.gridItems.Actions().Define([]);
  
  // Actions
  var actions = [
    { actionId: "Refresh", tooltipText: "Refresh", icon: "Refresh"},
    {},
    { actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
    { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
    { 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: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
    { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
  ];
  if (C.chkPublish.Value()) {
    actions.push({});
    actions.push({ actionId: "StatusOpen", tooltipText: "Set selected row(s) to 'Open'", icon: "DocumentStatus_Open", caption: "Open" });
    actions.push({ actionId: "StatusToSend", tooltipText: "Set selected row(s) to 'To Send'", icon: "DocumentStatus_ToSend", caption: "To Send" });
    actions.push({ actionId: "StatusNotIssued", tooltipText: "Set selected row(s) to 'Not Issued'", icon: "DocumentStatus_NotIssued", caption: "Not Issued" });
    actions.push({ actionId: "StatusCancel", tooltipText: "Set selected row(s) to 'Cancel'", icon: "DocumentStatus_Cancel", caption: "Cancel" });
    actions.push({});
    actions.push({ actionId: "Save", tooltipText: "Save changes to Logs", icon: "Save" });
  }
  if (hasNotes) {
    actions.push({});
    actions.push({ actionId: "CompactView", tooltipText: "Compact View (single line)", icon: "Grid_CompactView", checked: mCompactView });
  }
  C.gridItems.Actions().Define(actions);

  // Refresh
  C.gridItems.VirtualDataRefresh(mLogsToPublish.Items);

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

function gridItems_Action(actionId) {
  var selectedItems = C.gridItems.GetSelectedRowIndexes(true, true);
  
  switch (actionId.toUpperCase()) {
    case "REFRESH":
      // Clear Cache
      mLastRefreshParametersJson = "";

      // Refresh
      RefreshLogsToPublish(true);
      break;
      
    case "CHECK":
    case "UNCHECK":
      // Update Include Checkbox
      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mLogsToPublish.Items[selectedItems[i]];
        item.Include = (actionId.toUpperCase() == "CHECK")
      }
      C.gridItems.VirtualDataRefresh(mLogsToPublish.Items, true, { retainSelectedRows: true });
      break;
      
    case "COMPACTVIEW":
      // Compact View
      mCompactView = !mCompactView;
      gridItems_RefreshButtons();
      C.gridItems.VirtualDataRefresh(mLogsToPublish.Items, true, { retainSelectedRows: true });
      break;
      
    case "SELECTALL":
      // Select All
      C.gridItems.SelectAllRows(true);
      break;

    case "SELECTNONE":
      // Select None
      C.gridItems.SetSelectedRowIndexes([], true);
      break;
   
    case "SELECTUP":
      // Select Up
      // NOTE: Because this grid is sortable, we use ActiveDataRowIndex rather than ActiveDataRowListIndex
      var indexes = [];
      for (var i = C.gridItems.ActiveDataRowIndex(); i &gt;= 0; i--) {
        indexes.push(i);
      }
      
      // NOTE: Because this grid is sortable, we use SetSelectedRowIndexesForSortableGrid rather than SetSelectedRowIndexes
      C.gridItems.SetSelectedRowIndexesForSortableGrid(indexes, true);
      break;
      
    case "SELECTDOWN":
      // Select Down
      // NOTE: Because this grid is sortable, we use ActiveDataRowIndex rather than ActiveDataRowListIndex
      var indexes = [];
      for (var i = C.gridItems.ActiveDataRowIndex(); i &lt; mLogsToPublish.Items.length; i++) {
        indexes.push(i);
      }
      
      // NOTE: Because this grid is sortable, we use SetSelectedRowIndexesForSortableGrid rather than SetSelectedRowIndexes
      C.gridItems.SetSelectedRowIndexesForSortableGrid(indexes, true);
      break;
      
    case "SAVE":
      // Save
      var countCancel = 0;
      for (var i = 0; i &lt; mLogsToPublish.Items.length; i++) {
        var item = mLogsToPublish.Items[i];
        if (item.LogPublishStatus == "Cancel") countCancel += 1;
      }
      
      var message = "&lt;p&gt;Save any changes you have made to Log publish statuses?&lt;/p&gt;";
      if (countCancel != 0) {
        message += "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Logs with a publish status of 'Cancel' will be deleted.&lt;/p&gt;";
      }
      
      widget.UI.MsgBoxConfirm(message, { title: "Save Changes",  messageIsHtml: true }, gridItems_Action_Save);
      break;
    
    case "STATUSOPEN":  
    case "STATUSNOTISSUED":
    case "STATUSTOSEND":
    case "STATUSCANCEL":
      // Update Status
      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mLogsToPublish.Items[selectedItems[i]];
        switch(actionId.substr(6).toUpperCase()) {
          case "OPEN":
            item.LogPublishStatus = "Open";
            break;
            
          case "NOTISSUED":
            item.LogPublishStatus = "Not Issued";
            break;

          case "TOSEND":
            item.LogPublishStatus = "To Send";
            break;

          case "CANCEL":
            item.LogPublishStatus = "Cancel";
            break;
        }
      }
      C.gridItems.VirtualDataRefresh(mLogsToPublish.Items, true, { retainSelectedRows: true });
      break;
  }
}

function gridItems_Action_Save() {
  // Parameters
  var params = CreateFinishParameters(true);
  
  // Update Refresh Data
  widget.GetString("Save", params, 
    function (data) {
      // Unblock
      widget.UI.Unblock();
      
      // Remove "Deleted" items from collection
      for (var i = 0; i &lt; mLogsToPublish.Items.length; i++) {
        var item = mLogsToPublish.Items[i];
        if (item.LogPublishStatus == "Cancel") {
          widget.ArrayRemove(mLogsToPublish.Items, item);
        }
      }
      
      // Refresh
      C.gridItems.VirtualDataRefresh(mLogsToPublish.Items);
    },
    
    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();
    
      // Error
      widget.UI.MsgBoxAlert(errorMessage);
  });
}

function gridItems_AfterRowActivate(e) {
  // Refresh Buttons
  gridItems_RefreshButtons();
}

function gridItems_RefreshButtons() {
  var hasSelected = C.gridItems.GetSelectedRowIndexes(true, true).length != 0;
  
  C.gridItems.Actions().SetEnabled("Check", hasSelected);
  C.gridItems.Actions().SetEnabled("Uncheck", hasSelected);
  C.gridItems.Actions().SetEnabled("StatusOpen", hasSelected);
  C.gridItems.Actions().SetEnabled("StatusToSend", hasSelected);
  C.gridItems.Actions().SetEnabled("StatusNotIssued", hasSelected);
  C.gridItems.Actions().SetEnabled("StatusCancel", hasSelected);
  C.gridItems.Actions().SetChecked("CompactView", mCompactView);

  C.gridItems.RefreshButtons();
}

function gridItems_BeforeCellUpdate(e) {
  var item = mLogsToPublish.Items[e.row.listIndex];

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

function gridItems_InitialiseRow(e) {
  var item = mLogsToPublish.Items[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);
  
  // Fee
  if (!item.ChargeFee) {
    e.row.cells.Fee.value = null;
    e.row.cells.Fee.readOnly = true;
  }
  
  // Compact View
  if (mCompactView) {
    var s = item.LogNotes;
    if (s) {
      var i = s.indexOf("\r");
      if (i != -1) {
        e.row.cells.LogNotes.value = s.substr(0, i) + "...";
      }
    }
  }
  
  // File Type Icon
  switch(item.DocumentFileType) {
    case "Email":
      e.row.cells.DocumentFileTypeIcon.value = "Email";
      break;
  
    case "ExcelDocument":
      e.row.cells.DocumentFileTypeIcon.value = "DocumentType_Excel";
      break;

    case "Script":
      e.row.cells.DocumentFileTypeIcon.value = "Script";
      break;

    case "Sms":
      e.row.cells.DocumentFileTypeIcon.value = "Sms";
      break;
  
    case "WordDocument":
      e.row.cells.DocumentFileTypeIcon.value = "DocumentType_Word";
      break;
  }
  
  //e.row.cells.LogClassIcon = item.LogClass;
  //e.row.cells.DocumentFileTypeIcon = item.DocumentFileType;

  // Read-Only
  e.row.cells.LogDate.readOnly = true;
  e.row.cells.LogClass.readOnly = true;
  e.row.cells.SourceId.readOnly = true;
  e.row.cells.Name.readOnly = true;
  e.row.cells.AccountStatus.readOnly = true;
  e.row.cells.DocumentId.readOnly = true;
  e.row.cells.DocumentFileTypeIcon.readOnly = true;
  e.row.cells.LogSubject.readOnly = true;
  e.row.cells.LogNotes.readOnly = true;
  e.row.cells.Warning.readOnly = true;
  if (!item.CanPublish) {
    e.row.cells.Include.readOnly = true;
    e.row.cells.LogPublishStatus.readOnly = true;
    e.row.cells.Fee.readOnly = true;
  }
  if (C.chkRepublish.Value()) {
    e.row.cells.LogPublishStatus.readOnly = true;
  }
  
  // Styling
  e.row.cells.Name.small = true;
  e.row.cells.LogNotes.small = true;
  e.row.cells.Warning.colour = "red";
  e.row.cells.Warning.small = "red";

  // Hyperlinks
  e.row.cells.SourceId.hyperlink = "app://FormShow?form=" + item.LogClass + "&amp;id=" + widget.UI.HtmlEncode(item.SourceId);
  e.row.cells.LogSubject.hyperlink = "app://FormShow?form=" + item.LogClass + "Log&amp;id=" + widget.UI.HtmlEncode(item.LogPk) + "&amp;readOnly=true";
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Document Publish Processing is still running.\n\nThis will continue to run and you can re-open this form at any time to check on its status.\n\n\Close this form?", {}, tabWizard_Cancel_Post);
  }
  else if (mProcessId &amp;&amp; (tabWizard.SelectedTabId() == "Items" || mLogsToPublish)) {
    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." });
    if (mRecord.AllowCancel) {
      list.push({ key: "CANCEL", caption: "Close and Cancel", icon: "Trash", details: "This will close the wizard and cancel this process. The list of Logs to Publish will not be retained." });
    }

    var options = {
      closeOnEscape: true,
      title: "Close Publish Documents",
      showClose: true
    };

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

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

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

  // Parameters
  var params = CreateFinishParameters(true);

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

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

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

function tabWizard_Move(direction) {
  var Ok;

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

        default:
          found = true;
          break;
      }

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

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    default:
      break;
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (widget.CompareDates(C.dateLogPublishedDateFrom.Value(), C.dateLogPublishedDateTo.Value()) == 1) {
          Ok = false;
          widget.UI.MsgBoxAlert("Published 'From' date cannot be after the 'To' date.");
          C.dateLogPublishedDateFrom.Focus();
        }
        break;
        
      case "Parameters":
        if (Ok) {
          tabWizard_ValidatePost_Parameters(validCallback);
          return; 
        }
    
      case "Items":
        var found = false;
        for (var i = 0; i &lt; mLogsToPublish.Items.length; i++) {
          var item = mLogsToPublish.Items[i];
          if (item.Include) {
            found = true;
            break;
          }
        }

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

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

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

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

    // Callback
    validCallback();
  }
}

function tabWizard_ValidatePost_Parameters(validCallback) {
  // Refresh
  if (!mRecord.AutoCommit) RefreshLogsToPublish();

  // Callback
  validCallback();
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Advanced handling
// =================
function AdvancedInitialise(includeAccount, includeAccountApp, includeClient, includeUser) {
  // Initialise
  mPageParametersHasAdvanced = false;

  // Tweaks

  // Parameters
  AdvancedInitialiseSection("AccountManagers", mRecord.ShowAccountManagers, !includeAccount);
  AdvancedInitialiseSection("Accounts", mRecord.ShowAccounts, !includeAccount);
  AdvancedInitialiseSection("AccountApps", mRecord.ShowAccountApps, !includeAccountApp);
  AdvancedInitialiseSection("AccountAppTypes", mRecord.ShowAccountAppTypes, !includeAccountApp);
  AdvancedInitialiseSection("Branches", mRecord.ShowBranches, !includeAccount &amp;&amp; !includeAccountApp &amp;&amp; !includeClient);
  AdvancedInitialiseSection("ClientGroups", mRecord.ShowClientGroups, !includeClient);
  AdvancedInitialiseSection("Clients", mRecord.ShowClients, !includeClient);
  AdvancedInitialiseSection("ClientTypes", mRecord.ShowClientTypes, !includeClient);
  AdvancedInitialiseSection("Departments", mRecord.ShowDepartments, !includeAccount &amp;&amp; !includeAccountApp);
  AdvancedInitialiseSection("ExternalPartiesDealers", mRecord.ShowExternalPartiesDealers, !includeAccount &amp;&amp; !includeAccountApp);
  AdvancedInitialiseSection("Entities", mRecord.ShowEntities, !includeAccount &amp;&amp; !includeAccountApp &amp;&amp; !includeClient);
  AdvancedInitialiseSection("MonitorCategoriesAccountsA", mRecord.ShowMonitorCategoriesAccountsA, !includeAccount &amp;&amp; !includeAccountApp);
  AdvancedInitialiseSection("MonitorCategoriesAccountsB", mRecord.ShowMonitorCategoriesAccountsB, !includeAccount &amp;&amp; !includeAccountApp);
  AdvancedInitialiseSection("MonitorCategoriesAccountsC", mRecord.ShowMonitorCategoriesAccountsC, !includeAccount &amp;&amp; !includeAccountApp);
  AdvancedInitialiseSection("Pools", mRecord.ShowPools, !includeAccount);
  AdvancedInitialiseSection("ProductTypes", mRecord.ShowProductTypes, !includeAccount);
  AdvancedInitialiseSection("UserGroups", mRecord.ShowUserGroups, !includeUser);
  AdvancedInitialiseSection("Users", mRecord.ShowUsers, !includeUser);
}

function AdvancedInitialiseSection(id, option, alwaysHide) {
  // Get elements
  var els=$("*[advancedId='" + id + "']");
  if (els.length == 0) window.alert("none for " + id);

  // Update
  switch(option.toUpperCase()) {
    case "TRUE":
      // Always show, i.e., not advanced
      if (alwaysHide) {
        // Hide, e.g., not showing User Log filters
        els.hide();
      }
      else {
        els.show();      
      }
      break;

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

    case "ADVANCED":
      // Only show in 'Advanced' mode
      if (alwaysHide) {
        // Hide, e.g., not showing User Log filters
        els.hide();
      }
      else {
        els.show();
        els.addClass("advanced");
        mPageParametersHasAdvanced = true;
      }
      break;
  }
}

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

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

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

  // Finalise
  //AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

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

    // Confirmation Message
    var message = "";

    // Build Message
    message += "&lt;p&gt;Click OK to build a list of Logs to publish.&lt;/p&gt;";

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

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

    // Confirm
    var options = {
      heading: "Refresh Logs to Publish",
      messageIsHtml: true,
      icon: "Table|Refresh"
    }
    widget.UI.MsgBoxConfirm(message, options,
      function () {
        if (mLogsToPublish &amp;&amp; mProcessId) {
          CancelRefreshCompleteBackgroundProcess(mProcessId, fromGridAction, RefreshLogsToPublish_Post, function() {
            // Move back a page
            tabWizard_Move(-1);

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

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

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

function RefreshLogsToPublish_Post() {
  // Running new process
  mMonitoringExisting = false;
  mLogsToPublish = null;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Getting Logs to Publish, please wait...");

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

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

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

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

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

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

      // Show content
      frmMain.Visible(true);

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

// ==========================================
// Cancel Refresh Complete Background Process
// ==========================================
function CancelRefreshCompleteBackgroundProcess(processId, noPrompt, callback, cancelCallback) {
  if (noPrompt) {
    // Cancel immediately
    CancelRefreshCompleteBackgroundProcess_Execute(processId, callback);
  }
  else {
    // Prompt
    widget.UI.MsgBoxConfirm("Are you sure you want to cancel this Background Process?", {},
      function() {
        CancelRefreshCompleteBackgroundProcess_Execute(processId, callback);
      },

      cancelCallback
    );
  };
}

function CancelRefreshCompleteBackgroundProcess_Execute(processId, callback) {
  // Block
  widget.UI.Block("Cancelling Background Process, please wait...");

  // Params
  var params = {
    processId: processId,
  }

  widget.GetString("CancelBackgroundProcess", params, function() { callback(); }, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();

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

// ===================================
// View an existing Background Process
// ===================================
function ViewExistingProcess(itemIndex) {
  var item = mRecord_CurrentProcesses[itemIndex];
  var Ok = true;
  
  // Validate
  if (item.Status == "InProgressRefreshComplete" &amp;&amp; mRecord.AutoCommit) {
    Ok = false;
    widget.UI.MsgBoxInfo("Cannot resume a two-phase Process when this HTML Widget is configured to run in single-phase (Auto Commit) mode.");
  }

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

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

        // Update Controls
        Fields_Update_FromBackgroundProcess(JSON.parse(item.ScriptParametersJson));

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

        // Set Tab
        tabWizard.SelectedTabId("Items");
        tabWizard_Refresh();
        
        // Limited results warning
        if (mLogsToPublish.RefreshUnlimitedItemCount &gt; mLogsToPublish.RefreshItemLimit) {
          widget.UI.MsgBoxInfo("&lt;p&gt;For performance reasons, only &lt;b&gt;" + mLogsToPublish.RefreshItemLimit + "&lt;/b&gt; of &lt;b&gt;" + mLogsToPublish.RefreshUnlimitedItemCount + "&lt;/b&gt; items are included in this grid.&lt;/p&gt;&lt;p&gt;This means you will need to run this wizard multiple times to publish all available Documents.&lt;/p&gt;&lt;p&gt;Consider using the filters available on the previous pages to limit the Documents the number of Documents to review.&lt;/p&gt;", { messageIsHtml: true })
        }
        break;

      default:
        mFromRecent = true;
        mMonitoringExisting = true;

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

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

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

    range = range.substr(8);
    if (range.startsWith("Payee")) range = "ExternalParties" + range.substr(5);
    if (range.startsWith("PublishedUsers")) range = "Users";
    
    if (range.startsWith("AccountUser")) {
      // Find the correct Account User options
      for (var i = 0; i &lt; mRecord.AccountUsers.length; i++) {
        var item = mRecord.AccountUsers[i];
        
        if (range == "Account" + item.IdField) {
          caption = item.Caption;
          sql = item.RangeLookupSql;
          idField = item.IdField;
          break;
        }
      }
      
      // Show Lookup
      if (idField) {
        widget.UI.Forms.ShowRangeLookupFromDatabase(sender.Text(), { idField: idField, rangeLookupSql: sql, caption: caption },
          function (newRange) {
            sender.Text(newRange);
            sender.Focus();
          }
        );
      }
      else {
        widget.UI.MsgBoxAlert("Could not determine Range Lookup for the selected Account User field.");
      }      
    }
    else {
      widget.UI.Forms.ShowRangeLookupFromStandardRange(range, sender.Text(), { caption: "Lookup " + caption},
        function (newRange) {
          sender.Text(newRange);
          sender.Focus();
        }
      );
    }    
  }
}

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

    default:
      break;
  }
}

// ==========
// chkPublish
// ==========
function chkPublish_Change(sender, e) {
  C.chkPublish.Value(sender === C.chkPublish);
  C.chkRepublish.Value(sender === C.chkRepublish);
  
  // Controls
  C.dateLogPublishOnDateOnOrBefore.VisibleRow(C.chkPublish.Value());
  C.dateLogPublishedDateFrom.VisibleRow(C.chkRepublish.Value());
  C.dateLogPublishedDateTo.VisibleRow(C.chkRepublish.Value());
  C.txtRangePublishedUsers.VisibleRow(C.chkRepublish.Value());
  C.lstLogStatuses.VisibleRow(C.chkRepublish.Value());
  
  // Focus
  if (e) {
    if (C.chkPublish.Value()) {
      C.dateLogPublishOnDateOnOrBefore.Focus();
    }
    else {
      C.dateLogPublishedDateFrom.Focus();
    }
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>0</TimeoutSeconds>
    <UniqueId>5-B-6PbQ5kCisA3DR55HHw</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>2000</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1400</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="ShowAccountManagers" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccounts" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccountApps" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccountAppTypes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowBranches" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowClientGroups" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowClients" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowClientTypes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowDepartments" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowExternalPartiesDealers" type="List">
            <BlankTip />
            <Caption>Show Dealers</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowEntities" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowMonitorCategoriesAccountsA" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowMonitorCategoriesAccountsB" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowMonitorCategoriesAccountsC" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowPools" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowProductTypes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowUserGroups" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowUsers" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowLogNotes" type="Boolean">
            <BlankTip />
            <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>True</Value>
            <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="AutoPublishOpen" type="Boolean">
            <BlankTip />
            <Caption>Auto Publish 'Open' items?</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="RefreshItemLimit" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>2500</Value>
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="PermissionKeyCancel" 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 />
            <Visible>true</Visible>
            <List>RANGE.Permissions</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </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>Desktop Mode (testing only)</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>