<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-24T20:26:32.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-05-20T04:13:42.7160000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-24T20:26:20.9170000</UpdatedUtcDate>
    <ScriptId>HWSEM</ScriptId>
    <Description>Send Email Message Html Widget</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_EmailMessage
Option Explicit On
Option Strict On

' #################################################################
' Send Email Message wizard
'
' Version: 1.04 (25/09/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  23/11/2021  ISS      J027145   Created
'    1.01  25/03/2022  ISS      J028244   Added Attachment information to Confirmation page
'          07/04/2022  ISS      J028567   Fixed scroll issue with attachments block
'    1.02  10/08/2023  ISS      J031774   External Party and Ad-Hoc issues
'          15/08/2023  ISS      J031749   User incorrectly shows "Charge Fee" option
'          24/08/2023  ISS      J031882   Default subject for when launched from a record form
'    1.03  25/06/2024  ISS      J033766   Added widget parameters to send to GetSourceEmailAddresses()
'    1.04  25/09/2024  ISS      J034161   Update CC and BCC from textboxes to comboboxes
' #################################################################

' Constants
Private Const FORM_KEY As String = "EmailMessage"

' Common Parameters
Private mAllowChange As Boolean = False
Private mAllowFileAttachments As Boolean = True
Private mDefaultSubjectAccount As String
Private mDefaultSubjectClient As String
Private mEmailTo As String
Private mEmailCc As String
Private mEmailBcc 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
Private mParentSourceLogPk As Integer
Private mRecordId As String
Private mType As String
Private mWorkflowPk As Integer
Private mWorkflowItemPk As Integer

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

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

  ' Assume Success
  Main = True

  ' Initialise
  mRequestInfo = requestInfo

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

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

  ' Get Common Parameters
  With mCombinedParameters
    mAllowChange = .GetBoolean("AllowChange", mAllowChange)
    mAllowFileAttachments = .GetBoolean("AllowFileAttachments", mAllowFileAttachments)
    mDefaultSubjectAccount = .GetString("DefaultSubjectAccount")
    mDefaultSubjectClient = .GetString("DefaultSubjectClient")
    mEmailTo = .GetString("EmailTo")
    mEmailCc = .GetString("EmailCc")
    mEmailBcc = .GetString("EmailBcc")
    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)
    mParentSourceLogPk = .GetInteger("ParentSourceLogPk")    
    mRecordId = .GetString("Id")
    mType = .GetString("Type")
    mWorkflowPk = .GetInteger("WorkflowPk")
    mWorkflowItemPk = .GetInteger("WorkflowItemPk")
  End With

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

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

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

    Case "GetNonAccountFeeInfo"
      ' Get Fee information for non-Account Email Messages (Account ones are handled in WizardValidate)
      Main = GetNonAccountFeeInfo(parametersJson, returnValue)

    Case "GetEmailAddresses"
      ' Get a list of Email addresses
      Main = GetEmailAddresses(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;
'''  Builds a finSendEmailMessage object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateSendEmailMessage(ByRef sendEmailMessage As finSendEmailMessage,
                                        parameters As WizardFinishParameters) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  sendEmailMessage = finBL.CreateSendEmailMessage()

  ' Replying?
  If Success AndAlso mParentSourceLogPk &lt;&gt; 0 Then
    Success = sendEmailMessage.ParentSourceLogPkSet(finBL.Enums.isefinMessagingSourceType_FromString(mType), mRecordId, mParentSourceLogPk)
  End If

  ' Update
  If Success Then
    If parameters IsNot Nothing Then
      With sendEmailMessage
        .SourceTypeText = parameters.SourceTypeText
        .SourceId = parameters.SourceId
        .EmailTo = parameters.EmailTo
        .EmailCc = parameters.EmailCc
        .EmailBcc = parameters.EmailBcc
        .EmailHtml = parameters.EmailHtml
        .EmailSubject = parameters.EmailSubject
        .EmailMessage = parameters.EmailMessage

        ' File Attachments
        .FileAttachmentsFromScriptRequestInfo(mRequestInfo)

        ' Only set Branch if specified (setting the Source details will have defaulted the Branch)
        If Len(parameters.BranchId) &lt;&gt; 0 Then .BranchId = parameters.BranchId

        ' Log
        .LogSeverityId = parameters.LogSeverityId
        If parameters.LogActionTzDate IsNot Nothing Then
          .LogActionTimeZoneId = parameters.LogActionTimeZoneId
          .LogActionTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(parameters.LogActionTzDate)
        End If

        ' Fee
        If .FeeChargingEnabled Then
          .FeeAccountId = parameters.FeeAccountId
          .FeeCalculate()
          .FeeCharge = parameters.ChargeFee
          If .SourceType &lt;&gt; isefinMessagingSourceType.Account AndAlso .FeeCharge AndAlso parameters.Fee = 0 Then
            ' Do not overwrite calculated Fee
          Else
            .FeeValue = parameters.Fee
          End If
        End If

        ' Workflow
        .WorkflowPk = mWorkflowPk
        .WorkflowItemPk = mWorkflowItemPk
      End With
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Send Email Message.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim SendEmailMessage As finSendEmailMessage
  Dim obj As Object
  Dim Success As Boolean
  Dim SuccessPost As Boolean
  Dim WarningMessage As String
  Dim WizardFinishParameters As WizardFinishParameters
  Dim Workflow As finWorkflow
  Dim WorkflowItem As finWorkflowItem

  ' Assume Success
  Success = True

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

  ' Link to the current Workflow Item?
  If Success AndAlso mWorkflowPk &lt;&gt; 0 AndAlso mWorkflowItemPk = 0 AndAlso WizardFinishParameters.WorkflowLinkCurrentItem Then
    Workflow = finBL.CreateWorkflow()
    If Workflow.LoadPk(mWorkflowPk) Then
      WorkflowItem = Workflow.GetCurrentItem()
      If WorkflowItem IsNot Nothing Then mWorkflowItemPk = WorkflowItem.Pk
    Else
      Success = False
    End If
  End If

  ' Create finSendEmailMessage object
  If Success Then
    Success = CreateSendEmailMessage(SendEmailMessage, WizardFinishParameters)
  End If

  ' Send
  If Success Then
    If SendEmailMessage.ExecuteSendEmail(SuccessPost) Then
      If Not SuccessPost Then
        WarningMessage = finBL.Error.Message(True)
      End If
    Else
      Success = False
    End If
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Retrieve a Clients list of related Open Accounts as a Code Description List.
''' &lt;/summary&gt;
Private Function GetAccountsCodeDescriptionList(sourceType As isefinMessagingSourceType,
                                                sourceId As String,
                                                ByRef feeControlReadOnly As Boolean,
                                                ByRef codeDescriptionList As ISCodeDescriptionList) As Boolean

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim AccountApp As finAccountApp
  Dim AccountAppApplicant As finAccountAppApplicant
  Dim Client As finClient
  Dim ClientAccount As finClientAccount
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  feeControlReadOnly = False
  codeDescriptionList = finBL.Runtime.CreateCodeDescriptionList()

  ' Get Accounts
  Select Case sourceType
    Case isefinMessagingSourceType.Account
      ' =======
      ' Account
      ' =======
      Account = finBL.CreateAccount()
      Success = Account.Load(sourceId)

      If Success Then
        ' Check Account is Open
        If Account.Status = isefinAccountStatus.Open Then
          codeDescriptionList.Add(Account.AccountId, Account.Name)
        Else
          ' Account is closed, check Clients' other Accounts
          For Each AccountClient In Account.Clients
            For Each ClientAccount In AccountClient.Client.Accounts
              If IsClientAccountValid(ClientAccount) Then
                codeDescriptionList.Add(ClientAccount.AccountId, ClientAccount.Name)
              End If
            Next
          Next
        End If
      End If

    Case isefinMessagingSourceType.AccountApplication
      ' ===================
      ' Account Application
      ' ===================
      AccountApp = finBL.CreateAccountApp()
      Client = finBL.CreateClient()
      Success = AccountApp.Load(sourceId)

      ' Get Accounts for each Applicant (if they are an existing Client)
      If Success Then
        For Each AccountAppApplicant In AccountApp.Applicants
          If AccountAppApplicant.ClientPk &lt;&gt; 0 Then
            If Client.LoadPk(AccountAppApplicant.ClientPk) Then
              For Each ClientAccount In Client.Accounts
                If IsClientAccountValid(ClientAccount) Then
                  codeDescriptionList.Add(ClientAccount.AccountId, ClientAccount.Name)
                End If
              Next
            Else
              Success = False
            End If
          End If

          ' Exit if error
          If Not Success Then Exit For
        Next
      End If

    Case isefinMessagingSourceType.Client
      ' ======
      ' Client
      ' ======
      Client = finBL.CreateClient()
      Success = Client.Load(sourceId)

      ' Get Accounts
      If Success Then
        For Each ClientAccount In Client.Accounts
          If IsClientAccountValid(ClientAccount) Then
            codeDescriptionList.Add(ClientAccount.AccountId, ClientAccount.Name)
          End If
        Next
      End If
  End Select

  ' Fee Control read only?
  feeControlReadOnly = (codeDescriptionList.Count = 1)

  Return Success

End Function

''' &lt;summary&gt;
'''  Determines if a Client Account is valid to have a fee charged to it.
''' &lt;/summary&gt;
Private Function IsClientAccountValid(clientAccount As finClientAccount) As Boolean

  ' Determine if valid
  If clientAccount.Status = isefinAccountStatus.Open AndAlso Not clientAccount.AccountHidden AndAlso Not finBL.CurrentUserInformation.IsAccountFilteredOut(clientAccount.AccountId) Then
    Return True
  End If

  Return False

End Function

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

  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim SendEmailMessage As finSendEmailMessage
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

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

  If Success Then
    ' Create finSendEmailMessage object
    CreateSendEmailMessage(SendEmailMessage, Nothing)

    ' Form Initialisation Info
    If Success Then
      With FormInitialisationInfo
        ' Record
        .ParentSourceLogPk = mParentSourceLogPk
        If mParentSourceLogPk = 0 Then
          .SourceTypeText = finBL.Enums.isefinMessagingSourceType_ToString(finBL.Enums.isefinMessagingSourceType_FromString(mType))
          .SourceId = mRecordId
          .EmailTo = mEmailTo
          .EmailCc = mEmailCc
          .EmailBcc = mEmailBcc
          
          ' Defaults
          If Len(mType) &lt;&gt; 0 AndAlso Len(mRecordId) &lt;&gt; 0 Then
            .DefaultSubjectAccount = mDefaultSubjectAccount
            .DefaultSubjectClient = mDefaultSubjectClient
          End If

'          ' If not allowing change then pick up the record description to avoid DBCombos having to do it
'          If Not mAllowChange AndAlso Len(mRecordId) &lt;&gt; 0 Then
'            With SendEmailMessage
'              .SourceTypeText = mType
'              .SourceId = mRecordId
'              .SetRecipientDetails(Nothing)
'            End With
'            .SourceDescription = SendEmailMessage.RecipientName
'          End If
        Else
          ' Set from Log being replied to in CreateSendEmailMessage
          .SourceTypeText = SendEmailMessage.SourceTypeText
          .SourceId = SendEmailMessage.SourceId
          '.PhoneNumber = SendEmailMessage.RecipientPhoneNumber
        End If

        ' Workflow
        If mWorkflowPk &lt;&gt; 0 Then
          .WorkflowDescription = finBL.WorkflowFunctions.GetRecordCodeDescription(mWorkflowPk, .WorkflowId)
          .WorkflowItemPk = mWorkflowItemPk
        End If

        ' Lists
        .SourceTypesList = SendEmailMessage.GetSourceTypeList().ToCsvString()

        ' Configuration
        .AllowChange = mAllowChange OrElse Len(.SourceTypeText) = 0
        .AllowFileAttachments = mAllowFileAttachments
        .FormHeading = ScriptInfo.ScriptCaption
        If Len(.FormHeading) = 0 Then .FormHeading = "Email Message"
        If finBL.SettingsUser.CostCentreTestModeResolved Then .FormHeading &amp;= " (Test Mode)"
        .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
        .ReadOnly = finBL.Database.IsReadOnly
        .TestMode = finBL.SettingsUser.CostCentreTestModeResolved
      End With

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Email Addresses.
''' &lt;/summary&gt;
Private Function GetEmailAddresses(ByRef returnValue As String) As Boolean

  Dim EmailAddresses As finMessagingContacts
  Dim SendEmailMessage As finSendEmailMessage
  Dim obj As Object
  Dim SourceId As String
  Dim SourceTypeText As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Create finSendEmailMessage object
  If Success Then
    CreateSendEmailMessage(SendEmailMessage, Nothing)
    With SendEmailMessage
      .SourceTypeText = SourceTypeText
      .SourceId = SourceId

      EmailAddresses = .GetSourceEmailAddresses(
                          mIncludeGuarantors,
                          mIncludeEmployees,
                          mIncludeManager,
                          mIncludeDealer,
                          mIncludeBroker,
                          mIncludeInsurer,
                          mIncludeOtherRoles)
    End With

    obj = New With {
      .BranchId = SendEmailMessage.BranchId,
      .EmailAddresses = EmailAddresses.ToJsonObject(),
      .Tags = SendEmailMessage.GetSourceTagList().ToCodeDescriptionList().ToJsonObject()
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Validates the Tax Period being closed.
''' &lt;/summary&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim ConfirmList As New List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim FeeAccountReadOnly As Boolean
  Dim FeeAccounts As ISCodeDescriptionList
  Dim Html As String
  Dim obj As Object
  Dim PageId As String
  Dim SendEmailMessage As finSendEmailMessage
  Dim Success As Boolean
  Dim Warnings As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

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

  ' Validate
  If Success Then
    Select Case PageId
      Case "General"
      ' Create finSendEmailMessage object
      Success = CreateSendEmailMessage(SendEmailMessage, WizardFinishParameters)

      ' Get Fee Accounts
      GetAccountsCodeDescriptionList(SendEmailMessage.SourceType, SendEmailMessage.SourceId, FeeAccountReadOnly, FeeAccounts)

      ' Calculate Fee?
      ' NOTE: This will only be used by the JavaScript if something has changed since the last fetch (i.e., it won't overwrite a user-entered fee)
      With SendEmailMessage
        If .SourceType = isefinMessagingSourceType.Account Then
          If FeeAccounts.Count = 1 Then .FeeAccountId = FeeAccounts(0).Code
          .FeeCalculate()
        End If
      End With

      ' Validate
      If Success Then
        If Not SendEmailMessage.EmailToValidate(FailedMessage) Then
          FailedControlId = "cboEmail"
        ElseIf Not SendEmailMessage.EmailCcValidate(FailedMessage) Then
          FailedControlId = "cboEmailCc"
        ElseIf Not SendEmailMessage.EmailBccValidate(FailedMessage) Then
          FailedControlId = "cboEmailBcc"
        End If
      End If

      ' Get Preview
      If Success Then
        Html = SendEmailMessage.GetMessagePreviewHtml(Warnings, True)

        Data = New With {
                    .HtmlSummary = Html,
                    .FeeChargingEnabled = SendEmailMessage.FeeChargingEnabled,
                    .FeeAllowChange = SendEmailMessage.FeeAllowChange,
                    .FeeCharge = SendEmailMessage.FeeCharge,
                    .Fee = SendEmailMessage.FeeValue,
                    .FeeAccountId = SendEmailMessage.FeeAccountId,
                    .FeeAccountReadOnly = FeeAccountReadOnly,
                    .FeeAccounts = FeeAccounts.ToJsonObject(False),
                    .Warnings = Warnings
                  }
      End If
    End Select
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Fee information for non-Account SMS Messages (Account ones are handled in WizardValidate).
''' &lt;/summary&gt;
Private Function GetNonAccountFeeInfo(parametersJson As String,
                                      ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim Data As Object
  Dim SendEmailMessage As finSendEmailMessage
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create finSendEmailMessage object
  If Success Then
    Success = CreateSendEmailMessage(SendEmailMessage, WizardFinishParameters)
  End If

  ' Load Fee Account for additional checks
  If Success Then
    Account = finBL.CreateAccount()
    Account.Load(SendEmailMessage.FeeAccountId)
  End If

  ' Finalise
  If Success Then
    Data = New With {
                .FeeChargingEnabled = SendEmailMessage.FeeChargingEnabled AndAlso Account.Status = isefinAccountStatus.Open,
                .FeeAllowChange = SendEmailMessage.FeeAllowChange,
                .FeeCharge = SendEmailMessage.FeeCharge,
                .Fee = SendEmailMessage.FeeValue
              }
  End If

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

  Return Success

End Function



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

  ' Record
  Public SourceTypeText As String
  Public SourceId As String
  Public SourceDescription As String
  Public ParentSourceLogPk As Integer
  Public EmailTo As String
  Public EmailCc As String
  Public EmailBcc As String
  
  ' Defaults
  Public DefaultSubjectAccount As String
  Public DefaultSubjectClient As String

  ' Workflow
  Public WorkflowId As String
  Public WorkflowDescription As String
  Public WorkflowItemPk As Integer

  ' Lists
  Public SourceTypesList As String

  ' Configuration
  Public AllowChange As Boolean
  Public AllowFileAttachments As Boolean
  Public FormHeading As String
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean
  Public TestMode As Boolean

End Class



''' &lt;summary&gt;
'''  Finish Details.
''' &lt;/summary&gt;
Public Class WizardFinishDetails

  Public WarningMessage As String

  Public Sub New(warningMessage As String)

    Me.WarningMessage = warningMessage

  End Sub

End Class



''' &lt;summary&gt;
'''  Wizard Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters

  Public SourceTypeText As String
  Public SourceId As String
  Public BranchId As String
  Public EmailHtml As Boolean
  Public EmailTo As String
  Public EmailCc As String
  Public EmailBcc As String
  Public EmailMessage As String
  Public EmailSubject As String
  Public RecipientName As String

  ' Log details
  Public LogActionTimeZoneId As String
  Public LogActionTzDate As Date?
  Public LogSeverityId As String

  ' Fee details
  Public ChargeFee As Boolean
  Public FeeAccountId As String
  Public Fee As Decimal

  ' Workflow
  Public WorkflowLinkCurrentItem As Boolean

End Class



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

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

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

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

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "EmailMessage".

LIMITATIONS: This widget does not allow "Save as Draft" or "Open For Edit" functionality and relies on SMTP being configured.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Enter Email details."&gt;Email&lt;/li&gt;
        &lt;li tabId="Confirm" tooltipText="Confirm the message to be sent."&gt;Confirm&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;

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

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblRecipient"&gt;Specify Recipient details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboSourceType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboSourceType" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtEmail"&gt;Email:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtEmail" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboAccount"&gt;Account:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboAccount" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboAccountApp"&gt;Application:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboAccountApp" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboClient"&gt;Client:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboClient" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboExternalParty"&gt;External&amp;nbsp;Party:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboExternalParty" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboUser"&gt;User:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboUser" /&gt;&lt;/td&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;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblWorkflow"&gt;Workflow details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboWorkflow"&gt;Workflow:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboWorkflow" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkWorkflowLinkCurrentItem" type="checkbox"/&gt;&lt;/th&gt;
          &lt;/tr&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;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkEmailHtml" type="checkbox"/&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

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

      &lt;div style="flex-grow:1; margin-left:8px; position:relative; 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;!-- Confirm --&gt;
    &lt;div id="pageConfirm" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:0"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblLog"&gt;Specify details for the Log that will be created to record this Message&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateLogActionDate"&gt;Action:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;div id="dateLogActionDate"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboLogSeverity"&gt;Severity:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboLogSeverity" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblFee"&gt;Charge a Fee?&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkFeeChargeFee" type="checkbox"/&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th class="indent1"&gt;&lt;label for="cboFeeAccount"&gt;Account:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboFeeAccount" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th class="indent1"&gt;&lt;label for="numFee"&gt;Fee:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numFee" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblMessagePreview"&gt;The following Message will be sent&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div id="divPreviewWarnings" class="is-info-text warning" style="flex-grow:0"&gt;&lt;/div&gt;
      &lt;div style="flex-grow:1; position:relative; margin-left:8px"&gt;
        &lt;div id="wbMessagePreview" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;

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

&lt;script&gt;
// Record
var mRecord;

// Global Collections

// Controls
var C = {
  // General
  lblRecipient: null,
  cboSourceType: null,
  txtEmail: null,
  cboAccount: null,
  cboAccountApp: null,
  cboClient: null,
  cboExternalParty: null,
  cboUser: null,
  cboEmail: null,
  cboEmailCc: null,
  cboEmailBcc: null,

  lblWorkflow: null,
  cboWorkflow: null,
  chkWorkflowLinkCurrentItem: null,

  lblEmailSubject: null,
  chkEmailHtml: null,
  txtEmailSubject: null,
  heEmailMessage: null,

  divFileAttachments: null,
  lblFileAttachments: null,
  fuFileAttachments: null,

  // Confirm
  lblLog: null,
  dateLogActionDate: null,
  cboLogSeverity: null,

  lblFee: null,
  chkFeeChargeFee: null,
  cboFeeAccount: null,
  numFee: null,

  lblMessagePreview: null,
  divPreviewWarnings: null,
  wbMessagePreview: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mTimer;

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

  // Controls
  //   General
  C.lblRecipient = widget.UI.Label("lblRecipient", {});
  C.cboSourceType = widget.UI.ComboBox("cboSourceType", {
    allowBlank: true,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_15,

    onChange: cboSourceType_Change,
  });
  C.txtEmail = widget.UI.TextBox("txtEmail", {
    allowBlank: false,
    maxLength: 255,
  });
  C.cboAccount = widget.UI.DBCombo("cboAccount", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboEmail_Refresh,
  });
  C.cboAccountApp = widget.UI.DBCombo("cboAccountApp", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboEmail_Refresh,
  });
  C.cboClient = widget.UI.DBCombo("cboClient", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboEmail_Refresh,
  });
  C.cboExternalParty = widget.UI.DBCombo("cboExternalParty", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboEmail_Refresh,
  });
  C.cboUser = widget.UI.DBCombo("cboUser", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_20,

    onChange: cboEmail_Refresh,
  });
  C.cboEmail = widget.UI.DBCombo("cboEmail", {
    allowBlank: false,
    limitToList: false,
    maxLength: 0,
    showDescription: false
  });
  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.lblWorkflow = widget.UI.Label("lblWorkflow", {
    tooltipText: "By default, the Log created will be linked to this Workflow but not the current Workflow Item.",
  });
  C.cboWorkflow = widget.UI.DBCombo("cboWorkflow", {
    allowBlank: true,
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.chkWorkflowLinkCurrentItem = widget.UI.CheckBox("chkWorkflowLinkCurrentItem", {
    caption: "Link to the current Workflow Item?"
  });

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

  //   Confirm
  C.lblLog = widget.UI.Label("lblLog", {});
  C.dateLogActionDate = widget.UI.DateTimeZone("dateLogActionDate", {
    timeZoneVisible: true,
  });
  C.cboLogSeverity = widget.UI.DBCombo("cboLogSeverity", {});

  C.lblFee = widget.UI.Label("lblFee", {});
  C.chkFeeChargeFee = widget.UI.CheckBox("chkFeeChargeFee", {
    caption: "Charge Fee?",

    onChange: chkFeeChargeFee_Change,
  });
  C.cboFeeAccount = widget.UI.DBCombo("cboFeeAccount", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboFeeAccount_Change,
  });
  C.numFee = widget.UI.NumberBox("numFee", {
    allowBlank: false,
    decimals: -1,
    minValue: 0,

    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblMessagePreview = widget.UI.Label("lblMessagePreview", {});
  C.divPreviewWarnings = $("#divPreviewWarnings");
  C.wbMessagePreview = widget.UI.PreviewPane("wbMessagePreview", {});

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

  // Reset Form
  Form_Reset();
});

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults
  C.chkEmailHtml.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;

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

      // Global Collections
      //mBranches = mRecord.Branches;

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

      Fields_Load();
    },

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboSourceType.Text(mRecord.SourceTypeText);
    if (mRecord.AllowChange) {
      C.cboAccount.Text(mRecord.SourceId);
      C.cboAccountApp.Text(mRecord.SourceId);
      C.cboClient.Text(mRecord.SourceId);
      C.cboExternalParty.Text(mRecord.SourceId);
      C.cboUser.Text(mRecord.SourceId);
    }
    else {
      C.cboAccount.RefreshUnbound(mRecord.SourceId, mRecord.SourceDescription);
      C.cboAccountApp.RefreshUnbound(mRecord.SourceId, mRecord.SourceDescription);
      C.cboClient.RefreshUnbound(mRecord.SourceId, mRecord.SourceDescription);
      C.cboExternalParty.RefreshUnbound(mRecord.SourceId, mRecord.SourceDescription);
      C.cboUser.RefreshUnbound(mRecord.SourceId, mRecord.SourceDescription);
    }
    C.txtEmail.Text(mRecord.EmailTo);
    C.cboEmail.Text(mRecord.EmailTo);
    C.cboEmailCc.Text(mRecord.EmailCc);
    C.cboEmailBcc.Text(mRecord.EmailBcc);

    C.cboWorkflow.RefreshUnbound(mRecord.WorkflowId, mRecord.WorkflowDescription);
    
    // Defaults
    switch(mRecord.SourceTypeText) {
      case "Account":
        if (mRecord.DefaultSubjectAccount) C.txtEmailSubject.Text(mRecord.DefaultSubjectAccount);
        break;
      
      case "Client":
        if (mRecord.DefaultSubjectClient) C.txtEmailSubject.Text(mRecord.DefaultSubjectClient);
        break;
    }

    // Confirm
  }

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

  // Update Controls
  if (mRecord) {
    cboSourceType_Change();
  }

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

// =============
// cboSourceType
// =============
function cboSourceType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Controls
  C.txtEmail.VisibleRow(false);
  C.cboAccount.VisibleRow(false);
  C.cboAccountApp.VisibleRow(false);
  C.cboClient.VisibleRow(false);
  C.cboExternalParty.VisibleRow(false);
  C.cboUser.VisibleRow(false);
  C.cboEmail.VisibleRow(false);
  C.divFileAttachments.hide();

  switch(C.cboSourceType.Text()) {
    case "Account":
      C.cboAccount.VisibleRow(true);
      if (mRecord.AllowChange &amp;&amp; !C.cboAccount.isRefreshed) {
        C.cboAccount.isRefreshed = true;
        C.cboAccount.RefreshFromStandardRange("Accounts");
      }
      C.cboEmail.VisibleRow(true);
      break;

    case "Account Application":
      C.cboAccountApp.VisibleRow(true);
      if (mRecord.AllowChange &amp;&amp; !C.cboAccountApp.isRefreshed) {
        C.cboAccountApp.isRefreshed = true;
        C.cboAccountApp.RefreshFromStandardRange("AccountApps");
      }
      C.cboEmail.VisibleRow(true);
      break;

    case "Client":
      C.cboClient.VisibleRow(true);
      if (mRecord.AllowChange &amp;&amp; !C.cboClient.isRefreshed) {
        C.cboClient.isRefreshed = true;
        C.cboClient.RefreshFromStandardRange("Clients");
      }
      C.cboEmail.VisibleRow(true);
      break;

    case "External Party":
      C.cboExternalParty.VisibleRow(true);
      if (mRecord.AllowChange &amp;&amp; !C.cboExternalParty.isRefreshed) {
        C.cboExternalParty.isRefreshed = true;
        C.cboExternalParty.RefreshFromStandardRange("ExternalParties");
      }
      C.cboEmail.VisibleRow(true);
      break;

    case "User":
      C.cboUser.VisibleRow(true);
      if (mRecord.AllowChange &amp;&amp; !C.cboUser.isRefreshed) {
        C.cboUser.isRefreshed = true;
        C.cboUser.RefreshFromStandardRange("Users");
      }
      C.cboEmail.VisibleRow(true);
      break;

    default:
      C.txtEmail.VisibleRow(true);

      // Tags
      var tagsList = [{ caption: "NoSignature", value: "[NoSignature]"}];
      C.heEmailMessage.TagsListDefine(tagsList);
      break;
  }

  // Allow File Attachments
  if (mRecord.AllowFileAttachments) {
    switch(C.cboSourceType.Text()) {
      case "":
      case "Account":
      case "Account Application":
      case "Client":
      case "External Party":
      case "User":
        C.divFileAttachments.show();
        fuFileAttachments_Refresh();
        break;
    }
  }

  // Clear record?
  if (sender &amp;&amp; !C.cboSourceType.ReadOnly()) {
    C.cboAccount.Text("");
    C.cboAccountApp.Text("");
    C.cboClient.Text("");
    C.cboExternalParty.Text("");
    C.cboUser.Text("");
    C.cboFeeAccount.Text("");
  }

  // Resize
  tabWizard_Resize();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    workflowLinkCurrentItem: C.chkWorkflowLinkCurrentItem.Value(),

    sourceTypeText: C.cboSourceType.Text(),
    emailTo: C.cboEmail.Text(),
    emailCc: C.cboEmailCc.Text(),
    emailBcc: C.cboEmailBcc.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(),
  }

  switch(params.sourceTypeText) {
    case "Account":
      params.sourceId = C.cboAccount.Text();
      break;

    case "Account Application":
      params.sourceId = C.cboAccountApp.Text();
      break;

    case "Client":
      params.sourceId = C.cboClient.Text();
      break;

    case "External Party":
      params.sourceId = C.cboExternalParty.Text();
      break;

    case "User":
      params.sourceId = C.cboUser.Text();
      break;

    default:
      params.emailTo = C.txtEmail.Text();
      break;
  }

  return params;
}

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

  // Information Lists

  // Lists
  if (mRecord) {
    C.cboSourceType.ListFromCsvString(mRecord.SourceTypesList);
    C.cboLogSeverity.RefreshFromStandardRange("LogSeverities");
  }

  // Controls
  if (mRecord) {
    C.cboSourceType.ReadOnly(!mRecord.AllowChange);
    C.cboAccount.ReadOnly(!mRecord.AllowChange);
    C.cboAccountApp.ReadOnly(!mRecord.AllowChange);
    C.cboClient.ReadOnly(!mRecord.AllowChange);
    C.cboExternalParty.ReadOnly(!mRecord.AllowChange);
    C.cboUser.ReadOnly(!mRecord.AllowChange);

    if (!mRecord.WorkflowId) {
      C.lblWorkflow.VisibleRow(false);
      C.cboWorkflow.VisibleRow(false);
      C.chkWorkflowLinkCurrentItem.VisibleRow(false);
    }
    else if(mRecord.WorkflowItemPk) {
      // Workflow Item specified so don't give option to link to current
      C.chkWorkflowLinkCurrentItem.VisibleRow(false);
    }

    // Refresh Email Addresses
    cboEmail_Refresh();

    chkEmailHtml_Change();
    chkFeeChargeFee_Change();
    C.cboFeeAccount.RefreshFromStandardRange("Accounts");

    // Replying to a Log?
    if (mRecord.ParentSourceLogPk != 0) {
      C.cboSourceType.ReadOnly(true);
      C.cboAccount.ReadOnly(true);
      C.cboAccountApp.ReadOnly(true);
      C.cboClient.ReadOnly(true);
      C.cboExternalParty.ReadOnly(true);
      C.cboUser.ReadOnly(true);
    }
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

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

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

function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function() {
    if (mRecord.PromptOnCommit) {
      // Confirm
      var heading = "Send Email";
      var message = "&lt;p&gt;Are you sure you want to send this Email?&lt;/p&gt;";

      widget.UI.MsgBoxConfirm(message,
                              {
                                heading: heading,
                                icon: "Email",
                                messageIsHtml: true,
                              },
                              Form_ExecuteAction_FinishPost,
                              null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishPost() {
  // Block UI
  widget.UI.Block("Sending Email, please wait...");

  // Get Parameters
  var params = CreateFinishParameters();

  // Finish
  widget.UploadFiles("Finish", params, C.fuFileAttachments.GetFileData(),
    function (data) {
      // Parse
      data = JSON.parse(data);

      // Unblock
      widget.UI.Unblock();

      // Refresh Parent
      widget.RefreshParent();

      // Refresh Workflow?
      if (mRecord.WorkflowId) widget.ActionNotificationSend("WorkflowRefresh", { workflowId: mRecord.WorkflowId }, null, true);

      // Warning?
      if (data.WarningMessage) {
        widget.UI.MsgBoxAlert("The SMS was sent but the following warning was given:\n\n" + data.WarningMessage, {},
          function () {
            // Close
            widget.Close();
          }
        );
      }
      else {
        // Close
        widget.Close();
      }
    },

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

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

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

  // Tab
  tabWizard_Resize();
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        default:
          found = true;
          break;
      }

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

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

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

      default:
        break;
    }
  }

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

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

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

  // Resize Wizard
  tabWizard_Resize();

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.txtEmail.WidthResizeFromParent();
      C.cboAccount.WidthResizeFromParent();
      C.cboAccountApp.WidthResizeFromParent();
      C.cboClient.WidthResizeFromParent();
      C.cboExternalParty.WidthResizeFromParent();
      C.cboUser.WidthResizeFromParent();
      C.cboEmail.WidthResizeFromParent();
      C.cboEmailCc.WidthResizeFromParent();
      C.cboEmailBcc.WidthResizeFromParent();
      break;

    case "Confirm":
      C.cboLogSeverity.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  // Back, Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();

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

  // Finish Button
  if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        break;

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

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

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

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

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

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

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

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

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage, {}, function () {
      if (o.FailedControlId) $("#" + o.FailedControlId).focus();
    });
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        mRecord_Confirm = o.Data;

        // Update Fee details
        if (C.cboSourceType.Text() == "Account") {
          C.cboFeeAccount.Text(o.Data.FeeAccountId);
          C.numFee.Value(o.Data.Fee);
          if (o.Data.FeeCharge) {
            C.chkFeeChargeFee.Value(true);
          }
          else {
            C.chkFeeChargeFee.Value(false);
          }
        }
        else {
          // Handled in cboFeeAccount_Change
        }

        // Refresh Page
        pageConfirm_Refresh();
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ========
// cboEmail
// ========
function cboEmail_Refresh(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Reset Fee Account
  C.cboFeeAccount.Text("");

  // Refresh File Attachments control
  fuFileAttachments_Refresh();

  // Build refresh key
  var params = CreateFinishParameters();
  var key = params.sourceTypeText + "|" + params.sourceId;

  // Refresh required?
  if (!params.sourceTypeText || !params.sourceId || C.cboEmail.refreshKey == key) return;

  // Refresh
  C.cboEmail.refreshKey = key;
  if (sender) C.cboEmail.RefreshUnbound("", "");

  widget.GetString("GetEmailAddresses", { sourceTypeText: params.sourceTypeText, sourceId: params.sourceId },
    function (data) {
      // Parse
      data = JSON.parse(data);

      C.cboEmail.RefreshFromCollection(data.EmailAddresses, "Value", "SourceNameAndDescription", "Source,Name,Role,Description,Value");
      C.cboEmailCc.RefreshFromCollection(data.EmailAddresses, "Value", "SourceNameAndDescription", "Source,Name,Role,Description,Value");
      C.cboEmailBcc.RefreshFromCollection(data.EmailAddresses, "Value", "SourceNameAndDescription", "Source,Name,Role,Description,Value");

      // Select first Email Address
      if (!C.cboEmail.Text()) C.cboEmail.ListIndex(0);

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

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

// ===============
// chkFeeChargeFee
// ===============
function chkFeeChargeFee_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  C.cboFeeAccount.VisibleRow(C.chkFeeChargeFee.Value());
  C.numFee.VisibleRow(C.chkFeeChargeFee.Value());
}

// ===========
// pageConfirm
// ===========
function pageConfirm_Refresh() {
  var attachmentCount = C.fuFileAttachments.GetFileData().length;
  var feeVisible = true;
  var params = CreateFinishParameters();

  // Preview
  C.wbMessagePreview.SetContent(mRecord_Confirm.HtmlSummary, false);
  var htmlMessage = "The following Message will be sent to &lt;span style='background-color:yellow; padding:2px'&gt;" + widget.UI.HtmlEncode(params.emailTo) + "&lt;/span&gt;";
  if (attachmentCount != 0) {
    htmlMessage += " and will contain &lt;span style='background-color:yellow; padding:2px'&gt;" + widget.UI.HtmlEncode(attachmentCount) + "&lt;/span&gt; file";
    if (attachmentCount != 1) htmlMessage += "s";
  }
  C.lblMessagePreview.Html(htmlMessage);

  // Warnings
  if (mRecord_Confirm.Warnings) {
    C.divPreviewWarnings.html(widget.UI.HtmlEncode(mRecord_Confirm.Warnings));
    C.divPreviewWarnings.show();
  }
  else {
    C.divPreviewWarnings.html("");
    C.divPreviewWarnings.hide();
  }

  // Controls
  if (C.cboSourceType.Text()) {
    C.lblLog.VisibleRow(true);
    C.dateLogActionDate.VisibleRow(true);
    C.cboLogSeverity.VisibleRow(true);
  }
  else {
    C.lblLog.VisibleRow(false);
    C.dateLogActionDate.VisibleRow(false);
    C.cboLogSeverity.VisibleRow(false);
  }

  // Charge Fee
  if (C.cboSourceType.Text() == "Account") {
    C.cboFeeAccount.ReadOnly(mRecord_Confirm.FeeAccountReadOnly);
    C.numFee.ReadOnly(!mRecord_Confirm.FeeAllowChange);
  }
  else {
    // Non-Account so Fee details may change based on the selected Fee Account so we can't disable them
    C.cboFeeAccount.ReadOnly(false);
    C.numFee.ReadOnly(!mRecord_Confirm.FeeAllowChange);
  }

  // Refresh Fee Combo
  if (mRecord_Confirm.FeeAccounts &amp;&amp; mRecord_Confirm.FeeAccounts.length != 0) {
    if (mRecord_Confirm.FeeAccounts.length == 1) {
      var item = mRecord_Confirm.FeeAccounts[0];

      C.cboFeeAccount.ReadOnly(true);
      C.cboFeeAccount.RefreshUnbound(item.Code, item.Description);
    }
    else {
      C.cboFeeAccount.RefreshFromCollection(mRecord_Confirm.FeeAccounts, "Code", "Description");
    }
  }
  else {
    feeVisible = false;
  }

  // Special Handling for Users &amp; External Parties
  switch (C.cboSourceType.Text()) {
    case "External Party":
      feeVisible = true;
      C.cboFeeAccount.RefreshFromStandardRange("Accounts", "Status=1");
      break;
      
    case "User":
      feeVisible = false;
      break;
  }

  // Fail-safe to ensure no fee can be charged if not supported by the Cost Centre
  if (!mRecord_Confirm.FeeChargingEnabled) {
    feeVisible = false;
  }

  // Update Fee Visibility
  C.lblFee.VisibleRow(feeVisible);
  C.chkFeeChargeFee.VisibleRow(feeVisible);
  C.cboFeeAccount.VisibleRow(feeVisible);
  C.numFee.VisibleRow(feeVisible);

  // Update Controls
  if (feeVisible) {
    chkFeeChargeFee_Change();
  }
  else {
    // Ensures CreateFinishParameters() sends through the correct value if hidden
    C.chkFeeChargeFee.Value(false);
  }

  // Auto-Format page to sort out topmost headings
  tabWizard.AutoFormatPage();
}

// =============
// cboFeeAccount
// =============
function cboFeeAccount_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // If we're not dealing with an Account SMS, we must retrieve defaults for Fees etc AFTER selecting an Account
  if (sender &amp;&amp; C.cboSourceType.Text() != "Account" &amp;&amp; C.cboFeeAccount.Text()) {
    var params = CreateFinishParameters();

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

        // Update Confirmation details
        mRecord_Confirm.FeeChargingEnabled = data.FeeChargingEnabled;
        mRecord_Confirm.FeeAllowChange = data.FeeAllowChange;

        // Default Fee
        C.numFee.Value(data.Fee);

        // Just in case!
        if (!mRecord_Confirm.FeeChargingEnabled) {
          // NOTE: Cannot simply uncheck chkFeeCharge since this hides the Account!
          widget.UI.MsgBoxAlert("Fee charging is not enabled for this Account.");

          // NOTE: The User may overwrite this but the Finish process will prevent the Fee from actually attempting to charge
          C.numFee.Value(0);
        }

        // Refresh Page
        pageConfirm_Refresh();
      },

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

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

// =================
// fuFileAttachments
// =================
function fuFileAttachments_Refresh() {
  // Refresh File Attachments control
  if (mRecord.AllowFileAttachments) {
    var params = CreateFinishParameters();
    var sourceType = params.sourceTypeText;
    var sourceId = params.sourceId;

    if (params.sourceId) {
      switch(sourceType) {
        case "Account Application":
          sourceType = "AccountApp";
          break;
          
        case "External Party":
          sourceType = "ExternalParty";
          break;
      }
    }
    else {
      sourceTypeText = "";
    }

    C.fuFileAttachments.RefreshDocumentManager(sourceType, sourceId);
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>fFs+VTIx30+3EVCsWUzlpA</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption>Email Message</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1024</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>Email</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="AllowFileAttachments" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="Type" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>AccountApp,Account,Client,ExternalParty,User</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="Id" 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>20</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ParentSourceLogPk" type="Number">
            <BlankTip />
            <Caption>ParentSourceLogPk</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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="EmailTo" 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>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="EmailCc" 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>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="EmailBcc" 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>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AllowChange" type="Boolean">
            <BlankTip />
            <Caption>AllowChange</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="WorkflowPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="WorkflowItemPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Default Subjects when run from a record form.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DefaultSubjectAccount" type="Text">
            <BlankTip />
            <Caption>Account Subject:</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>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DefaultSubjectClient" type="Text">
            <BlankTip />
            <Caption>Client Subject:</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>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Include Contact Types</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <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>