<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2025-11-13T01:26:50.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2025-10-29T03:04:24.6500000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2025-11-13T01:26:15.0570000</UpdatedUtcDate>
    <ScriptId>HWWA</ScriptId>
    <Description>Workflow Actions</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_WorkflowActions
Option Explicit On
Option Strict On

' #################################################################
' Workflow Actions
'
' (C) Copyright Intersoft Systems Limited 2025
'
' Version: 1.01 (13/11/2025)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  15/04/2025  ISS      J030562   Created
'    1.01  13/11/2025  ISS      J036123   Changes for the Email Overhaul (J035872)
' #################################################################

' Constants
Private Const FORM_KEY As String = "WorkflowActions"

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

' Common Parameters
Private mSkipReviewPage As Boolean = False
Private mSkipReviewPageSingle As Boolean = True
Private mWorkflowIds As String
Private mIncludeBroker As Boolean = True
Private mIncludeDealer As Boolean = True
Private mIncludeEmployees As Boolean = True
Private mIncludeGuarantors As Boolean = True
Private mIncludeInsurer As Boolean = True
Private mIncludeManager As Boolean = True
Private mIncludeOtherRoles As Boolean = True

' Other
Private mDesktopMode As Boolean
Private WithEvents mDocumentsPrint As finDocumentsPrint
Private mProcessId As String
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus

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

  ' Assume Success
  Main = True
  
  ' Get Parameters
  mParameters = finBL.CreateKeyValueList()
  mParameters.FromSimpleJsonString(parametersJson)
  mStartupParameters = finBL.CreateKeyValueList()
  mStartupParameters.FromSimpleJsonString(startUpParametersJson)

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

  ' Get Parameters
  With mCombinedParameters
    mDesktopMode = .GetBoolean("DesktopMode")
    mProcessId = .GetString("ProcessId")
    mSkipReviewPage = .GetBoolean("SkipReviewPage", mSkipReviewPage)
    mSkipReviewPageSingle = .GetBoolean("SkipReviewPageSingle", mSkipReviewPageSingle)
    mWorkflowIds = .GetString("WorkflowIds")
    mIncludeBroker = .GetBoolean("IncludeBroker", mIncludeBroker)
    mIncludeDealer = .GetBoolean("IncludeDealer", mIncludeDealer)
    mIncludeEmployees = .GetBoolean("IncludeEmployees", mIncludeEmployees)
    mIncludeGuarantors = .GetBoolean("IncludeGuarantors", mIncludeGuarantors)
    mIncludeInsurer = .GetBoolean("IncludeInsurer", mIncludeInsurer)
    mIncludeManager = .GetBoolean("IncludeManager", mIncludeManager)
    mIncludeOtherRoles = .GetBoolean("IncludeOtherRoles", mIncludeOtherRoles)    
  End With
  
  ' Force Desktop Mode?
  ' NOTE: This won't prevent Web Services from running as a Background Process but means the Widget doesn't have to be specifically configured when running under desktop
  If Not finBL.IsRunningFromWeb Then
    mDesktopMode = True
  End If

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

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

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

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

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

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

    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)
      
    Case "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 BranchInfoEmailGlobal As BranchInfoEmail  
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim GlobalCostCentre As finCostCentreResolved
  Dim HasMixedWorkflowTargets As Boolean
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean
  Dim Target As String
  Dim Workflows As List(Of WorkflowItem)
  Dim WorkflowTargetObjectType As isefinWorkflowTargetObjectType 

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Validate
  Success = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)
  If Success Then
    If Len(mWorkflowIds) = 0 Then
      Success = False
      finBL.Error.ErrorBegin("No Workflow Ids specified.")
    End If
  End If

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

  ' Get Workflows List
  If Success Then
    Success = GetWorkflows(Workflows)
  End If
  
  ' Has Mixed Workflow Targets?
  If Success Then
    If Workflows.Count &lt;&gt; 0 Then
      Target = Workflows(0).TargetObjectType 
      WorkflowTargetObjectType = Workflows(0).Workflow.WorkflowType.TargetObjectType
      
      For Each WorkflowItem As WorkflowItem In Workflows
        If WorkflowItem.TargetObjectType &lt;&gt; Target Then
          HasMixedWorkflowTargets = True
        End If
      Next
    End If
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ProcessId = mProcessId      
      .Workflows = Workflows
      
      ' Actions Supported
      .SupportsActionLog = True
      .SupportsActionDocument = Not HasMixedWorkflowTargets
      .SupportsActionEmail = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("EmailMessage") AndAlso Workflows.Count = 1
      .SupportsActionIncomingCommunication = (Workflows.Count = 1)
      .SupportsActionOutgoingCommunication = True
      
      .SupportsActionWebMail = finBL.Settings.AddOns.WebAutomation AndAlso WorkflowTargetObjectType = isefinWorkflowTargetObjectType.Client AndAlso Not HasMixedWorkflowTargets

      ' ============
      ' Log-specific
      ' ============
      
      ' ===============================
      ' Incoming Communication-specific
      ' ===============================
      .IncomingCommunicationCallerListCsv = GetByWhomList(Workflows(0))
      
      ' =================
      ' Document-specific
      ' =================
      If Not HasMixedWorkflowTargets AndAlso Len(Target) &lt;&gt; 0 Then
        ' NOTE: Use the same method as the Document Create wizard, even though this means fake-loading an object
        Dim DocumentCreate As finDocumentCreate = finBL.CreateDocumentCreate()
        
        With Workflows(0).Workflow.WorkflowType
          Select Case .TargetObjectType 
            Case isefinWorkflowTargetObjectType.Account
              If Not DocumentCreate.AccountLoad(Workflows(0).TargetObjectId) Then
                ' Ignore error
              End If
              
            Case isefinWorkflowTargetObjectType.AccountApp
              If Not DocumentCreate.AccountAppLoad(Workflows(0).TargetObjectId) Then
                ' Ignore error
              End If
              
            Case isefinWorkflowTargetObjectType.Client
              If Not DocumentCreate.ClientLoad(Workflows(0).TargetObjectId) Then
                ' Ignore error
              End If
              
          End Select
        End With
        .Documents = DocumentCreate.GetDocumentsListAsHtmlWidgetJsonObject()
      End If
      
      ' ==============
      ' Email-specific
      ' ==============
      ' Service Details
      For Each Branch In finBL.Branches
        If Branch.Active Then
          .BranchesEmail.Add(New BranchInfoEmail(Branch))
        End If
        
        If Len(.EmailBranchId) = 0 Then
          .EmailBranchId = Branch.BranchId
        End If
      Next
      ' Default - use Global Cost Centre
      GlobalCostCentre = finBL.CostCentresResolved.ItemByBranchPk(0)
      BranchInfoEmailGlobal = New BranchInfoEmail With {
        .BranchId = "",
        .DefaultMessagingEmailServiceId = GlobalCostCentre.DefaultMessagingEmailServiceId,
        .Description = "Global Default"
      }
      If finBL.Messaging.IsEmailServiceAvailableAndConfigured(ISMessaging_EmailMicrosoftExchange.SERVICE_ID, 0) Then
        BranchInfoEmailGlobal.Services.Add(New ServiceDetailsEmail(ISMessaging_EmailMicrosoftExchange.SERVICE_ID, ISMessaging_EmailMicrosoftExchange.SERVICE_NAME, "", "", "", ""))
      End If
      If finBL.Messaging.IsEmailServiceAvailableAndConfigured(ISMessaging_EmailSmtp.SERVICE_ID, 0) Then
        BranchInfoEmailGlobal.Services.Add(New ServiceDetailsEmail(ISMessaging_EmailSmtp.SERVICE_ID, ISMessaging_EmailSmtp.SERVICE_NAME, "", "", "", ""))
      End If
      .BranchesEmail.Add(BranchInfoEmailGlobal)      
      .EmailTarget = finBL.Enums.iseMessageTarget_ToString(iseMessageTarget.Send)
      

      ' ====================
      ' Recall Date-specific
      ' ====================
      .RecallPeriodListCsv = "Immediate,To Date,1 Day,2 Days,3 Days,4 Days,5 Days,6 Days,1 Week,2 Weeks,1 Month"
      
      ' =======================
      ' Allocated User-specific
      ' =======================
      For Each WorkflowItem As WorkflowItem In Workflows
        If WorkflowItem.Workflow.PendingAllocatedUserPk &lt;&gt; 0 Then
          .PendingAllocatedUsers = True
          .PendingAllocatedUserId = WorkflowItem.Workflow.PendingAllocatedUserId
          .PendingAllocatedUserName = finBL.Users.ItemByPkSafe(WorkflowItem.Workflow.PendingAllocatedUserPk).Name
        End If
      Next
      
      Dim AllocateUserPksList As New ISList()
      If Workflows.Count = 1 Then
        ' Single Workflow
        With Workflows(0).Workflow
          If Not .WorkflowType.CanAllocateToAnyUser Then
            AllocateUserPksList.AppendListReadOnly(Workflows(0).Workflow.WorkflowType.GetUserPksList(False))  
            If .AllocatedUserPk &lt;&gt; 0 Then AllocateUserPksList.Add(CStr(.AllocatedUserPk), True)
            If .PendingAllocatedUserPk &lt;&gt; 0 Then AllocateUserPksList.Add(CStr(.PendingAllocatedUserPk), True)
          End If
        End With
      Else
        ' Multiple Workflows (only Users available to ALL Workflows)
        For Each User As finUserRO In finBL.Users
          If User.Active AndAlso Not User.Deleted Then
            AllocateUserPksList.Add(CStr(User.Pk))
          End If
        Next
        
        Dim UsersRemoved As Boolean = False
        For Each WorkflowItem As WorkflowItem In Workflows
          If Not WorkflowItem.Workflow.WorkflowType.CanAllocateToAnyUser Then
            ' Remove any Users that the Workflow cannot be allocated to
            If AllocateUserPksList.RemoveListReadOnly(WorkflowItem.Workflow.WorkflowType.GetUserPksList(False), True) Then
              UsersRemoved = True
            End If            
          End If
        Next
        
        If Not UsersRemoved Then
          ' No point applying an SQL Where clause
          AllocateUserPksList.Clear()
        End If
      End If
      
      If AllocateUserPksList.Count &lt;&gt; 0 Then
        .AllocatedUsersSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql("Pk IN (" &amp; AllocateUserPksList.ToCsvString &amp; ")")
      End If

      ' General
      
      ' Licence
      
      ' Permissions
      
        ' Advanced
        .ShowEmailCostCentre = mCombinedParameters.GetString("ShowEmailCostCentre") : If Len(.ShowEmailCostCentre) = 0 Then .ShowEmailCostCentre = "Advanced"
        .ShowEmailOptions = mCombinedParameters.GetString("ShowEmailOptions") : If Len(.ShowEmailOptions) = 0 Then .ShowEmailOptions = "Advanced"
          
        .PageEmailHasAdvanced = (.ShowEmailCostCentre = "Advanced" OrElse .ShowEmailOptions = "Advanced")           

      ' Configuration
      .AddOnCostCentre = finBL.Settings.AddOns.CostCentre
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      .SkipReviewPage = mSkipReviewPage OrElse (mSkipReviewPageSingle AndAlso Workflows.Count = 1)
    End With

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

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

  Return Success

End Function

Private Function GetByWhomList(workflowItem As WorkflowItem) As String 
  
  Select Case workflowItem.Workflow.WorkflowType.TargetObjectType
    Case isefinWorkflowTargetObjectType.Account
      Return finBL.AccountFunctions.GetByWhomList(workflowItem.Workflow.Account, True, True, True).ToCsvString()
      
    Case isefinWorkflowTargetObjectType.AccountApp
      Return finBL.AccountAppFunctions.GetByWhomList(workflowItem.Workflow.AccountApp, True, True, True).ToCsvString()
      
    Case isefinWorkflowTargetObjectType.Client 
      Return finBL.ClientFunctions.GetByWhomList(workflowItem.Workflow.Client, True).ToCsvString()
      
    Case Else
      Return ""
  End Select
  
End Function

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

  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

Private Function CreateMessagingEmailMessage(ByRef messagingEmailMessage As finMessagingEmailMessage,
                                             parameters As WizardFinishParameters_ActionEmail,
                                             workflowItem As WorkflowItem) As Boolean
  
  Dim MessagingContact As finMessagingContact   
  Dim Recipient As finMessagingContact
  Dim RecipientCc As finMessagingContact
  Dim RecipientBcc As finMessagingContact  
  Dim Success As Boolean
  Dim Workflow As finWorkflow
  
  ' Assume Success
  Success = True
  
  ' Initialise
  messagingEmailMessage = finBL.Messaging.CreateMessagingEmailMessage(isefinMessagingEmailMessageContext.WorkflowAction)
  Recipient = Nothing
  RecipientCc = Nothing
  RecipientBcc = Nothing
  Workflow = workflowItem.Workflow

  ' Update
  If Success Then
    With messagingEmailMessage
      ' Source
      Select Case Workflow.WorkflowType.TargetObjectType
        Case isefinWorkflowTargetObjectType.Account : .SourceType = isefinMessagingSourceType.Account
        Case isefinWorkflowTargetObjectType.AccountApp : .SourceType = isefinMessagingSourceType.AccountApplication
        Case isefinWorkflowTargetObjectType.Client : .SourceType = isefinMessagingSourceType.Client
        Case Else : 
          ' Likely invalid, but don't fail
          .SourceType = isefinMessagingSourceType.None
      End Select
      .SourceId = workflowItem.TargetObjectId
      
      ' Workflow
      .WorkflowPk = Workflow.Pk
      If Workflow.GetCurrentItem() Is Nothing Then
        .WorkflowItemPk = 0
      Else 
        .WorkflowItemPk = Workflow.GetCurrentItem().Pk
      End If
      
      ' Log Details
      .LogTimeZoneId = finBL.SettingsUser.TimeZoneIdResolved
      .LogUtcDate = finBL.TimeZoneFunctions.GetCurrentUtcDateTime()
      ' TODO: Add Log Action &amp; Fee details.      
        
      
      ' Requires Parameters
      If parameters IsNot Nothing Then        
        ' Recipient Details
        .RecipientsToCsv = parameters.EmailTo
        .RecipientsCcCsv = parameters.EmailCc
        .RecipientsBccCsv = parameters.EmailBcc
        
        ' Branch
        .BranchId = parameters.EmailBranchId
        
        ' Service
        .ServiceId = parameters.EmailServiceId
        
        ' Options
        .Target = finBL.Enums.iseMessageTarget_FromString(parameters.EmailTarget)
        .IsHtml = parameters.EmailHtml
        
        ' Subject &amp; Body
        .Subject = parameters.EmailSubject
        .Body = parameters.EmailMessage
        
        ' Recipients (this is for log details
        If .SourceType = isefinMessagingSourceType.None Then
          ' Ignore
        Else
          For Each MessagingContact In .GetSourceEmailAddresses()
            If MessagingContact.Value = parameters.EmailTo AndAlso Recipient Is Nothing Then
              Recipient = MessagingContact
            End If 
            If MessagingContact.Value = parameters.EmailBcc AndAlso RecipientBcc Is Nothing Then
              RecipientBcc = MessagingContact
            End If
            If MessagingContact.Value = parameters.EmailCc AndAlso RecipientCc Is Nothing Then
              RecipientCc = MessagingContact
            End If
            
            ' Break?
            If (Len(parameters.EmailTo) = 0 OrElse Recipient IsNot Nothing) AndAlso
               (Len(parameters.EmailBcc) = 0 OrElse RecipientBcc IsNot Nothing) AndAlso
               (Len(parameters.EmailCc) = 0 OrElse RecipientCc IsNot Nothing) Then
              Exit For   
            End If
          Next
          
          .SetRecipientToDetails(Recipient)
          .SetRecipientBccDetails(RecipientBcc)
          .SetRecipientCcDetails(RecipientCc)
        End If
      End If        
    End With
  End If
  
  Return Success
  
End Function

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

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

  ' Assume Success
  Success = True

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

  ' Validate
  If Success Then
    ' Not required
  End If
  
  ' Queue Background Process
  ' NOTE: If mDesktopMode is True then the desktop User Interface will handle this rather than Web Services Background Processes (for this Widget, this just makes testing easier)
  If Success Then
    'Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript(ScriptInfo.ScriptId, mParameters.ToSimpleJsonString(), mStartupParameters.ToSimpleJsonString(), ProcessId, mDesktopMode)
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript(ScriptInfo.ScriptId, parametersJson, mStartupParameters.ToSimpleJsonString(), ProcessId, mDesktopMode)
  End If
  
  If Success Then
    ' Context-specific functionality - not supported
    CompleteMessage = ""
  End If
  
  ' Response
  If Success Then
    Data = New With {
      .ProcessId = ProcessId,
      .CompleteMessage = CompleteMessage
    }
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, 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_HtmlWidgetScript(ScriptInfo.ScriptId, True, ProcessStatuses)

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

  Return Success

End Function

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

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  Return Success

End Function

Private Function GetWorkflows(ByRef workflows As List(Of WorkflowItem)) As Boolean

  Dim Database As ISDatabaseBL 
  Dim dr As IDataReader
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean
  Dim Workflow As finWorkflow 
  
  ' Assume Success
  Success = True
  
  ' Initialise ByRef Parameters
  workflows = New List(Of WorkflowItem)
  
  ' Initialise
  Database = finBLShared.Database
  
  ' Build Query
  sqb = Database.CreateSelectQueryBuilder()
  With sqb
    .Table = "Workflow"
    .Fields.Add("Pk")
    .SqlWhere.AppendRange("WorkflowId", mWorkflowIds)
    .OrderByFields.Add("WorkflowId")
  End With
  
  If sqb.ExecuteDataReader2(dr) Then
    Do While dr.Read()
      Workflow = finBLShared.CreateWorkflow()
      If Workflow.LoadPk(Database.GetFieldInteger(dr!Pk)) Then
        workflows.Add(New WorkflowItem(workflow))
      Else
        Success = False
        Exit Do 
      End If
    Loop
    Database.DataReaderClose(dr)
  Else
    Success = False
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object; "true" if validation passed, otherwise, information as to why validation failed.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean
                         
  Dim ConfirmList As List(Of String)                                
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

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

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

  Return Success

End Function

Private Function WizardValidate_Actions(ByRef data As Object) As Boolean
  
  Dim ActionEmail As Boolean
  Dim ConfirmList As List(Of String)
  Dim DefaultMessagingContact As finMessagingContact
  Dim EmailAddresses As finMessagingContacts
  Dim MessagingEmailMessage As finMessagingEmailMessage
  Dim Success As Boolean
  Dim Workflows As List(Of WorkflowItem)
  
  ' Assume Success
  Success = True
  
  ' Get Parameters
  With mCombinedParameters
    ActionEmail = .GetBoolean("ActionEmail")
  End With
  
  ' Initialise
  ConfirmList = New List(Of String)
  
  ' Get Workflows
  If Success Then
    Success = GetWorkflows(Workflows)
  End If  
  
  ' Validate
  If Success Then
    If ActionEmail AndAlso Workflows.Count &lt;&gt; 1 Then
      Success = False
      finBL.Error.ErrorBegin("Action unavailable.", Nothing, "Email Action is only available when one Workflow is selected.")
    End If
  End If 
  
  If ActionEmail Then
    ' Get Email Addresses    
    Success = CreateMessagingEmailMessage(MessagingEmailMessage, Nothing, Workflows.Item(0))
    
    With MessagingEmailMessage
      EmailAddresses = .GetSourceEmailAddresses(
                          mIncludeGuarantors,
                          mIncludeEmployees,
                          mIncludeManager,
                          mIncludeDealer,
                          mIncludeBroker,
                          mIncludeInsurer,
                          mIncludeOtherRoles)
    End With
    
    DefaultMessagingContact = EmailAddresses.GetDefaultMessagingContact()
    
    data = New With {
      .ConfirmList = ConfirmList,
      .BranchId = MessagingEmailMessage.BranchId,
      .DefaultRecipient = If(DefaultMessagingContact IsNot Nothing, DefaultMessagingContact.Value, ""),
      .EmailAddresses = EmailAddresses.ToJsonObject(),
      .Tags = MessagingEmailMessage.GetSourceTagList().ToCodeDescriptionList().ToJsonObject()
    }  
  Else
    data = New With {
      .ConfirmList = ConfirmList
    }
  End If
    
  Return Success
  
End Function

Private Function BackgroundProcess_Execute(parametersJson As String,
                                           ByRef returnValue As String) As Boolean
  
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim Workflows As List(Of WorkflowItem)
  
  ' Assume Success
  Success = True
  
  ' Get Background Process
  ' NOTE: This is required to add events and to check to see if the User has attempted to cancel this process (if supported)
  mProcessStatus = DirectCast(ScriptInfo.ContextData.GetObject("ProcessStatus"), finHtmlWidgetBackgroundProcessStatus)

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)
  
  ' Notify
  mProcessStatus.AddEvent_Information("Starting Workflow Actions")
  
  ' Get Workflows
  If Success Then
    Success = GetWorkflows(Workflows)
  End If
  
  ' Process
  ' NOTE: Errors will be recorded as events but will not stop processing
  If Success Then
    For Each WorkflowItem As WorkflowItem In Workflows
      ' Cancelled?
      If mProcessStatus.IsCancelRequested() Then
        mProcessStatus.NotifyCancelled()
        Exit For
      End If
      
      mProcessStatus.AddEvent_Information(String.Format("Actioning Workflow '{0}'", WorkflowItem.Workflow.WorkflowId))      
      
      ' Log
      If WizardFinishParameters.ActionLog Then
        If Not BackgroundProcess_Execute_ActionLog(WorkflowItem.Workflow, WizardFinishParameters.ActionLogDetails) Then
          ' Ignore errors
        End If
      End If
      
      ' Email
      If WizardFinishParameters.ActionEmail Then
        If Not BackgroundProcess_Execute_ActionMessagingEmail(WorkflowItem, WizardFinishParameters.ActionEmailDetails) Then
          ' Ignore errors
        End If
      End If
      
      ' Allocated User
      If WizardFinishParameters.ActionAllocatedUser Then
        If Not BackgroundProcess_Execute_ActionAllocatedUser(WorkflowItem.Workflow, WizardFinishParameters.ActionAllocatedUserDetails) Then
          ' Ignore errors
        End If
      End If

      ' Recall Date
      If WizardFinishParameters.ActionRecallDate Then
        If Not BackgroundProcess_Execute_ActionRecallDate(WorkflowItem.Workflow, WizardFinishParameters.ActionRecallDateDetails) Then
          ' Ignore errors
        End If
      End If

    Next
  End If
  
  Return Success  
  
End Function

Private Function BackgroundProcess_Execute_ActionLog(workflow As finWorkflow,
                                                     logDetails As WizardFinishParameters_ActionLog) As Boolean

  Dim AccountLog As finAccountLog
  Dim Log As I_finLog
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
      
  ' Create Objects
  Select Case workflow.WorkflowType.TargetObjectType
    Case isefinWorkflowTargetObjectType.Account
      Log = finBL.LogUtilities.CreateLog(isefinLogObjectType.Account, workflow.Account.AccountId)
      AccountLog = DirectCast(Log, finAccountLog)

    Case isefinWorkflowTargetObjectType.AccountApp
      Log = finBL.LogUtilities.CreateLog(isefinLogObjectType.AccountApp, workflow.AccountApp.AccountAppId)

    Case isefinWorkflowTargetObjectType.Client
      Log = finBL.LogUtilities.CreateLog(isefinLogObjectType.Client, workflow.Client.ClientId)

    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unhandled Target Object Type '{0}'.", workflow.WorkflowType.TargetObjectTypeText)
  End Select
  
  ' Update
  If Success Then
    With Log
      ' General
      If logDetails.LogTzDate Is Nothing Then
        .LogDbDate = finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime()
      Else
        .LogTimeZoneId = logDetails.LogTimeZoneId
        .LogTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(logDetails.LogTzDate)
      End If
      .Subject = logDetails.Subject
      .LogSeverityId = logDetails.LogSeverityId 
      .Notes = logDetails.Notes
      
      .ActionTimeZoneId = logDetails.ActionTimeZoneId
      .ActionTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(logDetails.ActionTzDate)
      .LogOutcome = logDetails.LogOutcome
      .DelegatedToUserId = logDetails.DelegatedToUserId 
      .DelegatedToRoleId = logDetails.DelegatedToRoleId
      
      ' Link to Workflow
      .WorkflowPk = workflow.Pk
      If workflow.GetCurrentItem() Is Nothing Then
        .WorkflowItemPk = 0
      Else
        .WorkflowItemPk = workflow.GetCurrentItem().Pk
      End If
      
      ' Fee
      If AccountLog IsNot Nothing AndAlso workflow.Account.Status = isefinAccountStatus.Open AndAlso logDetails.FeeDetails.ChargeFee Then
        With AccountLog
          .ChargeFee = True
          .Fee = logDetails.FeeDetails.Fee
          .FeeElementId = logDetails.FeeDetails.ElementId
          .FeeReference = logDetails.FeeDetails.Reference
          .FeeNotes = logDetails.FeeDetails.Notes
        End With
      End If
      
      ' Save
      Success = .Save()
    End With
  End If
  
  ' Event
  If Success Then
    mProcessStatus.AddEvent_Information("    Log added")
  Else
    mProcessStatus.AddEvent_Error("    Failed to add Log", finBL.Error.Message(True))
  End If

  Return Success
                                                
End Function

Private Function BackgroundProcess_Execute_ActionMessagingEmail(workflowDetails As WorkflowItem,
                                                                emailDetails As WizardFinishParameters_ActionEmail) As Boolean
                                                                
  Dim MessagingEmailMessage As finMessagingEmailMessage               
  Dim Success As Boolean
  Dim Workflow As finWorkflow
  
  ' Assume Success
  Success = True
  
  ' Initialise
  Workflow = workflowDetails.Workflow

  ' Create MessagingEmailMessage
  Success = CreateMessagingEmailMessage(MessagingEmailMessage, emailDetails, workflowDetails)
  
  ' Execute
  If Success Then
    Success = MessagingEmailMessage.ExecuteSendEmail()
  End If
  
  ' Add Recent Action
  If Success AndAlso finBL.SettingsUser.RecentActionsEnabledResolved Then
    finBL.RecentActions.AddRecentAction("Email", String.Format("Email sent to {0}", MessagingEmailMessage.SourceId), Workflow.WorkflowId, "Workflow", Workflow.Pk, "Task Manager")
  End If
  
  ' Event
  If Success Then
    mProcessStatus.AddEvent_Information("    Email Sent Successfully")
  Else
    mProcessStatus.AddEvent_Error("    Failed to update Allocated User", finBL.Error.Message(True))
  End If
  
  Return Success
                                                                
End Function                                                                

Private Function BackgroundProcess_Execute_ActionAllocatedUser(workflow As finWorkflow,
                                                               allocatedUserDetails As WizardFinishParameters_ActionAllocatedUser) As Boolean

  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Refresh workflow (just in case)
  Success = workflow.Refresh()
  
  If Success Then
    If allocatedUserDetails.PendingMakeCurrent Then
      ' ====================
      ' Make Pending Current
      ' ====================
      If workflow.PendingAllocatedUserPk = 0 Then
        ' No Pending User
        If allocatedUserDetails.AllocatedUpdateHold Then
          workflow.HoldAllocatedUser = allocatedUserDetails.HoldAllocatedUser
          mProcessStatus.AddEvent_Information("    Allocated User Hold set to: " &amp; allocatedUserDetails.HoldAllocatedUser)
        End If
      Else
        ' Pending User
        workflow.AllocatedUserPk = workflow.PendingAllocatedUserPk
        mProcessStatus.AddEvent_Information(String.Format("    Pending User '{0}' noved to current User", workflow.PendingAllocatedUserId))
        workflow.PendingAllocatedUserPk = 0        
        
        ' Hold
        If allocatedUserDetails.AllocatedUpdateHold Then
          workflow.HoldAllocatedUser = allocatedUserDetails.HoldAllocatedUser
          mProcessStatus.AddEvent_Information("    Allocated User Hold set to: " &amp; allocatedUserDetails.HoldAllocatedUser)
        End If
        
        ' Recall Immediately
        If workflow.RecallUtcDate = Nothing OrElse workflow.RecallUtcDate &gt; finBL.TimeZoneFunctions.GetCurrentUtcDateTime() Then
          ' NOTE: Do not use RecallDateSet since the User has not explicitly set the Recall Date
          workflow.RecallUtcDate = finBL.TimeZoneFunctions.GetCurrentUtcDateTime()
          mProcessStatus.AddEvent_Information("    Recall date set to now")
        End If
        
        ' Add Recent Action
        If finBL.SettingsUser.RecentActionsEnabledResolved Then
          finBL.RecentActions.AddRecentAction("AllocateUser", String.Format("Allocated to Pending User '{0}'", workflow.AllocatedUserId), workflow.WorkflowId, "Workflow", workflow.Pk, "Task Manager")
        End If
      End If
    Else
      ' ==================
      ' Set Allocated User
      ' ==================
      ' Set User 
      If workflow.AllocatedUserId &lt;&gt; allocatedUserDetails.AllocatedUserId Then
        mProcessStatus.AddEvent_Information(String.Format("    Allocated User '{0}' changed to '{1}'", workflow.AllocatedUserId, allocatedUserDetails.AllocatedUserId))
        workflow.AllocatedUserId = allocatedUserDetails.AllocatedUserId
      End If
      
      ' Hold
      If allocatedUserDetails.AllocatedUpdateHold Then
        workflow.HoldAllocatedUser = allocatedUserDetails.HoldAllocatedUser
        mProcessStatus.AddEvent_Information("    Allocated User Hold set to: " &amp; allocatedUserDetails.HoldAllocatedUser)
      End If
      
      ' Recall Immediately
      If workflow.AllocatedUserId &lt;&gt; allocatedUserDetails.AllocatedUserId AndAlso  workflow.RecallUtcDate = Nothing OrElse workflow.RecallUtcDate &gt; finBL.TimeZoneFunctions.GetCurrentUtcDateTime() Then
        ' NOTE: Do not use RecallDateSet since the User has not explicitly set the Recall Date
        workflow.RecallUtcDate = finBL.TimeZoneFunctions.GetCurrentUtcDateTime()
        mProcessStatus.AddEvent_Information("    Recall date set to now")
      End If
      
      ' Add Recent Action
      If finBL.SettingsUser.RecentActionsEnabledResolved Then
        finBL.RecentActions.AddRecentAction("AllocateUser", String.Format("Allocated to User '{0}'", workflow.AllocatedUserId), workflow.WorkflowId, "Workflow", workflow.Pk, "Task Manager")
      End If
    End If
  End If
  
  ' Save Workflow
  If Success Then
    Success = workflow.Save()
  End If
  
  ' Event
  If Not Success Then
    mProcessStatus.AddEvent_Error("    Failed to update Allocated User", finBL.Error.Message(True))
  End If

  Return Success
                                                
End Function

Private Function BackgroundProcess_Execute_ActionRecallDate(workflow As finWorkflow,
                                                            recallDateDetails As WizardFinishParameters_ActionRecallDate) As Boolean

  Dim RecallDate As Date
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  If Success Then
    ' Clear Recall Immediate
    workflow.RecallImmediateClear()
    
    ' Update Recall Date
    Select Case UCase(recallDateDetails.RecallPeriod)
      Case ""
        ' Clear
        workflow.RecallDateSet(Nothing)
        
        mProcessStatus.AddEvent_Information("    Recall Date cleared")
        
        ' Add Recent Action
        If finBL.SettingsUser.RecentActionsEnabledResolved Then
          finBL.RecentActions.AddRecentAction("RecallDateCleared", "Recall Date cleared", workflow.WorkflowId, "Workflow", workflow.Pk, "Task Manager")
        End If

      Case "TO DATE"
        ' Specified Date
        RecallDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(recallDateDetails.RecallDate)
        workflow.RecallDateSet(RecallDate)
        
        mProcessStatus.AddEvent_Information("    Recall Date set to " &amp; finBL.FormatDateLong(RecallDate))
        
        ' Add Recent Action
        If finBL.SettingsUser.RecentActionsEnabledResolved Then
          finBL.RecentActions.AddRecentAction("RecallDateChanged", "Recall Date set to " &amp; finBL.FormatDateTimeLongWithTimeZone(workflow.RecallTzDate, workflow.RecallTimeZoneId), workflow.WorkflowId, "Workflow", workflow.Pk, "Task Manager")
        End If
      
      Case Else
        ' Period
        RecallDate = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()
        If UCase(recallDateDetails.RecallPeriod) &lt;&gt; "IMMEDIATE" Then
          RecallDate = finBL.Utilities.DateCycleGetTermEndDate(recallDateDetails.RecallPeriod, RecallDate)          
        End If
        workflow.RecallDateSet(RecallDate)
        
        mProcessStatus.AddEvent_Information(String.Format("    Recall Date set to {0} ({1})", finBL.FormatDateTimeLongWithTimeZone(workflow.RecallTzDate, workflow.RecallTimeZoneId), recallDateDetails.RecallPeriod))

        ' Add Recent Action
        If finBL.SettingsUser.RecentActionsEnabledResolved Then
          finBL.RecentActions.AddRecentAction("RecallDateChanged", String.Format("Recall Date set to {0} ({1})", finBL.FormatDateTimeLongWithTimeZone(workflow.RecallTzDate, workflow.RecallTimeZoneId), recallDateDetails.RecallPeriod), workflow.WorkflowId, "Workflow", workflow.Pk, "Task Manager")
        End If
    End Select
  End If
  
  ' Save Workflow
  If Success Then
    Success = workflow.Save()
  End If
  
  ' Event
  If Not Success Then
    mProcessStatus.AddEvent_Error("    Failed to update Recall Date", finBL.Error.Message(True))
  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)
  Public ProcessId As String
  Public Workflows As List(Of WorkflowItem)

  ' Record

  ' Lists
  
  ' Actions Supported
  Public SupportsActionLog As Boolean
  Public SupportsActionDocument As Boolean
  Public SupportsActionEmail As Boolean
  Public SupportsActionIncomingCommunication As Boolean
  Public SupportsActionOutgoingCommunication As Boolean
  Public SupportsActionWebMail As Boolean
  
  ' Log-specific
  
  ' Incoming Communication-specific
  Public IncomingCommunicationCallerListCsv As String
  
  ' Document-specific
  Public Documents As Object
   
  ' Allocated User-specific
  Public AllocatedUsersSqlWhere As String
  Public PendingAllocatedUsers As Boolean
  Public PendingAllocatedUserId As String ' Only applicable if there is a single Workflow
  Public PendingAllocatedUserName As String
  
  ' Recall Date-specific
  Public RecallPeriodListCsv As String  
   
  ' Email-specific
  Public BranchesEmail As New List(Of BranchInfoEmail)  
  Public EmailBranchId As String  
  Public EmailTarget As String
  Public EmailTargetCsv As String
  
  ' Permissions

  ' Advanced Selection
  Public PageEmailHasAdvanced As Boolean  
  Public ShowEmailCostCentre As String
  Public ShowEmailOptions As String  
  
  ' Configuration
  Public AddOnCostCentre As Boolean
  Public PromptOnCommit As Boolean
  Public SkipReviewPage 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

  ' Log
  Public ActionLog As Boolean
  Public ActionLogDetails As New WizardFinishParameters_ActionLog()

  ' Email
  Public ActionEmail As Boolean
  Public ActionEmailDetails As New WizardFinishParameters_ActionEmail()

  ' Allocated User
  Public ActionAllocatedUser As Boolean
  Public ActionAllocatedUserDetails As New WizardFinishParameters_ActionAllocatedUser()

    ' Recall Date
  Public ActionRecallDate As Boolean
  Public ActionRecallDateDetails As New WizardFinishParameters_ActionRecallDate()

End Class

Public Class WizardFinishParameters_ActionLog
  
  Public LogTzDate As Date?
  Public LogTimeZoneId As String
  Public LogSeverityId As String
  Public Subject As String
  Public Notes As String
  
  Public ActionTzDate As Date?
  Public ActionTimeZoneId As String
  
  Public LogOutcome As String
  
  Public DelegatedToUserId As String
  Public DelegatedToRoleId As String
  
  Public FeeDetails As New FeeDetails()

End Class

Public Class WizardFinishParameters_ActionEmail
  
  Public EmailTo As String
  Public EmailCc As String
  Public EmailBcc As String
  Public EmailBranchId As String
  Public EmailServiceId As String
  Public EmailTarget As String
  Public EmailHtml As Boolean  
  Public EmailMessage As String
  Public EmailSubject As String

End Class

Public Class WizardFinishParameters_ActionAllocatedUser
  
  Public PendingMakeCurrent As Boolean
  
  Public AllocatedUserId As String
  Public AllocatedUpdateHold As Boolean
  Public HoldAllocatedUser As Boolean
  Public AllocatedUserRecallImmediately As Boolean

End Class

Public Class WizardFinishParameters_ActionRecallDate
  
  Public RecallPeriod As String
  Public RecallDate As Date?

End Class



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

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

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

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

  End Sub

End Class


''' &lt;summary&gt;
'''  Fee Details.
''' &lt;/summary&gt;
Public Class FeeDetails 
  
  Public ChargeFee As Boolean
  Public ElementId As String
  Public Fee As Decimal
  Public Reference As String
  Public Notes As String
  
End Class



''' &lt;summary&gt;
'''  Workflow Items.
''' &lt;/summary&gt;
Public Class WorkflowItem
  
  ' Properties
  Public WorkflowId As String
  Public Description As String
  Public Name As String
  Public TargetObjectId As String
  Public TargetObjectType As String
  
  ' Other
  Friend Workflow As finWorkflow
  
  Public Sub New(workflow As finWorkflow)
    
    Me.Workflow = workflow
    
    With workflow
      Me.WorkflowId = .WorkflowId
      Me.Description = .Description
      Me.TargetObjectType = workflow.WorkflowType.TargetObjectType.ToString() 
      
      Select Case .WorkflowType.TargetObjectType
        Case isefinWorkflowTargetObjectType.Account 
          Me.Name = workflow.Account.Name 
          Me.TargetObjectId = workflow.Account.AccountId
          
        Case isefinWorkflowTargetObjectType.AccountApp
          Me.Name = workflow.AccountApp.Name
          Me.TargetObjectId = workflow.AccountApp.AccountAppId
          
        Case isefinWorkflowTargetObjectType.Client 
          Me.Name = workflow.Client.Name
          Me.TargetObjectId = workflow.Client.ClientId
          
        Case Else
          Me.Name = "???"
      End Select
    End With
    
  End Sub
  
End Class



Public Class BranchInfoEmail
  
  Public BranchId As String
  Public DefaultMessagingEmailServiceId As String
  Public Description As String
  Public Services As New List(Of ServiceDetailsEmail)
  
  Public Sub New()
  End Sub
  
  Public Sub New(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.DefaultMessagingEmailServiceId = finBLShared.CostCentresResolved.ItemByBranchPk(.Pk).DefaultMessagingEmailServiceId
      
      ' Create Service Details
      ServicesList = .GetMessagingEmailServicesList()
      For Each Item In ServicesList
        ' Get Cost Centre
        If Not finBLShared.CostCentreFunctions.GetCostCentreFromBranchAndService(Me.BranchId, Item.Code, CostCentrePk)
          ' Ignore Errors
        End If
        
        If CostCentrePk = 0 Then
          Me.Services.Add(New ServiceDetailsEmail(Item.Code, Item.Description, "", "", "", ""))
        Else
          Me.Services.Add(New ServiceDetailsEmail(Item, finBLShared.CostCentres.ItemByPk(CostCentrePk), Me.BranchId))
        End If
      Next
      
      ' Clear Default Messaging Service if not in list (e.g., Test Mode and not configured)
      If Not ServicesList.Exists(Me.DefaultMessagingEmailServiceId) Then Me.DefaultMessagingEmailServiceId = ""
    End With 
               
  End Sub
  
End Class



Public Class ServiceDetailsEmail
  
  Public CostCentreDescription As String
  Public CostCentreId As String
  Public EmailMessageTargetCsvList As String
  Public SenderDefault As String
  Public SenderListCsv As String
  Public ServiceId As String
  Public ShowSaveAsDraft As Boolean
  Public Name As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(serviceId As String,
                 name As String,
                 costCentreId As String,
                 costCentreDescription As String,
                 senderDefault As String,
                 senderListCsv As String)

    With Me
      .ServiceId = serviceId
      .Name = name
      .CostCentreId = costCentreId
      .CostCentreDescription = CostCentreDescription
      .SenderDefault = senderDefault
      .SenderListCsv = senderListCsv
      
      Select Case UCase(serviceId)
        Case UCase(ISMessaging_EmailMicrosoftExchange.SERVICE_ID)
          .EmailMessageTargetCsvList = finBLShared.Enums.iseMessageTarget_GetList(finBLShared.Messaging.Service_EmailMicrosoftExchange.SupportsEmailSaveAsDraft, False).ToCsvString()
          
        Case UCase(ISMessaging_EmailSmtp.SERVICE_ID)
          .EmailMessageTargetCsvList = finBLShared.Enums.iseMessageTarget_GetList(finBLShared.Messaging.Service_EmailSmtp.SupportsEmailSaveAsDraft, False).ToCsvString()
          
        Case Else
          .EmailMessageTargetCsvList = finBLShared.Enums.iseMessageTarget_GetList(True, False).ToCsvString()
          
      End Select
    End With

  End Sub  
  
  Public Sub New(item As ISCodeDescriptionListItem,
                 costCentreRO As finCostCentreRO,
                 branchId As String)
  
    ' Cost Centre
    With costCentreRO
      Me.CostCentreDescription = .Description
      Me.CostCentreId = .CostCentreId      
    End With
    
    ' Service Specific
    With item 
      Me.ServiceId = item.Code
      Me.Name = item.Description
      
      Select Case UCase(.Code)
        Case UCase(ISMessaging_EmailMicrosoftExchange.SERVICE_ID)
          With finBLShared.CostCentresResolved.ItemByBranchId(branchId).EmailMicrosoftExchange
            Me.EmailMessageTargetCsvList = finBLShared.Enums.iseMessageTarget_GetList(finBLShared.Messaging.Service_EmailMicrosoftExchange.SupportsEmailSaveAsDraft, False).ToCsvString()
            Me.SenderDefault = .UserName
            Me.SenderListCsv = .UserName
            Me.ShowSaveAsDraft = finBLShared.Messaging.Service_EmailMicrosoftExchange.SupportsEmailSaveAsDraft
          End With
          
        Case UCase(ISMessaging_EmailSmtp.SERVICE_ID)
          With finBLShared.CostCentresResolved.ItemByBranchId(branchId).EmailSmtp
            Me.EmailMessageTargetCsvList = finBLShared.Enums.iseMessageTarget_GetList(finBLShared.Messaging.Service_EmailSmtp.SupportsEmailSaveAsDraft, False).ToCsvString()
            Me.SenderDefault = .SenderEmailAddress
            Me.SenderListCsv = .SenderEmailAddress
            Me.ShowSaveAsDraft = finBLShared.Messaging.Service_EmailSmtp.SupportsEmailSaveAsDraft
          End With
          
        Case Else
          ' Don't Error
          Me.EmailMessageTargetCsvList = finBLShared.Enums.iseMessageTarget_GetList(True, False).ToCsvString()
          Me.SenderDefault = ""
          Me.SenderListCsv = ""
          Me.ShowSaveAsDraft = False
          
      End Select      
    End With      
                 
  End Sub
  
End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "WorkflowActions" but only compitible with Task Manager 2 and the finPOWER Connect Cloud Workflow form.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent Workflow Actions you have performed."&gt;Recent Workflow Actions&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Review Worklfows to Action."&gt;Review&lt;/li&gt;
        &lt;li tabId="Actions" tooltipText="Select Actions to perform for these Workflows."&gt;Select Actions&lt;/li&gt;
        
        &lt;li tabId="ActionLog" tooltipText="Enter Log details."&gt;Log&lt;/li&gt;
        
        &lt;li tabId="ActionCommunicationIncoming" tooltipText="Enter Incoming Communiction details."&gt;Incoming Communication&lt;/li&gt;
        
        &lt;li tabId="ActionCommunicationOutgoing" tooltipText="Enter Outgoing Communiction details."&gt;Outgoing Communication&lt;/li&gt;
        
        &lt;li tabId="ActionDocument_DocumentSelect" tooltipText="Select the Document to send."&gt;Select Document&lt;/li&gt;
        &lt;li tabId="ActionDocument_Parameters" tooltipText="Enter parameters."&gt;Document Parameters&lt;/li&gt;
        &lt;li tabId="ActionDocument_Email" tooltipText="Enter email details."&gt;Email Document&lt;/li&gt;
        &lt;li tabId="ActionDocument_Sms" tooltipText="Enter SMS details."&gt;SMS Document&lt;/li&gt;
        &lt;li tabId="ActionDocument_Log" tooltipText="Enter Document Log details."&gt;Document Log&lt;/li&gt;
        
        &lt;li tabId="ActionEmail" tooltipText="Enter email details."&gt;Email&lt;/li&gt;
        
        &lt;li tabId="ActionSms" tooltipText="Enter SMS details."&gt;SMS&lt;/li&gt;
        
        &lt;li tabId="ActionAllocatedUser" tooltipText="Update Allocated User."&gt;Allocated User&lt;/li&gt;
        
        &lt;li tabId="ActionRecallDate" tooltipText="Specify the Recall period."&gt;Update Recall Date&lt;/li&gt;
        
        &lt;li tabId="ActionWebMail" tooltipText="Enter Web Mail details."&gt;Web Mail&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;!-- Items --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;div id="gridItems"&gt;&lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Actions --&gt;
    &lt;div id="pageActions"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8px" /&gt;
          &lt;col /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="3"&gt;&lt;label id="lblActions"&gt;Select the Actions to perform&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionLog" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionLog" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionCommunicationIncoming" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionCommunicationIncoming" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionCommunicationOutgoing" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionCommunicationOutgoing" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionDocument" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionDocument" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionEmail" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionEmail" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionSms" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionSms" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionAllocatedUser" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionAllocatedUser" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionRecallDate" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionRecallDate" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;button id="cmdActionWebMail" class="is-button small" icon="Arrow_Right"&gt;&lt;/id&gt;&lt;/th&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionWebMail" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    
    &lt;!-- Action Log --&gt;
    &lt;div id="pageActionLog"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionLogLogDetails"&gt;Log details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateActionLogLogDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateActionLogLogDate"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionLogLogSeverity"&gt;Severity:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionLogLogSeverity" /&gt;&lt;/td&gt;
        &lt;/tr&gt;  
              
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionLogSubject"&gt;Subject:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionLogSubject" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr style="height:100%"&gt;
          &lt;th&gt;&lt;label for="txtActionLogNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td style="height:100%"&gt;&lt;input id="txtActionLogNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionLogAction"&gt;Action details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateActionLogAction"&gt;Action:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateActionLogAction"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
  
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionLogLogOutcome"&gt;Outcome&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionLogLogOutcome"&gt;Outcome:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionLogLogOutcome" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionLogDelegated"&gt;Delegated User and Role&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionLogDelegatedToUser"&gt;Delegated&amp;nbsp;User:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionLogDelegatedToUser" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionLogDelegatedToRole"&gt;Delegated Role:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionLogDelegatedToRole" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionLogFee"&gt;Fee details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="fdActionLogFee"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Incoming Communication --&gt;
    &lt;div id="pageActionCommunicationIncoming"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionIncomingCommunication"&gt;When was the communication made?&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateActionIncomingCommunicationLogDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateActionIncomingCommunicationLogDate"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionIncomingCommunicationCaller"&gt;Who was the caller?&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionIncomingCommunicationCaller"&gt;Caller:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionIncomingCommunicationCaller"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionIncomingCommunicationLogDetails"&gt;Enter Log details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionIncomingCommunicationLogSeverity"&gt;Severity:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionIncomingCommunicationLogSeverity" /&gt;&lt;/td&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionIncomingCommunicationSubject"&gt;Subject:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionIncomingCommunicationSubject" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr style="height:100%"&gt;
          &lt;th&gt;&lt;label for="txtActionIncomingCommunicationNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td style="height:100%"&gt;&lt;input id="txtActionIncomingCommunicationNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionIncomingCommunicationAction"&gt;Action details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateActionIncomingCommunicationAction"&gt;Action:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateActionIncomingCommunicationAction"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
  
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionIncomingCommunicationLogOutcome"&gt;Outcome&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionIncomingCommunicationLogOutcome"&gt;Outcome:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionIncomingCommunicationLogOutcome" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionIncomingCommunicationDelegated"&gt;Delegated User and Role&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionIncomingCommunicationDelegatedToUser"&gt;Delegated&amp;nbsp;User:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionIncomingCommunicationDelegatedToUser" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboActionIncomingCommunicationDelegatedToRole"&gt;Delegated Role:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionIncomingCommunicationDelegatedToRole" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActionIncomingCommunicationFee"&gt;Fee details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="fdActionIncomingCommunicationFee"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Outgoing Communication --&gt;
    &lt;div id="pageActionCommunicationOutgoing"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Select Document --&gt;
    &lt;div id="pageActionDocument_DocumentSelect"&gt;
      &lt;div id="gridDocuments" style="is-dock-fill"&gt;&lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Email --&gt;
    &lt;div id="pageActionEmail" 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:7em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;
          &lt;tbody&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblEmailRecipient"&gt;Specify Recipient details&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboEmail"&gt;To:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboEmail" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboEmailCc"&gt;CC:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboEmailCc" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboEmailBcc"&gt;BCC:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboEmailBcc" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
          
          &lt;tbody advancedId="EmailCostCentre"&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblEmailBranch"&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="cboEmailBranch"&gt;Branch:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboEmailBranch" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
  
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblEmailService"&gt;Select the Email Service to use&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboEmailService"&gt;Service:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboEmailService" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            
            &lt;tr&gt;
              &lt;th&gt;&lt;/th&gt;
              &lt;td&gt;&lt;div id="divEmailCostCentreInformation" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
            &lt;/tr&gt;     
          &lt;/tbody&gt;     
          
          &lt;tbody advancedId="EmailOptions"&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblEmailOptions"&gt;Specify how the Email should be sent&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboEmailTarget"&gt;Target:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboEmailTarget" /&gt;&lt;/td&gt;
            &lt;/tr&gt;       
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkEmailHtml" type="checkbox"/&gt;&lt;/th&gt;
            &lt;/tr&gt;            
          &lt;/tbody&gt;     
          
          &lt;tbody&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;/tbody&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; min-height:200px"&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 id="divFileAttachments" style="flex-grow:0; margin-top:12px; margin-bottom:4px; max-height:320px"&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="lblFileAttachments"&gt;Files or documents to attach to this Email&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;div id="fuFileAttachments"&gt;&lt;/div&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Allocated User --&gt;
    &lt;div id="pageActionAllocatedUser"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAllocatedPending"&gt;Pending Allocated User. Click 'Accept' to make current&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboPendingAllocatedUser"&gt;Pending:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboPendingAllocatedUser" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trAllocatedPendingMakeCurrent"&gt;
          &lt;th colspan="2"&gt;
            &lt;button id="cmdAllocatedPendingMakeCurrent" class="is-button ok small"&gt;Accept&lt;/button&gt;
            &lt;div id="divAllocatedPendingMakeCurrent" class="is-info-text small" style="display:none;"&gt;Pending Accepted&lt;/div&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAllocatedUser"&gt;Specify Allocated User details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAllocatedUser"&gt;Allocated To:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAllocatedUser" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAllocatedUpdateHold" type="checkbox" /&gt;&lt;/th&gt;        
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkHoldAllocatedUser" type="checkbox" /&gt;&lt;/th&gt;        
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAllocatedUserRecallImmediately" type="checkbox" /&gt;&lt;/th&gt;        
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- RecallDate --&gt;
    &lt;div id="pageActionRecallDate"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblRecallPeriod"&gt;Specify a Recall period&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRecallPeriod"&gt;Period:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRecallPeriod" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateRecallDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateRecallDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



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

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

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

&lt;script&gt;
// Properties
var mRecord;
var mRecord_BackgroundProcessStatus;
var mRecord_CurrentProcesses;
var mRecord_Documents;
var mRecord_EmailAddresses;
var mRecord_EmailBranches;

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

  //   General
  gridItems: null,  
  
  //   Actions
  lblActions: null,
  cmdActionButtons: null,
  chkActionLog: null,
  chkActionCommunicationIncoming: null,
  chkActionCommunicationOutgoing: null,
  chkActionDocument: null,
  chkActionEmail: null,
  chkActionSms: null,
  chkActionAllocatedUser: null,
  chkActionRecallDate: null,
  chkActionWebMail: null,
  
  //   Log
  dateActionLogLogDate: null,
  cboActionLogLogSeverity: null,  
  cboActionLogSubject: null,
  txtActionLogNotes: null,
  
  dateActionLogAction: null,
  cboActionLogLogOutcome: null,
  
  cboActionLogDelegatedToUser: null,
  cboActionLogDelegatedToRole: null,
  
  lblActionLogFee: null,
  fdActionLogFee: null,

  //   Incoming Communication
  dateActionIncomingCommunicationLogDate: null,
  
  cboActionIncomingCommunicationCaller: null,  
  
  cboActionIncomingCommunicationLogSeverity: null,  
  cboActionIncomingCommunicationSubject: null,
  txtActionIncomingCommunicationNotes: null,
  
  dateActionIncomingCommunicationAction: null,
  cboActionIncomingCommunicationLogOutcome: null,
  
  cboActionIncomingCommunicationDelegatedToUser: null,
  cboActionIncomingCommunicationDelegatedToRole: null,
  
  lblActionIncomingCommunicationFee: null,
  fdActionIncomingCommunicationFee: null,
  
  //   Document
  gridDocuments: null,
  
  //   Email
  lblEmailRecipient: null,
  cboEmail: null,
  cboEmailCc: null,
  cboEmailBcc: null,
  
  lblEmailBranch: null,
  cboEmailBranch: null,
  
  lblEmailService: null,
  cboEmailService: null,
  
  divEmailCostCentreInformation: null,
  
  lblEmailOptions: null,
  cboEmailTarget: null,    
  
  lblEmailSubject: null,
  chkEmailHtml: null,
  txtEmailSubject: null,
  heEmailMessage: null,

  divFileAttachments: null,
  lblFileAttachments: null,
  fuFileAttachments: null,
  
  //   Allocated User
  lblAllocatedPending: null,
  cboPendingAllocatedUser: null,
  trAllocatedPendingMakeCurrent: null,
  cmdAllocatedPendingMakeCurrent: null,
  divAllocatedPendingMakeCurrent: null,
  
  lblAllocatedUser: null,
  cboAllocatedUser: null,
  chkAllocatedUpdateHold: null,
  chkHoldAllocatedUser: null,
  chkAllocatedUserRecallImmediately: null,
  
  //   Recall Date
  lblRecallPeriod: null,
  cboRecallPeriod: null,
  dateRecallDate: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;
var cmdAdvanced;

// Other
var mAdvancedVisible = false;
var mAllocatedPendingMakeCurrent = false;
var mComplete = false;
var mDocument = null;
var mFromRecent = false;
var mLastEventId = "";
var mLastProcessStatus = "";
var mLastRefreshParametersJson = "";
var mLastProcessSummaryJson = "";
var mMonitoringExisting = false;
var mProcessId;

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

  // Controls
  //   General
  
  //   Actions
  C.lblActions = widget.UI.Label("lblActions", {});
  C.cmdActionButtons = $("button", "#pageActions");
  C.cmdActionButtons.on("click", cmdActionButtons_Click);
  C.chkActionLog = widget.UI.CheckBox("chkActionLog", {
    caption: "Add Log",
    onChange: chkAction_Change,
  });
  C.chkActionCommunicationIncoming = widget.UI.CheckBox("chkActionCommunicationIncoming", {
    caption: "Incoming Communication",
    onChange: chkAction_Change,
  });
  C.chkActionCommunicationOutgoing = widget.UI.CheckBox("chkActionCommunicationOutgoing", {
    caption: "Outgoing Communication",
    onChange: chkAction_Change,
  });
  C.chkActionDocument = widget.UI.CheckBox("chkActionDocument", {
    caption: "Document",
    onChange: chkAction_Change,
  });
  C.chkActionEmail = widget.UI.CheckBox("chkActionEmail", {
    caption: "Email",
    onChange: chkAction_Change,
  });
  C.chkActionSms = widget.UI.CheckBox("chkActionSms", {
    caption: "SMS",
    onChange: chkAction_Change,
  });
  C.chkActionAllocatedUser = widget.UI.CheckBox("chkActionAllocatedUser", {
    caption: "Update Allocated User",
    onChange: chkAction_Change,
  });
  C.chkActionRecallDate = widget.UI.CheckBox("chkActionRecallDate", {
    caption: "Set Recall Date",
    onChange: chkAction_Change,
  });
  C.chkActionWebMail = widget.UI.CheckBox("chkActionWebMail", {
    caption: "Send Web Mail",
    onChange: chkAction_Change,
  });

  
  //   Log
  C.dateActionLogLogDate = widget.UI.DateTimeZone("dateActionLogLogDate", {
    allowBlank: true,
  });
  C.cboActionLogLogSeverity = widget.UI.DBCombo("cboActionLogLogSeverity", {
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.cboActionLogSubject = widget.UI.InformationListComboBox("cboActionLogSubject", {
    allowBlank: false,
    limitToList: false,
    maxLength: 50,
    
    onChange: cboActionLogSubject_Change,
  });
  C.txtActionLogNotes = widget.UI.TextBox("txtActionLogNotes", {
    allowBlank: true,
    multiLine: true,
    spellCheck: true,
  });

  C.dateActionLogAction = widget.UI.DateTimeZone("dateActionLogAction", {
    allowBlank: true,
    
    //onChange: dateAction_Change,
  });

  C.cboActionLogLogOutcome = widget.UI.InformationListComboBox("cboActionLogLogOutcome", {
    limitToList: false,
    maxLength: 50,
  });

  C.cboActionLogDelegatedToUser = widget.UI.DBCombo("cboActionLogDelegatedToUser", {
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.cboActionLogDelegatedToRole = widget.UI.DBCombo("cboActionLogDelegatedToRole", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  
  C.lblActionLogFee = widget.UI.Label("lblActionLogFee", {
    tooltipText: "A Fee will only be charged to 'Open' Accounts.",
  });
  C.fdActionLogFee = CreateFeeDetails("fdActionLogFee");

  //   Incoming Communication
  C.dateActionIncomingCommunicationLogDate = widget.UI.DateTimeZone("dateActionIncomingCommunicationLogDate", {
    allowBlank: true,
  });
  C.cboActionIncomingCommunicationCaller = widget.UI.ComboBox("cboActionIncomingCommunicationCaller", {
    allowBlank: false,
    limitToList: false,
    maxLength: 50,
  });
  C.cboActionIncomingCommunicationLogSeverity = widget.UI.DBCombo("cboActionIncomingCommunicationLogSeverity", {
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.cboActionIncomingCommunicationSubject = widget.UI.InformationListComboBox("cboActionIncomingCommunicationSubject", {
    allowBlank: false,
    limitToList: false,
    maxLength: 50,
    
    //onChange: cboActionIncomingCommunicationSubject_Change,
  });
  C.txtActionIncomingCommunicationNotes = widget.UI.TextBox("txtActionIncomingCommunicationNotes", {
    allowBlank: true,
    multiLine: true,
    spellCheck: true,
  });

  C.dateActionIncomingCommunicationAction = widget.UI.DateTimeZone("dateActionIncomingCommunicationAction", {
    allowBlank: true,
    
    //onChange: dateAction_Change,
  });

  C.cboActionIncomingCommunicationLogOutcome = widget.UI.InformationListComboBox("cboActionIncomingCommunicationLogOutcome", {
    limitToList: false,
    maxLength: 50,
  });

  C.cboActionIncomingCommunicationDelegatedToUser = widget.UI.DBCombo("cboActionIncomingCommunicationDelegatedToUser", {
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.cboActionIncomingCommunicationDelegatedToRole = widget.UI.DBCombo("cboActionIncomingCommunicationDelegatedToRole", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  
  C.lblActionIncomingCommunicationFee = widget.UI.Label("lblActionIncomingCommunicationFee", {
    tooltipText: "A Fee will only be charged to 'Open' Accounts.",
  });
  C.fdActionIncomingCommunicationFee = CreateFeeDetails("fdActionIncomingCommunicationFee");
  
  //   Email
  C.lblEmailRecipient = widget.UI.Label("lblEmailRecipient", {});
  C.cboEmail = widget.UI.DBCombo("cboEmail", {
    allowBlank: false,
    limitToList: false,
    maxLength: 0,
    showDescription: false,
    
    onChange: cboEmail_Change,
  });
  C.cboEmailCc = widget.UI.DBCombo("cboEmailCc", {
    allowBlank: true,
    limitToList: false,
    maxLength: 0,
    showDescription: false
  });
  C.cboEmailBcc = widget.UI.DBCombo("cboEmailBcc", {
    allowBlank: true,
    limitToList: false,
    maxLength: 0,
    showDescription: false
  });
  
  C.lblEmailBranch = widget.UI.Label("lblEmailBranch", {});
  C.cboEmailBranch = widget.UI.DBCombo("cboEmailBranch", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,

    onChange: cboEmailBranch_Change,
  });
  C.divEmailCostCentreInformation = $("#divEmailCostCentreInformation");

  C.lblEmailService = widget.UI.Label("lblEmailService", {});
  C.cboEmailService = widget.UI.DBCombo("cboEmailService", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_20,

    onChange: cboEmailService_Change,
  });  
  
  C.lblEmailOptions = widget.UI.Label("lblEmailOptions", {});
  C.cboEmailTarget = widget.UI.ComboBox("cboEmailTarget", {
    limitToList: true,
    allowBlank: false
  });    
  
  C.lblEmailSubject = widget.UI.Label("lblEmailSubject", {
    tooltipText: "The subject can also contain the majority of the same tags as the email message.",
  });
  C.chkEmailHtml = widget.UI.CheckBox("chkEmailHtml", {
    caption: "HTML format?",

    onChange: chkEmailHtml_Change,
  });

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

  C.divFileAttachments = $("#divFileAttachments");
  C.lblFileAttachments = widget.UI.Label("lblFileAttachments", {});
  C.fuFileAttachments = widget.UI.FileUpload("fuFileAttachments", {
    allowFile: true,
    allowDocumentManager: true,
    allowResource: true,

    resourceOptions: { includeAll: false, includeAllowAsEmailAttachment: true },
  });
  

  //   Allocated User
  C.lblAllocatedPending = widget.UI.Label("lblAllocatedPending", {});
  C.cboPendingAllocatedUser = widget.UI.DBCombo("cboPendingAllocatedUser", {
    autoReadOnly: false,
    width: widget.UI.FIELD_WIDTH_CODE_20,
    readOnly: true,
  });
  C.trAllocatedPendingMakeCurrent = $("#trAllocatedPendingMakeCurrent");
  C.cmdAllocatedPendingMakeCurrent = $("#cmdAllocatedPendingMakeCurrent");
  C.cmdAllocatedPendingMakeCurrent.click(cmdAllocatedPendingMakeCurrent_Click);
  C.divAllocatedPendingMakeCurrent = $("#divAllocatedPendingMakeCurrent");
  
  C.lblAllocatedUser = widget.UI.Label("lblAllocatedUser", {
    tooltipText: "Clear the 'Allocated User' to unallocate this Workflow.\n\nWhen the Allocated User is 'Held', this will prevent automatic processes from updating the Allocated User, it will not prevent the Allocated User being manually updated.",
  });
  C.cboAllocatedUser = widget.UI.DBCombo("cboAllocatedUser", {
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.chkAllocatedUpdateHold = widget.UI.CheckBox("chkAllocatedUpdateHold", {
    caption: "Update whether to 'Hold' the Allocated User?",
    onChange: chkAllocatedUpdateHold_Change,
  });
  C.chkHoldAllocatedUser = widget.UI.CheckBox("chkHoldAllocatedUser", {
    caption: "Hold the Allocated User?",
  });
  C.chkAllocatedUserRecallImmediately = widget.UI.CheckBox("chkAllocatedUserRecallImmediately", {
    caption: "Recall this Workflow immediately when updating the Allocated User?",
  });
  
  //   Recall Date
  C.lblRecallPeriod = widget.UI.Label("lblRecallPeriod", {});
  C.cboRecallPeriod = widget.UI.DateCycleComboBox("cboRecallPeriod", {
    allowBlank: true,
    blankTip: "Clear Recall Date",
    isFrequency: false,
    limitToList: false,
    width: "12em",

    onChange: cboRecallPeriod_Change,
  });
  C.dateRecallDate = widget.UI.DateBox("dateRecallDate", {
    allowBlank: false,
  });
  
  

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

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

    onAction: gridCurrentProcesses_Action,
    onAfterRowActivate: gridCurrentProcesses_AfterRowActivate,
    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

  C.gridItems = widget.UI.Grid("gridItems", {
    docked: true,
    showSearchBox: true,
    stickyHeader: true,
    rowNumbering: true,

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

  C.gridDocuments = widget.UI.Grid("gridDocuments", {
    docked: true,
    groupByColumns: "Category",
    showSearchBox: true,
    stickyHeader: true,

    onInitialiseRow: gridDocuments_InitialiseRow,
    onRowDrilldown: gridDocuments_RowDrilldown,
    onAfterRowActivate: gridDocuments_AfterRowActivate,
  });

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

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

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

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

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

  // Reset
  Form_Reset();
});

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults
  C.chkEmailHtml.Value(true);
  C.chkAllocatedUserRecallImmediately.Value(true);

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

  // Resize
  Form_Resize();

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

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mRecord_Documents = null;
  mRecord_EmailBranches = 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;
      mRecord_EmailBranches = mRecord.BranchesEmail;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mRecord_EmailBranches, "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 "InProgressCancelRequested":
            countCurrent += 1;
            break;
        }
      }
      if (processIndex != -1) {
        ViewExistingProcess(processIndex);
      }
      else if (countCurrent != 0) {
        tabWizard_Move(-1);
        widget.UI.MsgBoxInfo("There are existing incomplete Workflow Actions that you have started and are not yet complete.\n\nYou can review these or use the 'Next &gt;' button to begin new Workflow Actions.", { heading: "Workflow Actions still Processing", icon: "Workflow"} );
      }
      else if (mRecord.SkipReviewPage) {
        // Skip Review Page
        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
    
    // Email
    C.cboEmailBranch.Text(mRecord.EmailBranchId);
    C.cboEmailTarget.Text(mRecord.EmailTarget);
    
    // Select Document
    if (mRecord.SupportsActionDocument) gridDocuments_Refresh();
    
    // Allocated User
    C.cboPendingAllocatedUser.RefreshUnbound(mRecord.PendingAllocatedUserId, mRecord.PendingAllocatedUserName);
    
    //C.lstLogClasses.Text(mRecord.LogClassesList);
  }

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

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// =============
// Fields Update
// =============
function Fields_Update() {
  // Lists (including Information Lists)
  if (mRecord) {
    // Log
    C.cboActionLogSubject.SetComboFromInformationList("WorkflowLogSubjects", false, null, true);
    C.cboActionLogLogSeverity.RefreshFromStandardRange("LogSeverities");        
    
    C.cboActionLogDelegatedToUser.RefreshFromStandardRange("Users", "", false, "", "UserId,Name,Active");
    C.cboActionLogDelegatedToRole.RefreshFromStandardRange("Roles");
    
    // Incoming Communication
    C.cboActionIncomingCommunicationCaller.ListFromCsvString(mRecord.IncomingCommunicationCallerListCsv);
    
    // Outgoing Communication
    
    // Email
    if (mRecord.EmailToListCsv == "*") {
      C.cboEmail.ReadOnly(true);
      C.cboEmail.BlankTip("(Multiple)");
    }
    else {
      C.cboEmail.ListFromCsvString(mRecord.EmailToListCsv);
      C.cboEmailCc.ListFromCsvString(mRecord.EmailToListCsv);
      C.cboEmailBcc.ListFromCsvString(mRecord.EmailToListCsv);
    }
    C.cboEmailBranch.RefreshFromStandardRange("Branches");    
    C.cboEmailTarget.ListFromCsvString(mRecord.EmailTargetCsv);    
    
    // Allocated User
    C.cboAllocatedUser.RefreshFromStandardRange("Users", mRecord.AllocatedUsersSqlWhere, false, "", "UserId,Name,Active");
    
    // Recall Date
    C.cboRecallPeriod.ListFromCsvString(mRecord.RecallPeriodListCsv);
  }

  // Controls
  if(mRecord) {
    // Initialise Advanced
    AdvancedInitialise();    
  
    // Actions
    C.chkActionLog.VisibleRow(mRecord.SupportsActionLog);
    C.chkActionDocument.VisibleRow(mRecord.SupportsActionDocument);
    C.chkActionEmail.VisibleRow(mRecord.SupportsActionEmail);
    C.chkActionCommunicationIncoming.VisibleRow(mRecord.SupportsActionIncomingCommunication);
    C.chkActionCommunicationOutgoing.VisibleRow(mRecord.SupportsActionOutgoingCommunication);
    C.chkActionWebMail.VisibleRow(mRecord.SupportsActionWebMail);
    
    // Log
    
    // Incoming Communication
    
    // Outgoing Communication
    
    // Email
    if (!mRecord.AddOnCostCentre) {
      C.lblEmailBranch.VisibleRow(false);
      C.cboEmailBranch.VisibleRow(false);
      C.divEmailCostCentreInformation.hide();    
    }
    cboEmailBranch_Change();
    
    if (mRecord.Workflows.length == 1) {
      //C.fuFileAttachments.RefreshDocumentManager(mRecord.Workflows[0].TargetObjectType, mRecord.Workflows[0].TargetObjectId);
    }
    C.lblFileAttachments.VisibleRow(false); // Not yet supported for this wizard
    C.fuFileAttachments.VisibleRow(false);  // Not yet supported for this wizard
    
    // Allocated User
    if (mRecord.PendingAllocatedUsers) {
      if (mRecord.Workflows.length == 1) {
        // Single Workflow
        C.lblAllocatedPending.Text("There Is a Pending Allocated User. Click 'Accept' to make Current");
      }
      else {
        // Multiple Workflows
        C.lblAllocatedPending.Text("Click 'Accept' to make the Pending Allocated User Current for all selected Workflows");
        C.cboPendingAllocatedUser.VisibleRow(false);
      }
    }
    else {
      C.lblAllocatedPending.VisibleRow(false);
      C.cboPendingAllocatedUser.VisibleRow(false);
      C.trAllocatedPendingMakeCurrent.hide();
    }
    chkAllocatedUpdateHold_Change();
    
    // Recall Date
    cboRecallPeriod_Change();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess(params) {
  if (params) {
    // General
    //TODO:
    
    // Ranges
  }
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      default:
        break;
    }
  }

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

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

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

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

    case "General":
      // Refesh Items
      gridItems_Refresh();
      break;

    default:
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Actions":
      var caption;
      if (mRecord.Workflows.length == 1) {
        caption = "Select Actions to perform for this Workflow or click an arrow to perform a single action.";
      }
      else {
        caption = "Select Actions to perform for these " + mRecord.Workflows.length + " Workflows or click an arrow to perform a single action.";
      }
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), caption);
      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()) {
    case "ActionLog":
      C.cboActionLogSubject.Focus();
      break;

    default:
      tabWizard.FocusFirst();
      break;
  }
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    processId: mProcessId,
    
    actionLog: C.chkActionLog.Value(),
    actionEmail: C.chkActionEmail.Value(),
    actionAllocatedUser: C.chkActionAllocatedUser.Value(),
    actionRecallDate: C.chkActionRecallDate.Value(),
  }
  
  if (params.actionLog) params.actionLogDetails = CreateFinishParameters_ActionLog();
  if (params.actionEmail) params.actionEmailDetails = CreateFinishParameters_ActionEmail();
  if (params.actionAllocatedUser) params.actionAllocatedUserDetails = CreateFinishParameters_ActionAllocatedUser();
  if (params.actionRecallDate) params.actionRecallDateDetails = CreateFinishParameters_ActionRecallDate();

  return params;
}

function CreateFinishParameters_ActionLog() {
  return {
    LogTimeZoneId: C.dateActionLogLogDate.TimeZoneId(),
    LogTzDate: C.dateActionLogLogDate.Value(),
    LogSeverityId: C.cboActionLogLogSeverity.Text(),
    Subject: C.cboActionLogSubject.Text(),
    Notes: C.txtActionLogNotes.Text(),
    
    ActionTimeZoneId: C.dateActionLogAction.TimeZoneId(),
    ActionTzDate: C.dateActionLogAction.Value(),
    
    LogOutcome: C.cboActionLogLogOutcome.Text(),
    
    DelegatedToUserId: C.cboActionLogDelegatedToUser.Text(),
    DelegatedToRoleId: C.cboActionLogDelegatedToRole.Text(),
    
    FeeDetails: C.fdActionLogFee.GetFeeDetails(),
  }
}

function CreateFinishParameters_ActionEmail() {
  return {
    EmailTo: C.cboEmail.Text(),
    EmailCc: C.cboEmailCc.Text(),
    EmailBcc: C.cboEmailBcc.Text(),
    EmailBranchId: C.cboEmailBranch.Text(),
    EmailServiceId: C.cboEmailService.Text(),
    EmailTarget: C.cboEmailTarget.Text(),     
    EmailHtml: C.chkEmailHtml.Value(),
    EmailSubject: C.txtEmailSubject.Text(),
    EmailMessage: C.heEmailMessage.Text(),
    /*
    logActionTimeZoneId: C.dateLogActionDate.TimeZoneId(),
    logActionTzDate: C.dateLogActionDate.Value(),
    logSeverityId: C.cboLogSeverity.Text(),
    chargeFee: C.chkFeeChargeFee.Value(),
    feeAccountId: C.cboFeeAccount.Text(),
    fee: C.numFee.Value(),
    */
  }
}

function CreateFinishParameters_ActionAllocatedUser() {
  return {
    PendingMakeCurrent: mAllocatedPendingMakeCurrent,
    
    AllocatedUserId: C.cboAllocatedUser.Text(),    
    AllocatedUpdateHold: C.chkAllocatedUpdateHold.Value(),
    HoldAllocatedUser: C.chkHoldAllocatedUser.Value(),
    AllocatedUserRecallImmediately: C.chkAllocatedUserRecallImmediately.Value(),
  }
}

function CreateFinishParameters_ActionRecallDate() {
  return {
    RecallPeriod: C.cboRecallPeriod.Text(),
    RecallDate: C.dateRecallDate.Value(),
  }
}

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

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

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  if (cmdFinish.text() == "Stop") {
    // Stop Process?
    //widget.UI.MsgBoxConfirm("Are you sure you want to stop this process?\n\nNOTE: This may not take effect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
    widget.UI.MsgBoxAlert("Stopping this process is not supported.");
  }
  else {
    // Validate
    tabWizard_Validate(function () {
      // Confirmation Message
      var message = "";
      if (mRecord.Workflows.length == 1) {
        message += "&lt;p&gt;Are you sure you want to pefrom the following actions on Workflow &lt;b&gt;" + mRecord.Workflows[0].WorkflowId + "&lt;/b&gt;?&lt;/p&gt;";
      }
      else {
        message += "&lt;p&gt;Are you sure you want to peform the following actions on all &lt;b&gt;" + mRecord.Workflows.length + "&lt;/b&gt; Workflows?&lt;/p&gt;";
      }
      message += "&lt;ol&gt;";
      if (C.chkActionLog.Value()) message += "&lt;li&gt;Create a Log&lt;/li&gt;";
      
      if (C.chkActionEmail.Value()) message += "&lt;li&gt;Send an Email&lt;/li&gt;";
      if (C.chkActionAllocatedUser.Value()) {
        if (mAllocatedPendingMakeCurrent) {
          message += "&lt;li&gt;Make 'Pending' User the current allocated User&lt;/li&gt;";
        }
        else {
          if (C.cboAllocatedUser.Text()) {
            message += "&lt;li&gt;Allocate to User &lt;b&gt;" + widget.UI.HtmlEncode(C.cboAllocatedUser.Text()) + "&lt;/b&gt;&lt;/li&gt;";
          }
          else {
            message += "&lt;li&gt;Clear allocated User&lt;/li&gt;";
          }
        }
      }
      if (C.chkActionRecallDate.Value()) {
        switch (C.cboRecallPeriod.Text()) {
          case "":
            message += "&lt;li&gt;Clear Recall Date&lt;/li&gt;";
            break;
            
          case "Immediate":
            message += "&lt;li&gt;Recall immediately&lt;/li&gt;";
            break;

          case "To Date":
            message += "&lt;li&gt;Set Recall Date to &lt;b&gt;" + widget.FormatDate(C.dateRecallDate.Value()) + "&lt;/b&gt;&lt;/li&gt;";
            break;
            
          default:
            message += "&lt;li&gt;Set Recall Date to &lt;b&gt;" + C.cboRecallPeriod.Text() + "&lt;/b&gt; from now&lt;/li&gt;";
        }
      }
      message += "&lt;/ol&gt;";
      
      // Background Process
      message += "NOTE: This may take some time. You can close this form at any time and open it again to monitor progress.&lt;/p&gt;";

      // Confirm
      widget.UI.MsgBoxConfirm(message, { title: "Workflow Actions", messageIsHtml: true }, Form_ExecuteAction_FinishPost, null);
    });
  }
}

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

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Workflow Actions, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();

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

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

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

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

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

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

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  // 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;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

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

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Workflow Actions is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          break;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Workflow Actions failed to complete.");
          break;

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

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

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

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

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

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

  // Block UI
  widget.UI.Block("Refreshing Recent Workflow Actions, please wait...");

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

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

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

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

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

  // Stop button valid?
  tabWizard_UpdateButtons()

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

function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

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

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

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

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

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

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

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

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

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

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

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

  C.gridCurrentProcesses.RefreshButtons();
}

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

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

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

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

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

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

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

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

// =========
// gridItems
// =========
function gridItems_Refresh() {
  // Determine columns to show
  for (var i = 0; i &lt; mRecord.Workflows.length; i++) {
    var item = mRecord.Workflows[i];
    
    //if (item.Warning) hasWarnings = true;
  }

  // Add Columns
  C.gridItems.ClearColumns();  
  C.gridItems.AddColumnIcon("TargetObjectType", { caption: "", sortable: true });
  C.gridItems.AddColumnCode("TargetObjectId", { caption: "Target", sortable: true });
  C.gridItems.AddColumnString("Name", { caption: "Name", sortable: true });
  C.gridItems.AddColumnCode("WorkflowId", { caption: "Workflow", sortable: true });  
  C.gridItems.AddColumnString("Description", { caption: "Description", sortable: true });

  // Actions
  
  C.gridItems.Actions().Define([]);
  
  // Actions
  var actions = [];
  C.gridItems.Actions().Define(actions);

  // Refresh
  C.gridItems.VirtualDataRefresh(mRecord.Workflows);

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

function gridItems_Action(actionId) {
  var selectedItems = C.gridItems.GetSelectedRowIndexes(true, true);
  
  switch (actionId.toUpperCase()) {
  }
}

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

function gridItems_RefreshButtons() {
  var hasSelected = C.gridItems.GetSelectedRowIndexes(true, true).length != 0;
  
  //C.gridItems.Actions().SetEnabled("StatusCancel", hasSelected);

  C.gridItems.RefreshButtons();
}

function gridItems_InitialiseRow(e) {
  var item = mRecord.Workflows[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);
  
  // File Type Icon
  /*
  switch(item.DocumentFileType) {
    case "Email":
      e.row.cells.DocumentFileTypeIcon.value = "Email";
      break;
  
    case "ExcelDocument":
      e.row.cells.DocumentFileTypeIcon.value = "DocumentType_Excel";
      break;

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

    case "Sms":
      e.row.cells.DocumentFileTypeIcon.value = "Sms";
      break;
  
    case "WordDocument":
      e.row.cells.DocumentFileTypeIcon.value = "DocumentType_Word";
      break;
  }
  */
  
  //e.row.cells.LogClassIcon = item.LogClass;
  //e.row.cells.DocumentFileTypeIcon = item.DocumentFileType;
  
  // Styling
  e.row.cells.Name.small = true;
  e.row.cells.Description.small = true;

  // Hyperlinks
  e.row.cells.WorkflowId.hyperlink = "app://FormShow?form=Workflow&amp;id=" + encodeURIComponent(item.WorkflowId);
  e.row.cells.TargetObjectId.hyperlink = "app://FormShow?form=" + item.TargetObjectType + "&amp;id=" + encodeURIComponent(item.TargetObjectId);
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Workflow Actions are still running.\n\nThese will continue to run and you can re-open this form at any time to check on its status.\n\n\Close this form?", {}, tabWizard_Cancel_Post);
  }
  else if (mProcessId &amp;&amp; (tabWizard.SelectedTabId() == "Items" || mLogsToPublish)) {
    var list = [];
    list.push({ key: "CLOSE", caption: "Suspend and Close", icon: "Window_Close", details: "This will close the wizard but retain the list which can be reviewed later by re-opening this wizard." });
    list.push({ key: "CANCEL", caption: "Close and Cancel", icon: "Trash", details: "This will close the wizard and cancel this process." });

    var options = {
      closeOnEscape: true,
      title: "Close Workflow Actions",
      showClose: true
    };

    widget.UI.MsgBoxList("Select an option below to close", list, options, function(key) {
      switch (key) {
        case "CLOSE":
          if (widget.CanClose()) {
            widget.Close();
          }
          else {
            widget.Reset();
          }
          break;

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

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

function tabWizard_Move(direction) {
  var Ok;

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "ActionLog":
          if (C.chkActionLog.Value()) found = true;
          break;

        case "ActionCommunicationIncoming":
          if (C.chkActionCommunicationIncoming.Value()) found = true;
          break;

        case "ActionCommunicationOutgoing":
          if (C.chkActionCommunicationOutgoing.Value()) found = true;
          break;
          
        case "ActionDocument_DocumentSelect":
          if (C.chkActionDocument.Value()) found = true;
          break;
          
        case "ActionDocument_Parameters":
          if (C.chkActionDocument.Value()) found = true;
          break;

        case "ActionDocument_Email":
          if (C.chkActionDocument.Value()) found = true;
          break;

        case "ActionDocument_Sms":
          if (C.chkActionDocument.Value()) found = true;
          break;

        case "ActionDocument_Log":
          if (C.chkActionDocument.Value()) found = true;
          break;
          
        case "ActionEmail":
          if (C.chkActionEmail.Value()) found = true;
          break;

        case "ActionSms":
          if (C.chkActionSms.Value()) found = true;
          break;

        case "ActionAllocatedUser":
          if (C.chkActionAllocatedUser.Value()) found = true;
          break;

        case "ActionRecallDate":
          if (C.chkActionRecallDate.Value()) found = true;
          break;

        case "ActionWebMail":
          if (C.chkActionWebMail.Value()) found = true;
          break;
          
        case "Progress":
          // Just in case we accidentally try to get to this page, click Finish
          Form_ExecuteAction("Finish");
          return;
          
        default:
          found = true;
          break;
      }

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

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "ActionLog":
      // Log
      C.cboActionLogLogSeverity.WidthResizeFromParent();      
      C.cboActionLogSubject.WidthResizeFromParent(true);
      C.txtActionLogNotes.ResizeFromParent();
      C.cboActionLogLogOutcome.WidthResizeFromParent(true);
      break;

    case "ActionCommunicationIncoming":
      // Incoming Communication
      C.cboActionIncomingCommunicationCaller.WidthResizeFromParent();
      C.cboActionIncomingCommunicationLogSeverity.WidthResizeFromParent();
      C.cboActionIncomingCommunicationSubject.WidthResizeFromParent(true);
      C.txtActionIncomingCommunicationNotes.ResizeFromParent();
      C.cboActionIncomingCommunicationLogOutcome.WidthResizeFromParent(true);
      break;
      
    case "ActionEmail":
      // Email
      C.cboEmail.WidthResizeFromParent();
      C.cboEmailCc.WidthResizeFromParent();
      C.cboEmailBcc.WidthResizeFromParent();
      C.cboEmailBranch.WidthResizeFromParent();
      C.cboEmailService.WidthResizeFromParent();
      break;

    case "ActionAllocatedUser":
      // Allocated User
      break;
    
    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  // Back and Next Buttons?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 1);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 2);
  cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
  
  // Next Button
  switch (tabWizard.SelectedTabId()) {
    case "Actions":
      // Actions
      var actionsSelected = C.chkActionLog.Value() ||
                            C.chkActionCommunicationIncoming.Value() ||
                            C.chkActionCommunicationOutgoing.Value() ||
                            C.chkActionDocument.Value() ||
                            C.chkActionEmail.Value() ||
                            C.chkActionSms.Value() ||
                            C.chkActionAllocatedUser.Value() ||
                            C.chkActionRecallDate.Value() ||
                            C.chkActionWebMail.Value();
      cmdNext.prop("disabled", !actionsSelected);
      cmdFinish.prop("disabled", true);
      break;
      
    case "ActionDocument_DocumentSelect":
      // Select Document
      cmdNext.prop("disabled", C.gridDocuments.ActiveDataRowListIndex() == -1);
      break;
  }

  // Finish Button
  //cmdFinish.prop("disabled", tabIndex == 0 || tabIndex == tabWizard.TabCount() - 1 || (mRecord &amp;&amp; mRecord.ReadOnly));

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

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

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

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

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

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

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

    // Allow viewing recent list
    cmdHistory.prop("disabled", false);
  }
  
  // Only show Advanced button on relevant pages
  if (mRecord) {
    cmdAdvanced.hide()
    switch (tabWizard.SelectedTabId()) {
      case "ActionEmail":
        if (mRecord.PageEmailHasAdvanced) cmdAdvanced.show();
        break;
    }
  }
  else {
    cmdAdvanced.hide();
  }    
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        var found = false;
        for (var i = 0; i &lt; mRecord.Workflows.length; i++) {
          var item = mRecord.Workflows[i];
          found = true;
        }

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

      case "Actions":
        break;

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

  // Server-side validation
  if (Ok) {
    var params;
    switch (tabWizard.SelectedTabId()) {
      case "General":
        break;
        
      case "Actions":
        if (C.chkActionEmail.Value()) {
          params = {
            actionEmail: C.chkActionEmail.Value()
          }          
        }
        break;
    
      default:
        break;
    }

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

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

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

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

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

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { tabWizard_ValidatePost_General(validCallback); },
                                      null);
                                      
                                                  
        }
        else {
          tabWizard_ValidatePost_General(validCallback);
        }
        return;
        
      case "Actions":
        // Actions
        if (o.Data &amp;&amp; o.Data.ConfirmList &amp;&amp; o.Data.ConfirmList.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data.ConfirmList,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { tabWizard_ValidatePost_Actions(validCallback, o.Data); },
                                      null);
                                      
                                                  
        }
        else {
          tabWizard_ValidatePost_Actions(validCallback, o.Data);
        }        
        return;
    }

    // Callback
    validCallback();
  }
}

function tabWizard_ValidatePost_General(callback) {
  // Callback
  callback();
}

function tabWizard_ValidatePost_Actions(callback, data) {
  if (data) {
    // Email
    if (C.chkActionEmail.Value()) {
      mRecord_EmailAddresses = data.EmailAddresses;
      
      C.cboEmail.RefreshFromCollection(mRecord_EmailAddresses, "Value", "SourceNameAndDescription", "Source,Name,Role,Description,Value");
      C.cboEmailCc.RefreshFromCollection(mRecord_EmailAddresses, "Value", "SourceNameAndDescription", "Source,Name,Role,Description,Value");
      C.cboEmailBcc.RefreshFromCollection(mRecord_EmailAddresses, "Value", "SourceNameAndDescription", "Source,Name,Role,Description,Value");
      
      // Default Recipient
      if (data.DefaultRecipient) {
        C.cboEmail.Text(data.DefaultRecipient);
      }
      else {
        // Select first Email Address
        if (!C.cboEmail.Text()) C.cboEmail.ListIndex(0);
      }
      cboEmail_Change();
      
      // Branch
      if (data.BranchId) C.cboEmailBranch.Text(data.BranchId);
      cboEmailBranch_Change();    
      
      // Tags
      // NOTE: We never use the Description portion since we only want to insert the unresolved value at this point
      var tagsList = [];
      for (var i = 0; i &lt; data.Tags.length; i++) {
        var item = data.Tags[i];
        tagsList.push({ caption: item.Code, value: "[" + item.Code + "]" });
      }
      C.heEmailMessage.TagsListDefine(tagsList);  
    }  
  }

  // Callback
  callback();
}

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

  // Enable form
  frmMain.FormEnable();
}

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

      cancelCallback
    );
  };
}

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

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

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

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

// ===================================
// View an existing Background Process
// ===================================
function ViewExistingProcess(itemIndex) {
  var item = mRecord_CurrentProcesses[itemIndex];
  var Ok = true;
  
  // Validate

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

    // Status-dependant
    switch (item.Status) {
      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;
  }
}

// =========
// chkAction
// =========
function chkAction_Change(sender, e) {
  tabWizard_UpdateButtons();
}

// ================
// cmdActionButtons
// ================
function cmdActionButtons_Click(e) {
  var action = $(this).prop("id").substr(9);
  
  // Clear all checkboxes expect applicble one
  C.chkActionLog.Value(action == "Log");
  C.chkActionCommunicationIncoming.Value(action == "CommunicationIncoming");
  C.chkActionCommunicationOutgoing.Value(action == "CommunicationOutgoing");
  C.chkActionDocument.Value(action == "Document");
  C.chkActionEmail.Value(action == "Email");
  C.chkActionSms.Value(action == "Sms");
  C.chkActionAllocatedUser.Value(action == "AllocatedUser");
  C.chkActionRecallDate.Value(action == "RecallDate");
  C.chkActionWebMail.Value(action == "WebMail");
  
  // Move next tab
  tabWizard_Move(1);
}

// ===================
// cboActionLogSubject
// ===================
function cboActionLogSubject_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Find best outcome information list
  var InformationListId = "";
  for (var i = 0; i &lt; mRecord.Workflows.length; i++) {
    switch (mRecord.Workflows[i].TargetObjectType) {
      case "Account":
        InformationListId = "AccountLogOutcomes";
        break;
        
      case "AccountApp":
        InformationListId = "AccountAppLogOutcomes";
        break;
        
      case "Client":
        InformationListId = "ClientLogOutcomes";
        break;        
    }
    
    if (InformationListId) break;
  }

  // Update Log Outcome Information List (since this can be defined as a sectioned list)
  C.cboActionLogLogOutcome.SetLogOutcomeComboFromSectionedInformationList(InformationListId, C.cboActionLogSubject.Text(), "");
}

// =============
// gridDocuments
// =============
function gridDocuments_Refresh() {
  // Add Columns
  C.gridDocuments.ClearColumns();
  C.gridDocuments.AddColumnString("Category", { caption: "Category", visible: false });
  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);
}

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

  // Update cells
  e.row.AutoBind(item);
  if (!item.Category) e.row.cells.Category.value = "(none)";
}

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

function gridDocuments_AfterRowActivate() {
  // Get Document
  if (C.gridDocuments.ActiveDataRowListIndex() == -1) {
    mDocument = null;
  }
  else {
    mDocument = mRecord_Documents[C.gridDocuments.ActiveDataRowListIndex()];
  }
  
  // Update buttons
  tabWizard_UpdateButtons();
}

// ========
// Advanced
// ========
function AdvancedInitialise() {
  // Tweaks
  
  // General
  AdvancedInitialiseSection("EmailCostCentre", mRecord.ShowEmailCostCentre);
  AdvancedInitialiseSection("EmailOptions", mRecord.ShowEmailOptions);
}

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

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

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

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

function AdvancedToggle() {
  // Toggle Advanced
  mAdvancedVisible = !mAdvancedVisible;
  
  // Update Controls
  if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);  
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);  
  }
  
  // Other
  switch (tabWizard.SelectedTabId()) {
    default:
      break;
  }
  
  // Finalise
  AdvancedInitialise();  
  
  // Force resize
  tabWizard_Resize();
}

// ==============================
// cmdAllocatedPendingMakeCurrent
// ==============================
function cmdAllocatedPendingMakeCurrent_Click() {
  mAllocatedPendingMakeCurrent = true;
  C.cmdAllocatedPendingMakeCurrent.attr("disabled", "disabled");
  C.divAllocatedPendingMakeCurrent.show();
  
  C.lblAllocatedUser.VisibleRow(false);
  C.cboAllocatedUser.VisibleRow(false);
  C.chkAllocatedUpdateHold.VisibleRow(false);
  C.chkHoldAllocatedUser.VisibleRow(false);
  C.chkAllocatedUserRecallImmediately.VisibleRow(false);
}

// ========
// cboEmail
// ========
function cboEmail_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  if (mRecord_EmailAddresses &amp;&amp; C.cboEmail.ListIndex() != -1) {
    var item = mRecord_EmailAddresses[C.cboEmail.ListIndex()];
    
    if (item) {
      C.chkEmailHtml.Value(item.EmailHtml);
    }
  }
}

// ==============
// cboEmailBranch
// ==============
function cboEmailBranch_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Controls
  var branch = mRecord_EmailBranches.GetItem(C.cboEmailBranch.Text());
  if (branch) {
    C.cboEmailService.RefreshFromCollection(branch.Services, "ServiceId", "Name");
    C.cboEmailService.Text(branch.DefaultMessagingEmailServiceId);
  }
  else {
    C.cboService.RefreshUnbound("", "");
  }
  
  // Update Service
  cboEmailService_Change();
}

// ===============
// cboEmailService
// ===============
function cboEmailService_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Cost Centre Message
  var s = "";
  if (C.cboEmailService.Text()) {
    var branch = mRecord_EmailBranches.GetItem(C.cboEmailBranch.Text());
    if (branch) {
      for (var i = 0; i &lt; branch.Services.length; i++){
        var item = branch.Services[i];
        if (item.ServiceId == C.cboEmailService.Text()) {
          if (!C.cboEmailBranch.Text() || C.cboEmailBranch.Text().length == 0) {
            s = "This will be charged to the default 'Global' Cost Centre.";
          }             
          else 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.";
          }
          C.cboEmailTarget.ListFromCsvString(item.EmailMessageTargetCsvList);
          break;          
        }
      }
    }
  }
  C.divEmailCostCentreInformation.html(s);
}

// ======================
// chkAllocatedUpdateHold
// ======================
function chkAllocatedUpdateHold_Change(sender, e) {
  C.chkHoldAllocatedUser.ReadOnly(!C.chkAllocatedUpdateHold.Value());
}

// ===============
// cboRecallPeriod
// ===============
function cboRecallPeriod_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  C.dateRecallDate.VisibleRow(C.cboRecallPeriod.Text() == "To Date");
}

// ============
// chkEmailHtml
// ============
function chkEmailHtml_Change(sender, e) {
  C.heEmailMessage.PlainText(!C.chkEmailHtml.Value());
}

// ======================================
// Create a Fee Details conposite control
// ======================================
function CreateFeeDetails(id) {
  var C = {
    chkChargeFee: null,
    cboElement: null,
    numFee: null,
    txtReference: null,
    txtNotes: null,
  }

  // Get Element
  var e = $("#" + id);
  
  // Create table for controls
  var tbl = $("&lt;table class='is-form'&gt;" +
    "&lt;colgroup&gt;" +
    "&lt;col style='width:8px' /&gt;" +
    "&lt;col /&gt;" +
    "&lt;/colgroup&gt;" +
    "&lt;tbody&gt;" + 
    "&lt;tr&gt;&lt;th colspan='2'&gt;&lt;input id='chkChargeFee" + id + "' type='checkbox'/&gt;&lt;/th&gt;&lt;/tr&gt;" + 
    "&lt;tr style='display:none'&gt;&lt;th&gt;&lt;label for='cboElement" + id + "'&gt;Element:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id='cboElement" + id + "''/&gt;&lt;/td&gt;&lt;/tr&gt;" + 
    "&lt;tr style='display:none'&gt;&lt;th&gt;&lt;label for='numFee" + id + "'&gt;Value:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id='numFee" + id + "''/&gt;&lt;/td&gt;&lt;/tr&gt;" + 
    "&lt;tr style='display:none'&gt;&lt;th&gt;&lt;label for='txtReference" + id + "'&gt;Reference:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id='txtReference" + id + "''/&gt;&lt;/td&gt;&lt;/tr&gt;" + 
    "&lt;tr style='display:none'&gt;&lt;th&gt;&lt;label for='txtNotes" + id + "'&gt;Notes:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id='txtNotes" + id + "''/&gt;&lt;/td&gt;&lt;/tr&gt;" + 
    "&lt;/tbody&gt;" + 
    "&lt;/table&gt;");
  e.append(tbl);
  
  // Create Controls
  C.chkChargeFee = widget.UI.CheckBox("chkChargeFee" + id, {
    caption: "Charge a Fee to cover expenses?",
    
    onChange: function (sender, e) {
      C.cboElement.VisibleRow(C.chkChargeFee.Value());
      C.numFee.VisibleRow(C.chkChargeFee.Value());
      C.txtReference.VisibleRow(C.chkChargeFee.Value());
      C.txtNotes.VisibleRow(C.chkChargeFee.Value());
    },
  });
  C.cboElement = widget.UI.DBCombo("cboElement" + id, {
    allowBlank: false,
  });
  C.numFee = widget.UI.NumberBox("numFee" + id, {
    allowBlank: false,
    decimals: -1,
    minValue: 0,

    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.txtReference = widget.UI.TextBox("txtReference" + id, {
    maxLength: 20
  });
  C.txtNotes = widget.UI.TextBox("txtNotes" + id, {
    maxLength: 255
  });
  
  // Lists
  C.cboElement.RefreshFromStandardRange("Elements", "ElementType=400");
  
  return {
    TypeName: "CustomFeeDetails",
    ChargeFee: C.chkChargeFee.Value,
    Element: C.cboElement.Text,
    Fee: C.numFee.Value,
    Reference: C.txtReference.Text,
    Notes: C.txtNotes.Text,
    
    GetFeeDetails: function () {
      return {
        ChargeFee: C.chkChargeFee.Value(),
        ElementId: C.cboElement.Text(),
        Fee: C.numFee.Value(),
        Reference: C.txtReference.Text(),
        Notes: C.txtNotes.Text()
      }    
    },
  };
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <UniqueId>fvCMGy5cTUOREH2UaZyXVw</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>2000</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1400</HtmlWidgetMaxWidth>
    <HtmlWidgetDarkModeNotSupported>false</HtmlWidgetDarkModeNotSupported>
    <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>Workflow</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="SkipReviewPage" type="Boolean">
            <BlankTip />
            <Caption>Always skip Review page?</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="SkipReviewPageSingle" type="Boolean">
            <BlankTip />
            <Caption>Skip Review page if only a single Workflow is being processed</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="ShowEmailCostCentre" type="List">
            <BlankTip />
            <Caption>Show Email Cost Centre</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowEmailOptions" type="List">
            <BlankTip />
            <Caption>Show Email Options</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="WorkflowIds" type="Range">
            <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>
            <Rows>4</Rows>
            <RangeSingle>false</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>Workflows</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="ProcessId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>50</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DesktopMode" type="Boolean">
            <BlankTip />
            <Caption>Desktop Mode (testing only)</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeBroker" type="Boolean">
            <BlankTip />
            <Caption>Include Broker</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="IncludeDealer" type="Boolean">
            <BlankTip />
            <Caption>Include Dealer</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="IncludeEmployees" type="Boolean">
            <BlankTip />
            <Caption>Include Employees</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="IncludeGuarantors" type="Boolean">
            <BlankTip />
            <Caption>Include Guarantors</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="IncludeInsurer" type="Boolean">
            <BlankTip />
            <Caption>Include Insurer</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="IncludeManager" type="Boolean">
            <BlankTip />
            <Caption>Include Manager</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="IncludeOtherRoles" type="Boolean">
            <BlankTip />
            <Caption>Include Other Roles</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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>