<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-06-24T21:50:42.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2024-06-21T02:48:35.0080000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2024-06-24T21:47:49.9520000</UpdatedUtcDate>
    <ScriptId>hwSendSms</ScriptId>
    <Description>Send SMS Message Html Widget</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_SmsMessage
Option Explicit On
Option Strict On

' #################################################################
' Send SMS Message wizard
'
' Version: 1.05 (25/06/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.03  05/04/2022  ISS      J026102   Visual glitch when first loading
'    1.04  23/12/2022  ISS      J027688   Updated to use DateTimeZone control for Action Date
'    1.05  25/06/2024  ISS      J033766   Added widget parameters to send to GetSourcePhoneNumbers()
' #################################################################

' Constants
Private Const FORM_KEY As String = "SmsMessage"

' Common Parameters
Private mAllowChange As Boolean
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 mPhoneNumber As String
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 mStartupParameters As ISKeyValueList

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

  ' Assume Success
  Main = True

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

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

  ' Get Common Parameters
  With mCombinedParameters
    mAllowChange = .GetBoolean("AllowChange", True)
    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")
    mPhoneNumber = .GetString("PhoneNumber")
    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 SMS Messages (Account ones are handled in WizardValidate)
      Main = GetNonAccountFeeInfo(parametersJson, returnValue)

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

    Case "GetSmsInfo"
      ' Get SMS Information
      Main = GetSmsInfo(parametersJson, 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 finMessagingSmsMessage object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateMessagingSmsMessage(ByRef messagingSmsMessage As finMessagingSmsMessage,
                                           parameters As WizardFinishParameters) As Boolean

  Dim MessagingContact As finMessagingContact
  Dim MessagingContact2 As finMessagingContact
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  messagingSmsMessage = finBL.Messaging.CreateMessagingSmsMessage(isefinMessagingSmsMessageContext.UserInterface)

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

  ' Update
  If Success Then
    If parameters IsNot Nothing Then
      With messagingSmsMessage
        .SourceTypeText = parameters.SourceTypeText
        .SourceId = parameters.SourceId
        .RecipientPhoneNumber = parameters.PhoneNumber
        .BranchReset()
        .BranchId = parameters.BranchId
        .ServiceReset()
        .ServiceId = parameters.ServiceId
        .MessageBody = parameters.Message

        ' Recipient
        If .SourceType = isefinMessagingSourceType.None Then
          .RecipientName = parameters.RecipientName
        Else
          ' See if supplied Phone Number exists in list
          For Each MessagingContact2 In .GetSourcePhoneNumbers()
            If MessagingContact2.Value = parameters.PhoneNumber Then
              MessagingContact = MessagingContact2
              Exit For
            End If
          Next

          .SetRecipientDetails(MessagingContact)
        End If

        ' 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;
'''  Import Bank Transactions.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim MessagingSmsMessage As finMessagingSmsMessage
  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 Messaging SMS object
  If Success Then
    Success = CreateMessagingSmsMessage(MessagingSmsMessage, WizardFinishParameters)
  End If

  ' Send
  If Success Then
    If MessagingSmsMessage.ExecuteSendSms(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 Branch As finBranchRO
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim MessagingSmsMessage As finMessagingSmsMessage
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If Not finBL.Settings.SmsUseNewInterface Then
    Success = False
    finBL.Error.ErrorBegin("This form is only valid when using the New SMS Messaging Interface.")
  ElseIf finBL.IsRunningFromWeb AndAlso Not finBL.CurrentUser.Permissions.Allow("Cloud.Form.SmsMessage") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this form.")
  End If

  If Success Then
    ' Create Messaging SMS object
    CreateMessagingSmsMessage(MessagingSmsMessage, Nothing)

    ' Form Initialisation Info
    If Success Then
      FormInitialisationInfo = New FormInitialisationInfo()
      With FormInitialisationInfo
        ' Record
        .ParentSourceLogPk = mParentSourceLogPk
        If mParentSourceLogPk = 0 Then
          .SourceTypeText = finBL.Enums.isefinMessagingSourceType_ToString(finBL.Enums.isefinMessagingSourceType_FromString(mType))
          .SourceId = mRecordId
          .PhoneNumber = mPhoneNumber

          ' 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 MessagingSmsMessage
              .SourceTypeText = mType
              .SourceId = mRecordId
              .SetRecipientDetails(Nothing)
            End With
            .SourceDescription = MessagingSmsMessage.RecipientName
          End If
        Else
          ' Set from Log being replied to in CreateMessagingSmsMessage
          .SourceTypeText = MessagingSmsMessage.SourceTypeText
          .SourceId = MessagingSmsMessage.SourceId
          .PhoneNumber = MessagingSmsMessage.RecipientPhoneNumber
        End If

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

        ' Lists
        For Each Branch In finBL.Branches
          If Branch.Active Then
            .Branches.Add(New BranchInfo(finBL, Branch))
          End If
        Next
        .SourceTypesList = MessagingSmsMessage.GetSourceTypeList().ToCsvString()

        ' Configuration
        .AddOnCostCentre = finBL.Settings.AddOns.CostCentre
        .AllowChange = mAllowChange
        .FormHeading = ScriptInfo.ScriptCaption
        If Len(.FormHeading) = 0 Then .FormHeading = "SMS 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 Phone Numbers, Service details and other details.
''' &lt;/summary&gt;
Private Function GetPhoneNumbers(ByRef returnValue As String) As Boolean

  Dim MessagingSmsMessage As finMessagingSmsMessage
  Dim PhoneNumbers As finMessagingContacts
  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 Messaging SMS object
  If Success Then
    CreateMessagingSmsMessage(MessagingSmsMessage, Nothing)
    With MessagingSmsMessage
      .SourceTypeText = SourceTypeText
      .SourceId = SourceId
      .BranchReset()

      PhoneNumbers = .GetSourcePhoneNumbers(
                        mIncludeGuarantors,
                        mIncludeOtherRoles,
                        mIncludeEmployees,
                        mIncludeManager,
                        mIncludeDealer,
                        mIncludeBroker,
                        mIncludeInsurer)
    End With

    obj = New With {
      .BranchId = MessagingSmsMessage.BranchId,
      .PhoneNumbers = PhoneNumbers.ToJsonObject(),
      .Tags = MessagingSmsMessage.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;
'''  Get Phone Numbers and Service details.
''' &lt;/summary&gt;
Private Function GetSmsInfo(parametersJson As String,
                            ByRef returnValue As String) As Boolean

  Dim MessagingSmsMessage As finMessagingSmsMessage
  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 Messaging SMS object
  If Success Then
    Success = CreateMessagingSmsMessage(MessagingSmsMessage, WizardFinishParameters)
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New SmsInfo(MessagingSmsMessage), 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 MessagingSmsMessage As finMessagingSmsMessage
  Dim obj As Object
  Dim PageId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Parse Parameters
  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 Messaging SMS object
      Success = CreateMessagingSmsMessage(MessagingSmsMessage, WizardFinishParameters)

      ' Get Fee Accounts
      GetAccountsCodeDescriptionList(MessagingSmsMessage.SourceType, MessagingSmsMessage.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 MessagingSmsMessage
        If .SourceType = isefinMessagingSourceType.Account Then
          If FeeAccounts.Count = 1 Then .FeeAccountId = FeeAccounts(0).Code
          .FeeCalculate()
        End If
      End With

      ' Validate
      If Success Then
        With MessagingSmsMessage.SmsInformation
          If Len(MessagingSmsMessage.RecipientPhoneNumberFormatted) = 0 Then
            FailedMessage = "Invalid Phone Number."
            FailedControlId = "cboPhoneNumber"
          ElseIf .MessageCharactersOverLimit &gt; 0 Then
            Select Case .MessageCharactersOverLimit
              Case 1
                FailedMessage = "SMS message exceeds the maximum length by 1 character."
              Case Else
                FailedMessage = String.Format("SMS message exceeds the maximum length by {0} characters.", .MessageCharactersOverLimit)
            End Select
            FailedControlId = "txtMessage"
          End If
        End With
      End If

      ' Get Preview
      If Success Then
        Html = finBL.Utilities.GetHtmlFromSummaryTables(MessagingSmsMessage.SmsInformation.GetMessagePreviewSummaryTables(), "", False, "", ScriptInfo.Target)

        Data = New With {
                    .HtmlSummary = Html,
                    .PhoneNumber = MessagingSmsMessage.RecipientPhoneNumberFormatted,
                    .FeeChargingEnabled = MessagingSmsMessage.FeeChargingEnabled,
                    .FeeAllowChange = MessagingSmsMessage.FeeAllowChange,
                    .FeeCharge = MessagingSmsMessage.FeeCharge,
                    .Fee = MessagingSmsMessage.FeeValue,
                    .FeeAccountId = MessagingSmsMessage.FeeAccountId,
                    .FeeAccountReadOnly = FeeAccountReadOnly,
                    .FeeAccounts = FeeAccounts.ToJsonObject(False)
                  }
      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 MessagingSmsMessage As finMessagingSmsMessage
  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 Messaging SMS object
  If Success Then
    Success = CreateMessagingSmsMessage(MessagingSmsMessage, WizardFinishParameters)
  End If

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

  ' Finalise
  If Success Then
    Data = New With {
                .FeeChargingEnabled = MessagingSmsMessage.FeeChargingEnabled AndAlso Account.Status = isefinAccountStatus.Open,
                .FeeAllowChange = MessagingSmsMessage.FeeAllowChange,
                .FeeCharge = MessagingSmsMessage.FeeCharge,
                .Fee = MessagingSmsMessage.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 PhoneNumber As String

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

  ' Lists
  Public Branches As New List(Of BranchInfo)
  Public SourceTypesList As String

  ' Configuration
  Public AddOnCostCentre As Boolean
  Public AllowChange 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 ServiceId As String
  Public PhoneNumber As String
  Public Message 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



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

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

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

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

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

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

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

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

  End Sub

End Class



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

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

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

    With Me
      .ServiceId = serviceId
      .Name = name
      .CostCentreId = costCentreId
      .CostCentreDescription = CostCentreDescription
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  SMS information.
''' &lt;/summary&gt;
Public Class SmsInfo

  Public MaximumLength As Integer
  Public MessageCharactersOverLimit As Integer
  Public MessageCharactersRemaining As Integer
  Public MessageCharactersRemainingInMessagePart As Integer
  Public MessageLength As Integer
  Public MessageParts As Integer
  Public InformationMessage As String
  Public InformationMessageEditing As String
  Public WarningMessage As String

  Public Sub New(messagingSmsMessage As finMessagingSmsMessage)

    With messagingSmsMessage.SmsInformation
      Me.MaximumLength = .MaximumLength
      Me.MessageCharactersOverLimit = .MessageCharactersOverLimit
      Me.MessageCharactersRemaining = .MessageCharactersRemaining
      Me.MessageCharactersRemainingInMessagePart = .MessageCharactersRemainingInMessagePart
      Me.MessageLength = .MessageLength
      Me.MessageParts = .MessageParts

      ' Information and Warning Messages
      Me.InformationMessage = .GetInformationMessage(False, True)
      Me.InformationMessageEditing = .GetInformationMessage(True, True)
      Me.WarningMessage = .GetWarningMessage(True)
    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 forms "SmsMessage" and "SmsMessageNew".

LIMITATIONS: This widget only handles the New SMS Messaging Inteface.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
#divMessageInfo_Text {
  display:inline-block;
}
&lt;/style&gt;

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

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Enter SMS details."&gt;SMS&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="txtRecipientName"&gt;Recipient:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtRecipientName" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtPhoneNumber"&gt;Phone:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtPhoneNumber" /&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="cboPhoneNumber"&gt;Phone:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboPhoneNumber" /&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="lblBranch"&gt;Select the Branch to allocate costs to&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboBranch"&gt;Branch:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboBranch" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

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

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

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

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


    &lt;!-- 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 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 style="flex-grow:0; margin-left:8px"&gt;
        &lt;div id="divMessagePreviewInfo" class="is-info-text info small"&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;
var mRecord_SmsInfo;

// Global Collections
var mBranches;

// Controls
var C = {
  // General
  lblRecipient: null,
  cboSourceType: null,
  txtRecipientName: null,
  txtPhoneNumber: null,
  cboAccount: null,
  cboAccountApp: null,
  cboClient: null,
  cboExternalParty: null,
  cboUser: null,
  cboPhoneNumber: null,

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

  lblBranch: null,
  cboBranch: null,
  divCostCentreInformation: null,

  lblService: null,
  cboService: null,

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

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

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

  lblMessagePreview: null,
  wbMessagePreview: null,
  divMessagePreviewInfo: 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.txtPhoneNumber = widget.UI.TextBox("txtPhoneNumber", {
    allowBlank: false,
    dataType: "phone",
    maxLength: 20,
  });
  C.txtRecipientName = widget.UI.TextBox("txtRecipientName", {
    allowBlank: false,
    maxLength: 50,
  });
  C.cboAccount = widget.UI.DBCombo("cboAccount", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

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

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

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

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

    onChange: cboPhoneNumber_Refresh,
  });
  C.cboPhoneNumber = widget.UI.DBCombo("cboPhoneNumber", {
    allowBlank: false,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

  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.lblBranch = widget.UI.Label("lblBranch", {});
  C.cboBranch = widget.UI.DBCombo("cboBranch", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

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

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

    onChange: cboService_Change,
  });

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

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

  //   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.wbMessagePreview = widget.UI.PreviewPane("wbMessagePreview", {});
  C.divMessagePreviewInfo = $("#divMessagePreviewInfo");

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

  // 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_SmsInfo = 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.txtPhoneNumber.Text(mRecord.PhoneNumber);
    C.cboPhoneNumber.Text(mRecord.PhoneNumber);

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

    // 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.txtPhoneNumber.VisibleRow(false);
  C.txtRecipientName.VisibleRow(false);
  C.cboAccount.VisibleRow(false);
  C.cboAccountApp.VisibleRow(false);
  C.cboClient.VisibleRow(false);
  C.cboExternalParty.VisibleRow(false);
  C.cboUser.VisibleRow(false);
  C.cboPhoneNumber.VisibleRow(false);

  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.cboPhoneNumber.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.cboPhoneNumber.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.cboPhoneNumber.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.cboPhoneNumber.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.cboPhoneNumber.VisibleRow(true);
      break;

    default:
      C.txtPhoneNumber.VisibleRow(true);
      C.txtRecipientName.VisibleRow(true);
      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(),
    phoneNumber: C.cboPhoneNumber.Text(),
    branchId: C.cboBranch.Text(),
    serviceId: C.cboService.Text(),
    message: C.txtMessage.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.phoneNumber = C.txtPhoneNumber.Text();
      params.recipientName = C.txtRecipientName.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.cboBranch.RefreshFromStandardRange("Branches");
    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);
    }

    if (!mRecord.AddOnCostCentre) {
      C.lblBranch.VisibleRow(false);
      C.cboBranch.VisibleRow(false);
    }

    // Refresh Phone Numbers
    cboPhoneNumber_Refresh();

    txtMessage_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 SMS";
      var message = "&lt;p&gt;Are you sure you want to send this SMS Message?&lt;/p&gt;";

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

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

  // Get Parameters
  var params = CreateFinishParameters();

  // Finish
  widget.GetString("Finish", params,
    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":
        if (mRecord_SmsInfo) C.divMessagePreviewInfo.html(mRecord_SmsInfo.InformationMessage);
        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.txtRecipientName.WidthResizeFromParent();
      C.txtPhoneNumber.WidthResizeFromParent();
      C.cboAccount.WidthResizeFromParent();
      C.cboAccountApp.WidthResizeFromParent();
      C.cboClient.WidthResizeFromParent();
      C.cboExternalParty.WidthResizeFromParent();
      C.cboUser.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();
}

// ==============
// cboPhoneNumber
// ==============
function cboPhoneNumber_Refresh(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

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

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

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

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

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

      C.cboPhoneNumber.RefreshFromCollection(data.PhoneNumbers, "Value", "SourceNameAndDescription", "Source,Name,Role,Description,Value");
      if (data.BranchId) C.cboBranch.Text(data.BranchId);
      cboBranch_Change();

      // Select first Phone Number
      if (!C.cboPhoneNumber.Text()) C.cboPhoneNumber.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.txtMessage.TagsListDefine(tagsList);
    },

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

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

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

  // Update Service
  cboService_Change();
}

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

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


  // Update Message
  txtMessage_Change();
}

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

  // Refresh SMS Information
  txtMessage_RefreshInfo();
}

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

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

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

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

      // Refresh SMS Information
      divMessageInfo_Refresh();
    },

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

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

// ===============
// 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 feeVisible = true;

  // Preview
  C.wbMessagePreview.SetContent(mRecord_Confirm.HtmlSummary, false);
  C.lblMessagePreview.Html("The following Message will be sent to &lt;span style='background-color:yellow; padding:2px'&gt;" + mRecord_Confirm.PhoneNumber) + "&lt;/span&gt;";

  // 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":
    case "User":
      feeVisible = true;
      C.cboFeeAccount.RefreshFromStandardRange("Accounts", "Status = 1");
      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);
      }
    );
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>3oRou3kqAUuwGXI5pBa9xw</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption>SMS Message</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>800</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>SMS</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>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,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="PhoneNumber" type="Text">
            <BlankTip />
            <Caption>PhoneNumber</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="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>True</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>Include Phone Numbers</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>