<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-22T00:24:22.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-08-22T00:21:59.5630000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-22T00:23:47.3130000</UpdatedUtcDate>
    <ScriptId>DEX</ScriptId>
    <Description>Document Execute</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_DocumentExecute
Option Explicit On
Option Strict On

' #################################################################
' Document Execute wizard
'
' Version: 1.04 (22/08/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  19/11/2021  ISS      J027315   Created
'    1.01  08/12/2021  ISS      J027840   Spelling Correction
'    1.02  07/06/2022  ISS      J028452   User Defined fields not retaining indexes
'    1.03  29/09/2022  ISS      J029737   Implemented widget.UI.BuildBackgroundProcessProgress
'    1.04  22/08/2024  ISS      J034139   Email options were hidden if using Exchange instead of SMTP
' #################################################################

' Constants
Private Const FORM_KEY As String = "DocumentExecute"

' Common Parameters
Private mDocumentId As String
Private mFileType As iseDocumentFileType
Private mFilterByDocumentType As Boolean
Private mFilterByFileType As Boolean
Private mDocumentType As isefinDocumentType
Private mDocumentTypeText As String
Private mOnlyIncludeDocumentsFlaggedForCloud As Boolean

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

' Other
Private mAutoCommit As Boolean
Private mHostingContext As isefinHtmlWidgetHostingContext
Private mProcessId As String


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

  ' Assume Success
  Main = True

  ' Initialise
  mHostingContext = hostingContext

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

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

  ' Get Common Parameters
  With mCombinedParameters
    mAutoCommit = .GetBoolean("AutoCommit")
    mDocumentId = .GetString("DocumentId")
    If Len(mDocumentId) = 0 Then mDocumentId = .GetString("id")
    mDocumentType = DirectCast(.GetEnum("DocumentType", GetType(isefinDocumentType)), isefinDocumentType)
    mDocumentTypeText = .GetString("DocumentType")
    mFilterByDocumentType = .GetBoolean("FilterByDocumentType")
    mFileType = DirectCast(.GetEnum("FileType", GetType(iseDocumentFileType)), iseDocumentFileType)
    mFilterByFileType = .GetBoolean("FilterByFileType")
    mOnlyIncludeDocumentsFlaggedForCloud = .GetBoolean("OnlyIncludeDocumentsFlaggedForCloud")
    mProcessId = .GetString("ProcessId")
  End With

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

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

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

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

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

    Case "GetDocument"
      ' Get Document
      Main = GetDocument(returnValue)

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

    Case "GetItemPreview"
      ' Get Item Preview
      Main = GetItemPreview(parametersJson, returnValue)

    Case "GetSmsInfo"
      ' Get SMS Information
      Main = GetSmsInfo(parametersJson, returnValue)

    Case "Refresh"
      ' Refresh (and Execute Commit, if in Auto Commit mode)
      Main = Refresh(parametersJson, returnValue)

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

    Case "WizardValidate"
      ' Validate wizard page
      Main = WizardValidate(parametersJson, returnValue)

    Case Else
      finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
      Main = False
  End Select

End Function

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

  Dim Branch As finBranchRO
  Dim DocumentExecute As finDocumentExecute
  Dim FormInitialisationInfo As FormInitialisationInfo
  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.DocumentExecute)
  End If

  ' Create Document Execute object
  If Success Then
    Success = CreateDocumentExecute(DocumentExecute, Nothing)
  End If

' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' General
      .DocumentId = mDocumentId
      .DocumentType = If(len(mDocumentTypeText) = 0, "", mDocumentType.ToString())
      .FilterByDocumentType = mFilterByDocumentType
      .ProcessId = mProcessId

      ' Documents List
      .Documents = DocumentExecute.GetDocumentsListAsHtmlWidgetJsonObject(mFilterByDocumentType, mDocumentType, mFilterByFileType, mFileType, mOnlyIncludeDocumentsFlaggedForCloud, mDocumentId, True)

      ' Lists

      ' Global Collections
      For Each Branch In finBL.Branches
        If Branch.Active Then
          .Branches.Add(New BranchInfo(finBL, Branch))
        End If
      Next

      ' Configuration
      .AddOnAccountApplication = finBL.Settings.AddOns.AccountApplication
      .AddOnCostCentre = finBL.Settings.AddOns.CostCentre
      .AddOnSecurityRegister = finBL.Settings.AddOns.SecurityRegister
      .AutoCommit = mAutoCommit
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      .TestMode = finBL.SettingsUser.CostCentreTestModeResolved
    End With

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

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Document (used when viewing a current Process with a Status of 'InProgressRefreshComplete').
''' &lt;/summary&gt;
Private Function GetDocument(ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim DocumentExecute As finDocumentExecute
  Dim DocumentId As String
  Dim Documents As List(Of finDocumentExecute.jsonDocument)
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Create Document Execute object
  If Success Then
    If CreateDocumentExecute(DocumentExecute, Nothing) Then
      Success = DocumentExecute.InitialiseDocument(DocumentId)
    Else
      Success = False
    End If
  End If

  ' Get Document
  If Success Then
    Documents = DocumentExecute.GetDocumentsListAsHtmlWidgetJsonObject(,,,,,DocumentId, True)
    If Documents.Count = 0 Then
      Success = False
      finBL.Error.ErrorBeginFormat("Document '{0}' not found.", DocumentId)
    Else
      Data = New With {
        .Document = Documents(0),
        .Record_Document = GetDocumentDetails(documentExecute)
      }
    End If
  End If

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

  Return Success

End Function

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

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  DocumentExecute = finBL.CreateDocumentExecute()

  ' Update
  If Success Then
    If parameters IsNot Nothing AndAlso Len(parameters.DocumentId) &lt;&gt; 0 Then
      With DocumentExecute
        ' Initialise Document
        Success = .InitialiseDocument(parameters.DocumentId)

        ' Other (no point unless Document has been set)
        If Success Then
          ' General
          If parameters.ActionTzDate IsNot Nothing Then
            .ActionTimeZoneId = parameters.ActionTimeZoneId
            .ActionTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(parameters.ActionTzDate)
          End If
          .EmailDocument = parameters.EmailDocument
          .GenerateLogs = parameters.GenerateLogs
          .LogSeverityId = parameters.LogSeverityId
          If parameters.LogTzDate IsNot Nothing Then
            .LogTimeZoneId = parameters.LogTimeZoneId
            .LogTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(parameters.LogTzDate)
          End If

          ' Parameters
          .ParametersUpdateFromHtmlWidgetJsonString(parameters.ParametersJson)

          ' File Type-specific
          Select Case .Document.FileType
            Case iseDocumentFileType.Email
              ' =====
              ' Email
              ' =====
              .EmailSubject = parameters.EmailSubject
              .EmailMessage = parameters.EmailMessage

            Case iseDocumentFileType.Log
              ' ===
              ' Log
              ' ===
              .LogSubject = parameters.LogSubject
              .LogMessage = parameters.LogMessage

            Case iseDocumentFileType.Sms
              ' ===
              ' SMS
              ' ===
              .BranchId = parameters.BranchId
              .SmsMessage = parameters.SmsMessage
              .SmsServiceId = parameters.SmsServiceId
          End Select
        End If
      End With
    End If
  End If

  Return Success

End Function

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

  Dim DocumentExecute As finDocumentExecute
  Dim ProcessId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Validate

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get finDocumentExecute Object
  If Success Then
    Success = CreateDocumentExecute(DocumentExecute, WizardFinishParameters)
  End If

  ' Queue Background Process
  If Success Then
    ' Start Refresh Process
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_DocumentExecute_Refresh(DocumentExecute, mAutoCommit, ProcessId)
  End If

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

  Return Success

End Function

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

  Dim DocumentExecute As finDocumentExecute
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Validate

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get finDocumentExecute Object
  If Success Then
    Success = CreateDocumentExecute(DocumentExecute, WizardFinishParameters)
  End If

  ' Certain Document Types, e.g., Word Documents do not need to Refresh a list of Recipients and so can simulate an 'Auto-Commit'
  If Success Then
    If mAutoCommit Then
      ' Widget is configured to auto-commit anyway
    Else
      If finBL.Documents.Exists(WizardFinishParameters.DocumentId) Then
        Select Case finBL.Documents(WizardFinishParameters.DocumentId).FileType
          Case iseDocumentFileType.Email, iseDocumentFileType.Log, iseDocumentFileType.Sms
          Case Else
            mAutoCommit = True
        End Select
      End If
    End If
  End If

  ' Queue Background Process
  If Success Then
    If mAutoCommit Then
      ' Queue 'Refresh' with mAutoCommit True will perform an Execute Commit automatically
      Success = Me.Refresh(parametersJson, returnValue)
    Else
      ' Queue Background Process
      ' NOTE: DocumentExecute object is supplied as well as RefreshData (recipients grid) since parameters such as Log details are entered at the end of the wizard
      If Success Then
        Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_DocumentExecute_ExecuteCommit(WizardFinishParameters.ProcessId, DocumentExecute, WizardFinishParameters.RefreshData)
      End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  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;
'''  Get Item Preview (e.g., Email or SMS).
''' &lt;/summary&gt;
Private Function GetItemPreview(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim DocumentExecute As finDocumentExecute
  Dim ProcessStatus As finCloudConnectProcessStatus
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get finDocumentExecute Object
  If Success Then
    Success = CreateDocumentExecute(DocumentExecute, WizardFinishParameters)
  End If

  ' Update Refresh Data (Recipients)
  ' NOTE: Not passed back from client-side since we can access it here
  If Success Then
    ' Get Background Processes Status
    If finBL.HtmlWidgetUtilities.GetBackgroundProcessStatusObject(mProcessId, ProcessStatus) Then
      ' Update Recipients (using a method specific to retrieving a message preview)
      Success = DocumentExecute.RecipientsFromBackgroundProcessRefreshData(ProcessStatus.RefreshData)
    Else
      Success = False
    End If
  End If

  ' Get Item Preview
  If Success Then
    returnValue = DocumentExecute.GetMessagePreviewHtml(WizardFinishParameters.PreviewIndex)
  End If

  ' Error
  If Not Success Then
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message(True))
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Information about an SMS Message.
''' &lt;/summary&gt;
Private Function GetSmsInfo(parametersJson As String,
                            ByRef returnValue As String) As Boolean

  Dim DocumentExecute As finDocumentExecute
  Dim obj As Object
  Dim SmsInformation As ISSmsInformation
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Document Execute object
  If Success Then
    Success = CreateDocumentExecute(DocumentExecute, WizardFinishParameters)
  End If

  ' Get SMS Information
  If Success Then
    SmsInformation = DocumentExecute.GetSmsInformation()
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(SmsInformation.ToHtmlWidgetJsonObject(), returnValue)
  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.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim ConfirmList As New List(Of String)
  Dim DocumentExecute As finDocumentExecute
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim obj As Object
  Dim PageId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Parse Parameters
  ' NOTE: parametersJson will always be WizardFinishDetails object for this wizard
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(WizardFinishParameters), obj) Then
    WizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If

  ' Create Document Create object
  ' NOTE: This is required for all pages that have server-side validation
  If Success Then
    Success = CreateDocumentExecute(DocumentExecute, WizardFinishParameters)
  End If

  ' Validate
  If Success Then
    Select Case PageId
      Case "General"
        Data = GetDocumentDetails(DocumentExecute)
    End Select
  End If

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

  Return Success

End Function

Private Function GetDocumentDetails(documentExecute As finDocumentExecute) As Object

  Dim Data As Object
  Dim Document As finDocumentRO
  Dim ExternalPartiesFilter As String
  Dim TagsList As Object
  Dim TagsListEmailSubject As Object

  ' Initialise
  Document = documentExecute.Document

  ' External Parties Filter?
  ExternalPartiesFilter = finBL.ExternalParties.GetDataViewFilter_Categories(Document.ExternalPartyCategories)

  ' Tags
  Select Case DocumentExecute.Document.FileType
    Case iseDocumentFileType.Email, iseDocumentFileType.Log, iseDocumentFileType.Sms
      TagsList = DocumentExecute.GetSourceTagList(False).ToCodeDescriptionList().ToJsonObject()
  End Select

  Data = New With {
    .Parameters = DocumentExecute.ParametersAsWsParameters(),
    .AllowModify = Document.TemplateAllowModify,
    .AllowEmailDocument = Document.EmailDocument &lt;&gt; iseYesNoPrompt.No AndAlso finBL.SettingsUser.EmailIsUnattendedAvailable(),
    .EmailDocumentDefault = Document.EmailDocument = iseYesNoPrompt.Yes,
    .ChargeFee = Document.ChargeFee,
    .CanChargeFee = Document.DocumentType = isefinDocumentType.Account,
    .DefaultBranchId = DocumentExecute.BranchId,
    .DefaultFee = Document.Fee,
    .EmailHtml = Document.EmailHtml,
    .EmailSubject = Document.TemplateSubject,
    .EmailMessage = Document.TemplateMessage,
    .SmsMessage = Document.TemplateMessage,
    .LogSubject = Document.TemplateSubject,
    .LogMessage = Document.TemplateMessage,
    .GenerateLogs = (Document.GenerateLog &lt;&gt; iseYesNoPrompt.No),
    .Tags = TagsList,
    .TagsEmailSubject = TagsListEmailSubject
  }

  Return Data

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;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

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

  ' General
  Public DocumentId As String
  Public DocumentType As String
  Public FilterByDocumentType As Boolean
  Public ProcessId As String

  ' Lists
  Public Documents As Object

  ' Global Collections
  Public Branches As New List(Of BranchInfo)

  ' Configuration
  Public AddOnAccountApplication As Boolean
  Public AddOnCostCentre As Boolean
  Public AddOnSecurityRegister As Boolean
  Public AutoCommit As Boolean
  Public PromptOnCommit As Boolean
  Public TestMode 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

  ' Wizard Validation
  Public PageId As String

  ' Document
  Public DocumentId As String

  ' Process
  Public ProcessId As String
  Public RefreshData As String

  ' General
  Public ParametersJson As String

  ' Email-specific
  Public EmailSubject As String
  Public EmailMessage As String

  ' SMS-specific
  Public BranchId As String
  Public SmsServiceId As String
  Public SmsMessage As String

  ' Log-specific
  Public LogSubject As String
  Public LogMessage As String

  ' Notes
  Public ActionTimeZoneId As String
  Public ActionTzDate As Date?
  Public EmailDocument As Boolean
  Public LogSeverityId As String
  Public GenerateLogs As Boolean
  Public LogTimeZoneId As String
  Public LogTzDate As Date?

  ' Previewing an Item (e.g., Email or SMS)
  Public PreviewIndex As Integer

End Class



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

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

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

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

  End Sub

End Class



''' &lt;summary&gt;
'''  Branch details.
''' &lt;/summary&gt;
Public Class BranchInfo

  Public BranchId As String
  Public DefaultMessagingSmsServiceId As String
  Public Description As String
  Public Services As New List(Of ServiceDetails)

  Public Sub New(finBL As ISfinSupport,
                 branch As finBranchRO)

    Dim CostCentrePk As Integer
    Dim Item As ISCodeDescriptionListItem
    Dim ServicesList As ISCodeDescriptionList

    With branch
      ' General
      Me.BranchId = .BranchId
      Me.Description = .Description
      Me.DefaultMessagingSmsServiceId = finBL.CostCentresResolved.ItemByBranchPk(.Pk).DefaultMessagingSmsServiceId

      ' Create Service Details
      ServicesList = .GetMessagingSmsServicesList()
      For Each Item In ServicesList
        ' Get Cost Centre
        If Not finBL.CostCentreFunctions.GetCostCentreFromBranchAndService(Me.BranchId, Item.Code, CostCentrePk) Then
          ' Ignore Errors
        End If

        If CostCentrePk = 0 Then
          Me.Services.Add(New ServiceDetails(Item.Code, Item.Description, "", ""))
        Else
          With finBL.CostCentres.ItemByPk(CostCentrePk)
            Me.Services.Add(New ServiceDetails(Item.Code, Item.Description, .CostCentreId, .Description))
          End With
        End If
      Next

      ' Clear Default Messaging Service if not in list (e.g., Test Mode and not configured)
      If Not ServicesList.Exists(Me.DefaultMessagingSmsServiceId) Then Me.DefaultMessagingSmsServiceId = ""
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Service details.
''' &lt;/summary&gt;
Public Class ServiceDetails

  Public CostCentreDescription As String
  Public CostCentreId As String
  Public ServiceId As String
  Public Name As String

  Public Sub New(serviceId As String,
                 name As String,
                 costCentreId As String,
                 costCentreDescription As String)

    With Me
      .ServiceId = serviceId
      .Name = name
      .CostCentreId = costCentreId
      .CostCentreDescription = CostCentreDescription
    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 "DocumentExecute" form.

LIMITATIONS: For SMS type Documents, this widget only handles the New SMS Messaging Interface.
LIMITATIONS: This widget does not allow "Save as Draft" or "Open For Edit" functionality and relies on SMTP being configured for Email type Documents.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
#divMessageInfo_Text {
  display:inline-block;
}
&lt;/style&gt;

&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent Documents you have executed."&gt;Recent Documents Executed&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Select the Document to create."&gt;Document&lt;/li&gt;
        &lt;li tabId="Parameters" tooltipText=""&gt;Parameters&lt;/li&gt;
        &lt;li tabId="Email" tooltipText=""&gt;Email&lt;/li&gt;
        &lt;li tabId="Sms" tooltipText=""&gt;SMS&lt;/li&gt;
        &lt;li tabId="Log" tooltipText=""&gt;Log&lt;/li&gt;
        &lt;li tabId="Items" tooltipText=""&gt;Recipients&lt;/li&gt;
        &lt;li tabId="Confirm" tooltipText=""&gt;Confirm&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" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:0"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblDocumentType"&gt;Optionally, select a Document Type to filter by&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;div id="rblDocumentType"&gt;&lt;/div&gt;&lt;/th&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label&gt;Select a Document&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div style="flex-grow:1; position:relative; margin-left:8px"&gt;
        &lt;div id="gridDocuments" style="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Parameters --&gt;
    &lt;div id="pageParameters"&gt;
      &lt;div id="phParameters" style="display:block"&gt;&lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Email --&gt;
    &lt;div id="pageEmail" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:0"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblEmailSubject"&gt;Email Subject and Message&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div style="flex-grow:0; margin-left:8px; position:relative; margin-bottom:4px;"&gt;
        &lt;input id="txtEmailSubject" /&gt;
      &lt;/div&gt;

      &lt;div style="flex-grow:1; margin-left:8px; position:relative"&gt;
        &lt;div style="display:flex; flex-direction:column; flex-grow:1" class="is-dock-fill"&gt;
          &lt;div id="heEmailMessage"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- SMS --&gt;
    &lt;div id="pageSms" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:0"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblBranch"&gt;Select the Branch to allocate costs to&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboBranch"&gt;Branch:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboBranch" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblService"&gt;Select the SMS Service to use&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboService"&gt;Service:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboService" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;/th&gt;
            &lt;td&gt;&lt;div id="divCostCentreInformation" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblMessage"&gt;Enter the SMS Message&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div style="flex-grow:1; margin-left:8px; position:relative"&gt;
        &lt;div style="display:flex; flex-direction:column; flex-grow:1" class="is-dock-fill"&gt;
          &lt;input id="txtMessage"/&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div style="flex-grow:0; margin-left:8px"&gt;
        &lt;div id="divMessageInfo" class="is-info-text info small"&gt;
          &lt;div id="divMessageInfo_Text"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Log --&gt;
    &lt;div id="pageLog" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:0"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblLogSubject"&gt;Log Subject and Notes&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div style="flex-grow:0; margin-left:8px; position:relative; margin-bottom:4px;"&gt;
        &lt;input id="txtLogSubject" /&gt;
      &lt;/div&gt;

      &lt;div style="flex-grow:1; margin-left:8px; position:relative"&gt;
        &lt;div style="display:flex; flex-direction:column; flex-grow:1" class="is-dock-fill"&gt;
          &lt;input id="txtLogMessage" /&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Items --&gt;
    &lt;div id="pageItems"&gt;
      &lt;div class="is-dock-fill"&gt;
        &lt;div id="gridItems"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOtherOptions"&gt;Other options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkEmailDocument" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkGenerateLogs" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateLogDate"&gt;Log Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateLogDate"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateLogActionDate"&gt;Action:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateLogActionDate"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboLogSeverity"&gt;Severity:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboLogSeverity" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;
            &lt;div id="divExecuteDetails" class="is-info-text info small"&gt;&lt;/div&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


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

  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdHistory" class="is-button" style="float:left"&gt;Recent&lt;/button&gt;

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

&lt;script&gt;
// Record
var mRecord;
var mRecord_Document;
var mRecord_Documents;
var mRecord_SmsInfo;

var mRecord_BackgroundProcessStatus;
var mRecord_CurrentProcesses;

var mDocumentExecute;

// Global Collections
var mBranches;

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

  //   General
  lblDocumentType: null,
  rblDocumentType: null,

  gridDocuments: null,

  //   Parameters
  phParameters: null,

  //   Email
  lblEmailSubject: null,
  txtEmailSubject: null,
  heEmailMessage: null,

  //   SMS
  lblBranch: null,
  cboBranch: null,
  divCostCentreInformation: null,

  lblService: null,
  cboService: null,

  lblMessage: null,
  txtMessage: null,
  divMessageInfo: null,
  divMessageInfo_Text: null,

  //   Log
  lblLogSubject: null,
  txtLogSubject: null,
  txtLogMessage: null,

  //   Recipients
  gridItems: null,

  //   Notes
  lblOtherOptions: null,
  chkEmailDocument: null,
  chkGenerateLogs: null,
  dateLogActionDate: null,
  dateLogDate: null,
  cboLogSeverity: null,

  divExecuteDetails: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;

// Other
var mComplete = false;
var mDocument;
var mTimer;
var mFromRecent = false;
var mFromRecentRefresh = false;
var mLastRefreshParametersJson = "";
var mMonitoringExisting = false;
var mProcessId;


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

  // Controls
  //   General
  C.lblDocumentType = widget.UI.Label("lblDocumentType", {});
  C.rblDocumentType = widget.UI.RadioButtonList("rblDocumentType", {
    allowBlank: false,

    onChange: rblDocumentType_Change,
  });

  //   Parameters
  C.phParameters = widget.UI.ParametersHost("phParameters", {});

  //   Email
  C.lblEmailSubject = widget.UI.Label("lblEmailSubject", {
    tooltipText: "The subject can also contain the majority of the same tags as the email message.",
  });
  C.txtEmailSubject = widget.UI.TextBox("txtEmailSubject", {
    allowBlank: false,
    maxLength: 1024,
    //multiLine: true, // So tags appear below rather than above the control
    //rows: 1,
  });

  C.heEmailMessage = widget.UI.HtmlEditor("heEmailMessage", {});

  //   SMS
  C.lblBranch = widget.UI.Label("lblBranch", {});
  C.cboBranch = widget.UI.DBCombo("cboBranch", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboBranch_Change,
  });
  C.divCostCentreInformation = $("#divCostCentreInformation");

  C.lblService = widget.UI.Label("lblService", {});
  C.cboService = widget.UI.DBCombo("cboService", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboService_Change,
  });

  C.lblMessage = widget.UI.Label("lblMessage", {});
  C.txtMessage = widget.UI.TextBox("txtMessage", {
    allowBlank: false,
    changeWhileTyping: true,
    multiLine: true,
    maxLength: 4096,
    minHeight: "80px",
    rows: 8,

    onChange: txtMessage_Change,
  });
  C.txtMessage.TagsListDefine(null); // Required to make the textbox fill its container
  C.divMessageInfo = $("#divMessageInfo");
  C.divMessageInfo_Text = $("#divMessageInfo_Text");

  //   Log
  C.lblLogSubject = widget.UI.Label("lblLogSubject", {
    tooltipText: "The subject can also contain the majority of the same tags as the log notes.",
  });
  C.txtLogSubject = widget.UI.TextBox("txtLogSubject", {
    allowBlank: false,
    maxLength: 1024,
    //multiLine: true, // So tags appear below rather than above the control
    //rows: 1,
  });

  C.txtLogMessage = widget.UI.TextBox("txtLogMessage", {
    multiLine: true,
    rows: 8,
  });
  C.txtLogMessage.TagsListDefine(null); // Required to make the textbox fill its container

  //   Notes
  C.lblOtherOptions = widget.UI.Label("lblOtherOptions", {});
  C.chkEmailDocument = widget.UI.CheckBox("chkEmailDocument", {
    caption: "Email Document if possible?",

    onChange: chkEmailDocument_Change,
  });
  C.chkGenerateLogs = widget.UI.CheckBox("chkGenerateLogs", {
    caption: "Create a Log for each message?",

    onChange: chkGenerateLogs_Change,
  });

  C.dateLogActionDate = widget.UI.DateTimeZone("dateLogActionDate", {
    timeZoneVisible: true,
  });
  C.dateLogDate = widget.UI.DateTimeZone("dateLogDate", {
    timeZoneVisible: true,
  });
  C.cboLogSeverity = widget.UI.DBCombo("cboLogSeverity", {
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });

  C.divExecuteDetails = $("#divExecuteDetails");

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

    onInitialiseRow: gridDocuments_InitialiseRow,
    onRowDrilldown: gridDocuments_RowDrilldown,
  });

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

    onAction: gridItems_Action,
    onBeforeCellUpdate: gridItems_BeforeCellUpdate,
    onInitialiseRow: gridItems_InitialiseRow,
    onRowDrilldown: gridItems_RowDrilldown,
  });


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

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

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

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

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

  // Reset Form
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_Document = null;
  mRecord_Documents = null;
  mRecord_SmsInfo = null;

  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = 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;
      mRecord_Documents = mRecord.Documents;

      // Global Collections
      mBranches = mRecord.Branches;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mBranches, "BranchId");

      // 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 Documents that you have executed that are not yet complete.\n\nReview and optionally monitor these or use the 'Next &gt;' button to execute a new Document.", { heading: "Documents Still Executing", icon: "MonitorCategory"} );
      }
      else if(mRecord.DocumentId) {
        // Advance past Documents grid
        tabWizard_Move(1);
      }
    },

    // 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
    // NOTE: List must be built here so we can assign the value
    var list = [];
    list.push({ caption: "None", value: "" });
    list.push({ caption: "Account", value: "Account" });
    if (mRecord.AddOnAccountApplication) list.push({ caption: "Account Application", value: "AccountApp" });
    list.push({ caption: "Client", value: "Client" });
    if (mRecord.AddOnSecurityRegister) list.push({ caption: "Security Statement", value: "SecurityStatement" });
    list.push({ caption: "User", value: "User" });
    list.push({ caption: "Other", value: "General" });
    C.rblDocumentType.ListFromArray(list);
    C.rblDocumentType.Value(mRecord.DocumentType || "");

    //C.cboRecord.Caption(mRecord.RecordCaption + ":");
    //C.cboRecord.RefreshUnbound(mRecord.RecordCode, mRecord.RecordDescription);

    //C.cboWorkflow.RefreshUnbound(mRecord.WorkflowId, mRecord.WorkflowDescription);

    gridDocuments_Refresh();

    // Parameters

    // Email

    // SMS

    // Notes
  }

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

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters(includeRefreshData) {
  var params = {
    documentId: mDocument.DocumentId,
    processId: mProcessId,

    // Notes page
    emailDocument: C.chkEmailDocument.Value(),
    generateLogs: C.chkGenerateLogs.Value(),
    logTimeZoneId: C.dateLogDate.TimeZoneId(),
    logTzDate: C.dateLogDate.Value(),
    actionTimeZoneId: C.dateLogActionDate.TimeZoneId(),
    actionTzDate: C.dateLogActionDate.Value(),
    logSeverityId: C.cboLogSeverity.Text(),
  }

  // Document Parameters
  if (mDocument.HasParameters &amp;&amp; mRecord_Document) {
    params.ParametersJson = JSON.stringify(C.phParameters.GetParameterValuesWithTypes())
  }

  // File Type-specific
  switch(mDocument.FileType) {
    case "Email":
      params.emailSubject = C.txtEmailSubject.Text();
      params.emailMessage = C.heEmailMessage.Text();
      break;

    case "Log":
      params.logSubject = C.txtLogSubject.Text();
      params.logMessage = C.txtLogMessage.Text();
      break;

    case "Sms":
      params.branchId = C.cboBranch.Text();
      params.smsMessage = C.txtMessage.Text();
      params.smsServiceId = C.cboService.Text();
      break;
  }

  // Recipients
  if (includeRefreshData &amp;&amp; mDocumentExecute) {
    params.RefreshData = JSON.stringify(mDocumentExecute);
  }

  return params;
}

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

  // Information Lists

  // Lists
  if (mRecord) {
    C.cboBranch.RefreshFromStandardRange("Branches");
    C.cboLogSeverity.RefreshFromStandardRange("LogSeverities");
  }

  // Controls
  if (mRecord) {
    if (mRecord.FilterByDocumentType || mRecord.DocumentId) {
      C.lblDocumentType.VisibleRow(false);
      C.rblDocumentType.VisibleRow(false);
    }
    if (!mRecord.AddOnCostCentre) {
      //C.lblBranch.VisibleRow(false);
      //C.cboBranch.VisibleRow(false);
    }

    rblDocumentType_Change();

    // Lock Documents grid?
    if (mRecord.DocumentId) {
      C.gridDocuments.ReadOnly(true);
      C.gridDocuments.ActivateFirstDataRow();
    }
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess() {
  if (mDocumentExecute) {
    // File Type-specific
    switch(mDocument.FileType) {
      case "Email":
        C.txtEmailSubject.Text(mDocumentExecute.EmailSubject);
        C.heEmailMessage.Text(mDocumentExecute.EmailMessage);
        break;

      case "Log":
        C.txtLogSubject.Text(mDocumentExecute.LogSubject);
        C.txtLogMessage.Text(mDocumentExecute.LogMessage);
        break;

      case "Sms":
        C.cboBranch.Text(mDocumentExecute.BranchId);
        C.txtMessage.Text(mDocumentExecute.SmsMessage);
        C.cboService.Text(mDocumentExecute.SmsServiceId);
        break;

      default:
    }

    // Notes
    // NOTE: Not actually from the background process but a default supplied by the Document
    C.chkEmailDocument.Value(mRecord_Document.EmailDocument);
    C.chkGenerateLogs.Value(mRecord_Document.GenerateLogs);

    // Create Parameters
    C.phParameters.Initialise(mRecord_Document.Parameters, { alwaysCreateControls: true });

    // Update Parameters
    if (mDocumentExecute.ParametersJson) {
      C.phParameters.UpdateParameterValues(JSON.parse(mDocumentExecute.ParametersJson));
    }
  }
}

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

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

      // Build Message
      message += "Are you sure you want to execute this Document?";

      // Auto-Commit?
      if (DocumentSupportsRecients() &amp;&amp; mRecord.AutoCommit) {
        switch(mDocument.FileType) {
          case "Email":
            message += "&lt;p style='color:green'&gt;An email will be sent to all applicable recipients.&lt;/p&gt;";
            break;

          case "Log":
            message += "&lt;p style='color:green'&gt;A Log will be sent for all applicable recipients.&lt;/p&gt;";
            break;

          case "Sms":
            message += "&lt;p style='color:green'&gt;An SMS will be sent to all applicable recipients.&lt;/p&gt;";
            break;
        }
      }

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

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

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

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Document Execute, 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();
    }
  );
}

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

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

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 Execute was successfully cancelled.");
          break;

        case "InProgressRefreshComplete":
          // Get Items
          mDocumentExecute = JSON.parse(mRecord_BackgroundProcessStatus.RefreshData);

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

          // Refresh Complete
          mRecord_BackgroundProcessStatus = null;

          // Set Tab
          tabWizard.SelectedTabId("Items");
          tabWizard_Refresh();
          pageItems_Refresh();
          break;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          if (InProgressRefreshComplete) {
            widget.UI.MsgBoxInfo("Document Execute Refresh is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          else {
            widget.UI.MsgBoxInfo("Document Execute 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 (mDocumentExecute.Recipients) mComplete = true;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

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

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

  // Tab
  tabWizard_Resize();
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Document Execute 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" || (mDocumentExecute &amp;&amp; mDocumentExecute.Recipients))) {
    var list = [];
    list.push({ key: "CLOSE", caption: "Suspend and Close", icon: "Window_Close", details: "This will close the wizard but retain the list of recipients which can be reviewed later by re-opening this wizard." });
    list.push({ key: "CANCEL", caption: "Close and Cancel", icon: "Trash", details: "This will close and wizard and cancel this process. Document Execute will need to be restarted to get back to this point." });

    var options = {
      closeOnEscape: true,
      title: "Close Document Execute",
      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, tabWizard_Cancel_Post);
          break;
      }
    });
  }
  else {
    tabWizard_Cancel_Post();
  }
}

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

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

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "Parameters":
          if (mDocument.HasParameters) found = true;
          break;

        case "Email":
          if (mDocument.FileType == "Email") found = true;
          break;

        case "Sms":
          if (mDocument.FileType == "Sms") found = true;
          break;

        case "Log":
          if (mDocument.FileType == "Log") found = true;
          break;

        case "Items":
          if (DocumentSupportsRecients()) {
            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_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "General":
        break;

      case "Items":
        pageItems_Refresh();
        break;

      case "Confirm":
        pageConfirm_Refresh();
        break;

      default:
        break;
    }
  }

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

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "General":
      // Auto-Format
      tabWizard.AutoFormatPage();
      break;

    case "CurrentProcesses":
      // Reset from recent flags
      mFromRecent = false;
      mFromRecentRefresh = false;
      break;

    default:
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Parameters":
      frmMain.RefreshHeading("Parameters", "Specify Parameters for Document " + mDocument.DocumentId + ", '" + mDocument.Description + "'.");
      break;

    case "Email":
      frmMain.RefreshHeading("Email", "Enter Email details for Document " + mDocument.DocumentId + ", '" + mDocument.Description + "'.");
      break;

    case "Sms":
      frmMain.RefreshHeading("SMS", "Enter SMS details for Document " + mDocument.DocumentId + ", '" + mDocument.Description + "'.");
      break;

    case "Log":
      frmMain.RefreshHeading("Log", "Enter Log details for Document " + mDocument.DocumentId + ", '" + mDocument.Description + "'.");
      break;

    case "Confirm":
      frmMain.RefreshHeading("Confirm", "Enter Log details for Document " + mDocument.DocumentId + ", '" + mDocument.Description + "'.");
      break;

    case "Items":
      frmMain.RefreshHeading("Recipients", "Select the recipients for Document " + mDocument.DocumentId + ", '" + mDocument.Description + "'.");
      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;
  }
}

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      break;

    case "Parameters":
      C.phParameters.ResizeFromParent();
      break;

    case "Email":
      break;

    case "Sms":
      break;

    case "Log":
      break;

    case "Confirm":
      break;

    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  var tabIndex = tabWizard.SelectedTabIndex();

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

  // Finish Button
  cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

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

    switch(mRecord_BackgroundProcessStatus.Status) {
      case "Pending":
      case "InProgress":
        // NOTE: Document Execute does not allow cancelling, i.e., the "Stop" button
        cmdFinish.prop("disabled", true);
        //cmdFinish.text("Stop");
        //cmdFinish.prop("disabled", false);
        //cmdFinish.addClass("negative");
        break;

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

  // Recent Page exceptions
  if (mFromRecent) {
    // We have moved straight to the Progress page from the Recent list
    cmdHistory.prop("disabled", false);

    cmdBack.prop("disabled", true);
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", true);
  }
  else if(mFromRecentRefresh) {
    // We have moved to the Items grid from the Recent list
    cmdHistory.prop("disabled", false);

    // Don't allow moving back to the General page (i.e., the Document selection grid)
    if (mDocument.HasParameters) {
      cmdBack.prop("disabled", tabIndex &lt;= 2);
    }
    else {
      cmdBack.prop("disabled", tabIndex &lt;= 4);
    }
  }

  // Never allow moving back from Progress page
  if (tabWizard.SelectedTabId() == "Progress") cmdBack.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 (C.gridDocuments.ActiveDataRowListIndex() == -1) {
          Ok = false;
          C.gridDocuments.Focus();
        }
        else {
          mDocument = mRecord_Documents[C.gridDocuments.ActiveDataRowListIndex()];
        }
        break;

      case "Email":
        if (!mRecord.AutoCommit) {
          RefreshDocumentExecute();
        }
        break;

      case "Sms":
        if (!mRecord.AutoCommit) {
          RefreshDocumentExecute();
        }
        break;

      case "Log":
        if (!mRecord.AutoCommit) {
          RefreshDocumentExecute();
        }
        break;

      case "Items":
        var countIncluded = 0;
        for (var i = 0; i &lt; mDocumentExecute.Recipients.length; i++) {
          var item = mDocumentExecute.Recipients[i];
          if (item.Include &amp;&amp; item.CanSend) countIncluded += 1;
        }
        if (countIncluded == 0) {
          Ok = false;
          widget.UI.MsgBoxAlert("You have not included any recipients.");
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        var params = CreateFinishParameters(false);
        params.PageId = "General";
        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, {}, function () {
      if (o.FailedControlId) $("#" + o.FailedControlId).focus();
    });
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        mRecord_Document = o.Data;

        // Create Parameters
        C.phParameters.Initialise(mRecord_Document.Parameters, { alwaysCreateControls: true });

        // Defaults
        switch(mDocument.FileType) {
          case "Email":
            // =====
            // Email
            // =====
            C.txtEmailSubject.Text(mRecord_Document.EmailSubject);
            //C.txtEmailSubject.TagsListDefineFromCodeDescriptionList(mRecord_Document.TagsEmailSubject);

            C.heEmailMessage.Text(mRecord_Document.EmailMessage);
            C.heEmailMessage.TagsListDefineFromCodeDescriptionList(mRecord_Document.Tags);

            C.txtEmailSubject.ReadOnly(!mRecord_Document.AllowModify);
            C.heEmailMessage.ReadOnly(!mRecord_Document.AllowModify);
            break;

          case "Sms":
            // ===
            // SMS
            // ===
            C.cboBranch.Text(mRecord_Document.DefaultBranchId);
            cboBranch_Change();

            C.txtMessage.Text(mRecord_Document.SmsMessage);
            C.txtMessage.TagsListDefineFromCodeDescriptionList(mRecord_Document.Tags);

            C.txtMessage.ReadOnly(!mRecord_Document.AllowModify);
            break;

          case "Log":
            // ===
            // Log
            // ===
            C.txtLogSubject.Text(mRecord_Document.LogSubject);

            C.txtLogMessage.Text(mRecord_Document.LogMessage);
            C.txtLogMessage.TagsListDefineFromCodeDescriptionList(mRecord_Document.Tags);

            C.txtLogSubject.ReadOnly(!mRecord_Document.AllowModify);
            C.txtLogMessage.ReadOnly(!mRecord_Document.AllowModify);
            break;
        }

        C.chkEmailDocument.Value(mRecord_Document.EmailDocumentDefault);
        C.chkGenerateLogs.Value(mRecord_Document.GenerateLogs);
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ===========
// pageConfirm
// ===========
function pageConfirm_Refresh() {
  switch(mDocument.FileType) {
    case "Log":
      // Special, hide checkbox but still shows many Log fields
      C.chkGenerateLogs.VisibleRow(false);
      break;

    case "Email":
    case "Sms":
      C.chkGenerateLogs.VisibleRow(true);
      break;

    default:
      // Not applicable to other File Types
      C.chkGenerateLogs.Value(false);
      C.chkGenerateLogs.VisibleRow(false);
  }
  chkGenerateLogs_Change();

  if (mRecord_Document.AllowEmailDocument) {
    C.lblOtherOptions.TooltipText("Once this document is created, if the recipient has a valid email address, it can automatically be emailed to them.");
    C.chkEmailDocument.VisibleRow(true);
  }
  else {
    C.lblOtherOptions.TooltipText("");
    C.chkEmailDocument.VisibleRow(false);
  }

  divExecuteDetails_Refresh();
}

// =============
// gridDocuments
// =============
function gridDocuments_Refresh() {
  // Add Columns
  C.gridDocuments.ClearColumns();
  C.gridDocuments.AddColumnIcon("Icon", { sortable: true });
  C.gridDocuments.AddColumnCode("DocumentId", { caption: "Document", sortable: true });
  C.gridDocuments.AddColumnString("Description", { caption: "Description", sortable: true });

  // Refresh
  //C.gridDocuments.VirtualDataRefresh(mRecord_Documents);
  rblDocumentType_Change();
}

function gridDocuments_InitialiseRow(e) {
  var item = mRecord_Documents[e.row.listIndex];

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

  // Hidden (filtered out)
  if (item.Hidden) e.row.hidden = true;
}

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

// ================
// chkEmailDocument
// ================
function chkEmailDocument_Change(sender, e) {
  divExecuteDetails_Refresh();
}

// ===============
// chkGenerateLogs
// ===============
function chkGenerateLogs_Change(sender, e) {
  // Controls
  if (C.chkGenerateLogs.Value() || mDocument.FileType == "Log") {
    C.dateLogDate.VisibleRow(true);
    C.dateLogActionDate.VisibleRow(true);
    C.cboLogSeverity.VisibleRow(true);
  }
  else {
    C.dateLogDate.VisibleRow(false);
    C.dateLogActionDate.VisibleRow(false);
    C.cboLogSeverity.VisibleRow(false);
  }

  // Details
  divExecuteDetails_Refresh();
}

// =================
// divExecuteDetails
// =================
function divExecuteDetails_Refresh() {
  var s = "";

  // Count included
  var countIncluded = 0;
  if (mDocumentExecute &amp;&amp; mDocumentExecute.Recipients) {
    for (var i = 0; i &lt; mDocumentExecute.Recipients.length; i++) {
      if (mDocumentExecute.Recipients[i].Include) countIncluded += 1;
    }
  }

  // Information
  switch(mDocument.FileType) {
    case "Email":
      switch(countIncluded) {
        case 0:
          s += "&lt;p&gt;An email will be sent to each of the included recipients.&lt;/p&gt;";
          break;

        case 1:
          s += "&lt;p&gt;An email will be sent to the &lt;b&gt;1&lt;/b&gt; included recipient.&lt;/p&gt;";
          break;

        default:
          s += "&lt;p&gt;An email will be sent to the &lt;b&gt;" + countIncluded + "&lt;/b&gt; included recipients.&lt;/p&gt;";
          break;
      }
      break;

    case "ExcelWorkbook":
      s += "&lt;p&gt;One or more Excel Workbooks will be created.&lt;/p&gt;";
      break;

    case "Log":
      switch(countIncluded) {
        case 0:
          s += "&lt;p&gt;A Log will be created for each of the included recipients.&lt;/p&gt;";
          break;

        case 1:
          s += "&lt;p&gt;A Log will be created for the &lt;b&gt;1&lt;/b&gt; included recipient.&lt;/p&gt;";
          break;

        default:
          s += "&lt;p&gt;A Log will be created for the &lt;b&gt;" + countIncluded + "&lt;/b&gt; included recipients.&lt;/p&gt;";
          break;
      }
      break;

    case "Sms":
      switch(countIncluded) {
        case 0:
          s += "&lt;p&gt;An SMS message will be sent to each of the included recipients.&lt;/p&gt;";
          break;

        case 1:
          s += "&lt;p&gt;An SMS message will be sent to the &lt;b&gt;1&lt;/b&gt; included recipient.&lt;/p&gt;";
          break;

        default:
          s += "&lt;p&gt;An SMS message will be sent to the &lt;b&gt;" + countIncluded + "&lt;/b&gt; included recipients.&lt;/p&gt;";
          break;
      }
      break;

    case "WordDocument":
      s += "&lt;p&gt;One or more Word Documents will be created.&lt;/p&gt;";
      break;

    default:
      console.warn("Document Execute: divExecuteDetails_Refresh - File Type '" + mDocument.FileType + "' not handled.");
  }

  if (C.chkGenerateLogs.Value() &amp;&amp; mDocument.FileType != "Log") {
    s += "&lt;p&gt;A Log will be added to each included record where possible.&lt;/p&gt;";
  }

  if (C.chkEmailDocument.Value()) {
    s += "&lt;p&gt;If possible, an email will be sent with the document attached.&lt;/p&gt;";
  }

  // Warnings
  var warnings = "";
  if (mRecord_Document.ChargeFee &amp;&amp; mRecord_Document.DefaultFee != 0) {
    warnings += "&lt;p&gt;A fee of &lt;b&gt;" + widget.FormatCurrency(mRecord_Document.DefaultFee, true) + "&lt;/b&gt; will be charged to 'Open' Accounts.&lt;/p&gt;";
  }
  if (warnings) {
    s += "&lt;div style='color:red'&gt;" + warnings + "&lt;/div&gt;";
  }

  C.divExecuteDetails.html(s);
}

// =========
// cboBranch
// =========
function cboBranch_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Controls
  var branch = mBranches.GetItem(C.cboBranch.Text());
  if (branch) {
    C.cboService.RefreshFromCollection(branch.Services, "ServiceId", "Name");
    C.cboService.Text(branch.DefaultMessagingSmsServiceId);
  }
  else {
    C.cboService.RefreshUnbound("", "");
  }

  // Update Service
  cboService_Change();
}

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

  // Update Cost Centre Message
  var s = "";
  if (C.cboBranch.Text() &amp;&amp; C.cboService.Text()) {
    var branch = mBranches.GetItem(C.cboBranch.Text());
    if (branch) {
      for (var i = 0; i &lt; branch.Services.length; i++) {
        var item = branch.Services[i];
        if (item.ServiceId == C.cboService.Text()) {
          if (item.CostCentreId) {
            s = "This will be charged to Cost Centre &lt;b&gt;" + item.CostCentreId + "&lt;/b&gt;, '" + widget.UI.HtmlEncode(item.CostCentreDescription) + "'."
          }
          else {
            s = "Cost Centre not defined for this Service.";
          }
          break;
        }
      }
    }
  }
  C.divCostCentreInformation.html(s);


  // Update Message
  txtMessage_Change();
}

// ==========
// txtMessage
// ==========
function txtMessage_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Refresh SMS Information
  txtMessage_RefreshInfo();
}

function txtMessage_RefreshInfo() {
  // Clear
  if (mTimer) {
    window.clearTimeout(mTimer);
    mTimer = null;
  }

  // Execute (delayed)
  if (C.cboService.Text()) {
    mTimer = window.setTimeout(txtMessage_RefreshInfo_Execute, 250);
  }
  else {
    C.divMessageInfo_Text.text("Please select an SMS Service");
  }
}

function txtMessage_RefreshInfo_Execute() {
  var params = CreateFinishParameters();

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

      // Refresh SMS Information
      divMessageInfo_Refresh();
    },

    function (error) {
      // Ignore
    }
  );
}

// ==============
// divMessageInfo
// ==============
function divMessageInfo_Refresh() {
  // Message
  if (mRecord_SmsInfo) {
    C.divMessageInfo_Text.html(mRecord_SmsInfo.InformationMessageEditing);
  }
  else {
    C.divMessageInfo_Text.html("");
  }
}

// ===============
// rblDocumentType
// ===============
function rblDocumentType_Change(sender, e) {
  // Filter Documents
  var filter = C.rblDocumentType.Value();

  for (var i = 0; i &lt; mRecord_Documents.length; i++) {
    var item = mRecord_Documents[i];
    item.Hidden = false;

    if (filter == "") {
    }
    else {
      if (filter != item.DocumentType) item.Hidden = true;
    }
  }

  C.gridDocuments.VirtualDataRefresh(mRecord_Documents);
}

// ====================
// gridCurrentProcesses
// ====================
function gridCurrentProcesses_Refresh() {
  // Columns to show
  var showDocumentId = false;
  for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
    var item = mRecord_CurrentProcesses[i];
    if (item.RefreshData) showDocumentId = true;
  }

  // Add Columns
  if (C.gridCurrentProcesses.ColumnCount() == 0) {
    C.gridCurrentProcesses.AddColumnDrilldown();
    C.gridCurrentProcesses.AddColumnCode("DocumentId", { caption: "Document", visible: showDocumentId });
    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, 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);

  // Extract Document Id
  if (item.RefreshData) {
    try {
      var s = JSON.parse(item.RefreshData);
      e.row.cells.DocumentId.value = s.DocumentId;
    }
    catch(ex) {}
  }

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

// ===================================
// 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
        mDocumentExecute = JSON.parse(item.RefreshData);

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

        // We need mDocument and mRecord_Document objects to restore state so fetch these now
        widget.GetString("GetDocument", { documentId: mDocumentExecute.DocumentId },
          function (data) {
            mFromRecentRefresh = true;

            // Parse
            data = JSON.parse(data);
            mDocument = data.Document;
            mRecord_Document = data.Record_Document;

            // Update Controls
            Fields_Update_FromBackgroundProcess();

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

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

            // View Recipients
            tabWizard.SelectedTabId("Items");
            tabWizard_Refresh();
            pageItems_Refresh();
          },

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

            widget.UI.MsgBoxAlert(error);
          }
        );
        break;

      default:
        mFromRecent = true;
        mMonitoringExisting = true;

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

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

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

    default:
      break;
  }
}

// =======
// Refresh
// =======
function RefreshDocumentExecute() {
  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;Proceding will build a list of recipients which may take some time.&lt;/p&gt;";

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

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

    // Confirm
    widget.UI.MsgBoxConfirm(message, { heading: "Refresh Recipients", messageIsHtml: true, icon: "Table|Refresh" },
      function () {
        if (mDocumentExecute &amp;&amp; mProcessId) {
          CancelRefreshCompleteBackgroundProcess(mProcessId, RefreshDocumentExecute_Post, function() {
            // Move back a page
            tabWizard_Move(-1);

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

      function() {
        // Move back a page
        tabWizard_Move(-1);

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

function RefreshDocumentExecute_Post() {
  // Running new process
  mMonitoringExisting = false;
  mDocumentExecute = null;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Recipients Refresh, please wait...");

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

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

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

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

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

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

  // Stop button valid?
  tabWizard_UpdateButtons()

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

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

// =================
// gridItems_Refresh
// =================
function gridItems_Refresh() {
  // Add Columns
  C.gridItems.ClearColumns();
  C.gridItems.AddColumnIcon("Icon", { caption: "" });
  C.gridItems.AddColumnBoolean("Include", { caption: "Include", allowEdit: true });
  C.gridItems.AddColumnCode("Id", { caption: "ID" });
  C.gridItems.AddColumnString("Name", { caption: "Name" });
  switch(mDocument.FileType) {
    case "Email":
      C.gridItems.AddColumnString("Address", { caption: "Email" });
      break;

    case "Sms":
      C.gridItems.AddColumnString("Address", { caption: "Phone Number" });
      break;
  }
  C.gridItems.AddColumnDrilldown("Preview", { icon: "Preview" });

  // Actions
  C.gridItems.Actions().Define([{ actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                      { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },
                                      { actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                      { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                      { actionId: "SelectChecked", tooltipText: "Select all rows that are checked to include", icon: "Select_Checked" },
                                      { actionId: "SelectUnchecked", tooltipText: "Select all rows that are not checked to include", icon: "Select_Unchecked" },
                                      {},
                                      { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                      { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
                                     ]);

  // Refresh
  C.gridItems.VirtualDataRefresh(mDocumentExecute.Recipients);

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

function gridItems_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridItems.ActiveDataRowListIndex();
      var indexes = [];

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

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

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

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

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

        if(item.CanSend) {
          if(actionId.toUpperCase() == "SELECTCHECKED" &amp;&amp; item.Include) {
            indexes.push(i);
          }
          else if(actionId.toUpperCase() == "SELECTUNCHECKED" &amp;&amp; !item.Include) {
            indexes.push(i);
          }
        }
      }
      break;

    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridItems.GetSelectedRowIndexes(true, true);

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

    default:
      break;
  }

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

function gridItems_BeforeCellUpdate(e) {
  var item = mDocumentExecute.Recipients[e.row.listIndex];

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

function gridItems_InitialiseRow(e) {
  var item = mDocumentExecute.Recipients[e.row.listIndex];

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

  // ID column
  e.row.cells.Id.value = item.AccountId || item.AccountAppId || item.ClientId || item.UserId;

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

//  // Active / Exclude
//  e.row.cells.Include.value = (item.Status == "Active");
//
//  // Name
//  e.row.cells.AccountName.small = true;
//
//  // Hyperlinks
//  e.row.cells.AccountId.hyperlink = "app://FormShow?form=Accounts&amp;id=" + widget.UI.HtmlEncode(item.AccountId);
}

function gridItems_RowDrilldown(e) {
  var item = mDocumentExecute.Recipients[e.row.listIndex];

  switch(e.columnKey) {
    case "Preview":
      var params = CreateFinishParameters(false);
      params.previewIndex = e.row.listIndex;
      var title = "Message Preview";
      if (item.Address) title += "(" + item.Address + ")";

      widget.GetString("GetItemPreview", params,
        function (data) {
          widget.UI.Forms.ShowHtml(title, data);
        },

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

// ======================================
// Does this Document support Recipients?
// ======================================
function DocumentSupportsRecients() {
  if (mDocument) {
    switch(mDocument.FileType) {
      case "Email":
      case "Log":
      case "Sms":
        return true;
    }
  }
  else {
    return false;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>QtJPB3OzK0aUafN4XqnqwQ</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1024</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>Document</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="OnlyIncludeDocumentsFlaggedForCloud" 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="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DocumentId" 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.Documents</List>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="FilterByDocumentType" 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>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DocumentType" 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>Account,AccountApp,Client,SecurityStatement,User,General</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="FilterByFileType" 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>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="FileType" 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>Email,ExcelWorkbook,Html,Log,Script,Sms,WordDocument</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AutoCommit" type="Boolean">
            <BlankTip />
            <Caption>Auto Commit?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>If this is checked then the User will not be shown a Recipients list to choose from. Instead, an Email, SMS or Log will be generated for all valid items in the default list.</TooltipText>
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ProcessId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>50</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>