<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-19T02:42:48.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2021-01-11T03:29:03.5470000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2024-09-19T02:42:28.9330000</UpdatedUtcDate>
    <ScriptId>DC</ScriptId>
    <Description>Document Create</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_DocumentCreate
Option Explicit On
Option Strict On

' #################################################################
' Document Create wizard
'
' Version: 1.11 (19/09/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.03  08/09/2021  ISS      J027352   GenerateMessage issue
'          20/09/2021  ISS      J027401   DocumentId ignored
'          30/09/2021  ISS      J027423   HTML Editor for Emails
'          16/11/2021  ISS      J027776   Notes updated for email limitations
'    1.04  09/02/2022  ISS      J028121   Document list now grouped by Category
'          15/02/2022  ISS      J027775   Now respects Web, Document can be published flag
'          25/02/2022  ISS      J028331   Documents with no Category now group under "(none)"
'          22/03/2022  ISS      J028340   Tooltips updated
'          25/05/2022  ISS      J028579   SMS Phone Number list blank for Account Applications
'          07/06/2022  ISS      J028452   User Defined fields not retaining indexes
'    1.05  24/08/2022  ISS      J028630   Add "Account.Logs.UpdateDocumentFee" Permission
'    1.06  13/09/2022  ISS      J029490   Update logic where Fee cannot be charged
'    1.07  13/10/2022  ISS      J029522   Bank Account Enquiry support additional Parameters
'          09/11/2022  ISS      J029964   Branch is now defaulted when HTML Widget is initialised
'    1.08  29/01/2024  ISS      J032797   Document Log's Print Status now set to 'Printed' if downloaded
'    1.09  14/06/2024  ISS      J033662   When running under desktop, now ignores Document setting restricting whether Publish is available
'    1.10  25/06/2024  ISS      J033766   Added widget parameters to send to GetContactDetails()
'          10/07/2024  ISS      J033382   Better handling of Email Documents configured to not 'Print Document even if Emailed'
'          22/08/2024  ISS      J034133   Email options were hidden if using Exchange instead of SMTP
'    1.11  19/09/2024  ISS      J028029   Enhancements to allow Email Account Document based on Document options
' #################################################################

' Constants
Private Const FORM_KEY As String = "DocumentCreate"

' Common Parameters
Private mAccountAppApplicantPk As Integer
Private mDocumentId As String
Private mFileType As iseDocumentFileType
Private mFilterByFileType 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 mOnlyIncludeDocumentsFlaggedForCloud As Boolean
Private mRecordId As String
Private mReplyLogPk As Integer
Private mRunningFromDesktop As Boolean
Private mServiceLogPk As Integer
Private mServiceLogBranchPk As Integer
Private mTarget As isefinCreateDocumentTarget
Private mWorkflowPk As Integer
Private mWorkflowItemPk As Integer

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

' Other
Private mHostingContext As isefinHtmlWidgetHostingContext


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

  Dim [Type] As String

  ' Assume Success
  Main = True

  ' Initialise
  mHostingContext = hostingContext

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

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

  ' Get Common Parameters
  With mCombinedParameters
    mAccountAppApplicantPk = .GetInteger("AccountAppApplicantPk")
    mRunningFromDesktop = .GetBoolean("_runningfromdesktop") ' System parameter set when running from desktop
    mDocumentId = .GetString("DocumentId")
    mFileType = DirectCast(.GetEnum("FileType", GetType(iseDocumentFileType)), iseDocumentFileType)
    mFilterByFileType = .GetBoolean("FilterByFileType")
    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)    
    mOnlyIncludeDocumentsFlaggedForCloud = .GetBoolean("OnlyIncludeDocumentsFlaggedForCloud")
    mRecordId = .GetString("Id")
    mReplyLogPk = .GetInteger("ReplyLogPk")
    mServiceLogPk = .GetInteger("ServiceLogPk")
    mServiceLogBranchPk = .GetInteger("ServiceLogBranchPk")
    Type = .GetString("Type")
    mWorkflowPk = .GetInteger("WorkflowPk")
    mWorkflowItemPk = .GetInteger("WorkflowItemPk")
  End With

  ' Determine Target
  Select Case ucase(type)
    Case "CLIENT_ACCOUNTAPP"
      mTarget = isefinCreateDocumentTarget.AccountApp
    Case Else
      mTarget = DirectCast(mCombinedParameters.GetEnum("Type", GetType(isefinCreateDocumentTarget)), isefinCreateDocumentTarget)
  End Select

  ' 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 "GenerateMessage"
      ' Generate Message
      Main = GenerateMessage(parametersJson, returnValue)

    Case "GetMessagePreview"
      ' Get Message Preview
      Main = GetMessagePreview(parametersJson, returnValue)

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

    Case "SetLogPrinted"
      ' Set the Log as having been Printed
      Main = SetLogPrinted(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 finDocumentCreate object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateDocumentCreate(ByRef documentCreate As finDocumentCreate,
                                      parameters As WizardFinishParameters) As Boolean
                               
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  documentCreate = finBL.CreateDocumentCreate()
  Select Case mTarget
    Case isefinCreateDocumentTarget.Account
      Success = documentCreate.AccountLoad(mRecordId)

    Case isefinCreateDocumentTarget.AccountApp
      Success = documentCreate.AccountAppLoad(mRecordId)

    Case isefinCreateDocumentTarget.Client
      Success = documentCreate.ClientLoad(mRecordId)

    Case isefinCreateDocumentTarget.User
      Success = documentCreate.UserLoad(mRecordId)

    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unhandled Target '{0}'.", mTarget)
  End Select

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

        ' Other (no point unless Document has been set)
        If Success Then
          ' General
          If parameters.ActionTzDate IsNot Nothing Then
            .ActionTimeZoneId = parameters.ActionTimeZoneId
            .ActionTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(parameters.ActionTzDate)
          End If
          .EmailDocument = parameters.EmailDocument
          If .Document.AllowExternalParty &lt;&gt; isefinDocumentAllowExternalParty.None Then
            .ExternalPartyId = parameters.ExternalPartyId
          End If
          .LogSeverityId = parameters.LogSeverityId
          .Notes = parameters.Notes
          .ParentLogPk = mReplyLogPk
          If parameters.PublishOnTzDate IsNot Nothing Then
            .PublishOnTimeZoneId = parameters.PublishOnTimeZoneId
            .PublishOnTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(parameters.PublishOnTzDate)
          End If
          
          ' Fee
          Select Case mTarget
            Case isefinCreateDocumentTarget.Account
              If documentCreate.Account.Status = isefinAccountStatus.Open Then
                .Fee = parameters.Fee
              End If  
          End Select    
  
          ' Parameters
          .ParametersUpdateFromHtmlWidgetJsonString(parameters.ParametersJson)
          
          ' Service Log
          .ServiceLogPk = mServiceLogPk
          .ServiceLogBranchPk = mServiceLogBranchPk

          ' File Type-specific
          Select Case .Document.FileType
            Case iseDocumentFileType.Email
              ' =====
              ' Email
              ' =====
              If parameters.UseDocumentRecipientsList Then
                .UseDocumentRecipientsList = True
                .EmailSubject = parameters.EmailSubject
                .EmailMessage = parameters.EmailMessage
              ElseIf Len(parameters.EmailTo) &lt;&gt; 0 Then
                .UseDocumentRecipientsList = False
                .EmailTo = parameters.EmailTo
                .EmailCc = parameters.EmailCc
                .EmailBcc = parameters.EmailBcc
                .EmailSubject = parameters.EmailSubject
                .EmailMessage = parameters.EmailMessage

                ' Attempt to match a Messaging Contact from the Email
                ' NOTE: This will then determine objects used for tag resolution, e.g., if an Account is being used, the Messaging Contact may be for a particular Client or the Manager User
                .SetMessagingContactFromContactValue(parameters.EmailTo)

                ' Email (may have been supplied by 'GenerateMessage' Script event)
                If Len(parameters.EmailSender) &lt;&gt; 0 Then .EmailSender = parameters.EmailSender
                  If Len(parameters.EmailSenderName) &lt;&gt; 0 Then .EmailSenderName = parameters.EmailSenderName
              End If

            Case iseDocumentFileType.Sms
              ' ===
              ' SMS
              ' ===
              If Len(parameters.BranchId) &lt;&gt; 0 Then
                .BranchId = parameters.BranchId
              End If              
              If Len(parameters.SmsPhoneNumber) &lt;&gt; 0 Then
                .SmsPhoneNumber = parameters.SmsPhoneNumber
                .SmsMessage = parameters.SmsMessage
                .SmsServciceId = parameters.SmsServiceId
                
                ' Attempt to match a Messaging Contact from the Phone Number
                ' NOTE: This will then determine objects used for tag resolution, e.g., if an Account is being used, the Messaging Contact may be for a particular Client or the Manager User
                .SetMessagingContactFromContactValue(parameters.SmsPhoneNumber)
              End If
          End Select

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish and create Document.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim DocumentCreate As finDocumentCreate
  Dim DocumentShowApplicationShortcutUrl As String
  Dim EmailSent As Boolean
  Dim obj As Object
  Dim PublishError As Boolean
  Dim Success 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 Document Create object
  If Success Then
    Success = CreateDocumentCreate(DocumentCreate, WizardFinishParameters)
  End If

  ' Create Document
  If Success Then
    If DocumentCreate.ExecuteCreateLog(WizardFinishParameters.Publish, PublishError, WarningMessage, EmailSent) Then
      If Not WizardFinishParameters.Publish Then
        ' Not Publishing
      ElseIf PublishError Then
        ' Publish error
        WarningMessage = finBL.Error.Message(True)
      Else
        ' Get an Application Shortcut to show the Published Document
        If mHostingContext = isefinHtmlWidgetHostingContext.WebInternal Then
          ' If Emailed, then only offer to Print if the Document is configured to do this
          If Not EmailSent OrElse DocumentCreate.Document.PrintDocumentEvenIfEmailed Then
            DocumentShowApplicationShortcutUrl = DocumentCreate.GetDocumentShowApplicationShortcutUrl()
          End If
        Else
          ' When Published from within finPOWER Connect, the Document will automatically be displayed upon Publish
        End If
      End If
    Else
      Success = False
    End If
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(WarningMessage, DocumentShowApplicationShortcutUrl, DocumentCreate.LogObjectType, DocumentCreate.Log.Pk), returnValue)
  End If

  Return Success

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 DocumentCreate As finDocumentCreate
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  If Success Then
    ' Create Document Create object
    Success = CreateDocumentCreate(DocumentCreate, Nothing)

    ' Form Initialisation Info
    If Success Then
      FormInitialisationInfo = New FormInitialisationInfo()
      With FormInitialisationInfo
        ' Record
        .RecordCaption = DocumentCreate.RecordCaption
        .RecordCode = DocumentCreate.RecordCode
        .RecordDescription = DocumentCreate.RecordDescription

        ' General
        .DocumentId = mDocumentId

        ' Default Branch - J029964
        .BranchId = DocumentCreate.BranchId
        If Len(.BranchId) = 0 Then .BranchId = finBL.CurrentUserInformation.BranchId
        
        ' Workflow
        If mWorkflowPk &lt;&gt; 0 Then
          .WorkflowDescription = finBL.WorkflowFunctions.GetRecordCodeDescription(mWorkflowPk, .WorkflowId)
          .WorkflowItemPk = mWorkflowItemPk
        End If

        ' Documents List
        .Documents = DocumentCreate.GetDocumentsListAsHtmlWidgetJsonObject(mFilterByFileType, mFileType, mOnlyIncludeDocumentsFlaggedForCloud, mDocumentId, True)

        ' Lists

        ' Global Collections
        For Each Branch In finBL.Branches
          If Branch.Active Then
            .Branches.Add(New BranchInfo(finBL, Branch))
            
            If Len(.BranchId) = 0 Then
              .BranchId = Branch.BranchId
            End If
          End If
        Next
        
        ' Configuration
        .AddOnCostCentre = finBL.Settings.AddOns.CostCentre
        .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
        .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;
'''  Generate Message for Email and SMS Documents.
''' &lt;/summary&gt;
''' &lt;param name="returnValue"&gt;
'''  An HTML String.
''' &lt;/param&gt;
Private Function GenerateMessage(parametersJson As String,
                                 ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim DocumentCreate As finDocumentCreate
  Dim EmailRecipients As ISCodeDescriptionList 
  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 Document Create object
  If Success Then
    Success = CreateDocumentCreate(DocumentCreate, WizardFinishParameters)
  End If

  ' Generate Message
  If Success Then
    Success = DocumentCreate.GenerateMessage()
  End If
  
  ' For Account Email Documents, get a list of possible Email Recipients
  ' NOTE: This in turn allows the 'Document Execute' process to be selected as an alternative
  If Success Then
    EmailRecipients = finBL.CreateCodeDescriptionList()
    
    If DocumentCreate.EmailAccountRecipientDetailsItems IsNot Nothing AndAlso
       DocumentCreate.Document.AllowStandalone Then
      For Each Recipient As finDocumentRecipientDetailsItem In DocumentCreate.EmailAccountRecipientDetailsItems
        If Recipient.EmailDetails.EmailAddresses.Count &lt;&gt; 0 Then
          EmailRecipients.Add(Recipient.EmailDetails.EmailAddresses(0), Recipient.Client.Name)
        End If
      Next
    End If
  End If

  ' Serialise
  If Success Then
    Data = New With {
      .Subject = DocumentCreate.EmailSubject,
      .Message = If(DocumentCreate.Document.FileType = iseDocumentFileType.Sms, DocumentCreate.SmsMessage, DocumentCreate.EmailMessage),
      .EmailTo = DocumentCreate.EmailTo,
      .EmailCc = DocumentCreate.EmailCc,
      .EmailBcc = DocumentCreate.EmailBcc,
      .EmailRecipients = EmailRecipients.ToJsonObject(),
      .EmailSender = DocumentCreate.EmailSender,
      .EmailSenderName = DocumentCreate.EmailSenderName,
      .SmsPhoneNumber = DocumentCreate.SmsPhoneNumber
    }

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Message Preview for Email and SMS Documents.
''' &lt;/summary&gt;
''' &lt;param name="returnValue"&gt;
'''  An HTML String.
''' &lt;/param&gt;
Private Function GetMessagePreview(parametersJson As String,
                                   ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim DocumentCreate As finDocumentCreate
  Dim Html As String
  Dim obj As Object
  Dim Success As Boolean
  Dim Warnings As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Document Create object
  If Success Then
    Success = CreateDocumentCreate(DocumentCreate, WizardFinishParameters)
  End If

  ' Get Message Preview and Warnings
  If Success Then
    Html = DocumentCreate.GetMessagePreviewHtml(Warnings)
  Else
    Html = finBL.GetHtmlErrorMessage(finBL.Error.Message(True))
  End If

  ' Serialise
  If Success Then
    Data = New With {
      .Html = html,
      .Warnings = Warnings
    }

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

  Return Success

End Function

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

  Dim DocumentCreate As finDocumentCreate
  Dim obj As Object
  Dim SmsInformation As ISSmsInformation
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Document Create object
  If Success Then
    Success = CreateDocumentCreate(DocumentCreate, WizardFinishParameters)
  End If

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Set a Log as having been Printed.
''' &lt;/summary&gt;
Private Function SetLogPrinted(ByRef returnValue As String) As Boolean

  Dim Log As i_finLog
  Dim LogPk As Integer
  Dim LogObjectType As isefinLogObjectType
  Dim Success As Boolean
  

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    LogPk = .GetInteger("LogPk")
    LogObjectType = DirectCast(.GetEnum("LogObjectType", GetType(isefinLogObjectType)), isefinLogObjectType)
  End With

  ' Update Log's Print Status
  If Success Then
    ' Load Log
    If finBL.LogUtilities.LoadLog(LogObjectType, LogPk, Log) Then
      ' Update and Save Log
      With Log
        .PrintStatus = isefinLogPrintStatus.Printed 
        Success = .Save()
      End With
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim ConfirmList As New List(Of String)
  Dim Contacts As Object
  Dim DocumentCreate As finDocumentCreate
  Dim Data As Object
  Dim DefaultContact As String
  Dim ExternalPartiesFilter As String
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim obj As Object
  Dim PageId As String
  Dim Success As Boolean
  Dim TagsList As Object
  Dim TagsListEmailSubject As Object
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

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

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

    ' External Parties Filter?
    If success Then
      ExternalPartiesFilter = finBL.ExternalParties.GetDataViewFilter_Categories(DocumentCreate.Document.ExternalPartyCategories)
    End If

    ' Get File Type-specific properties
    If Success Then
      Select Case DocumentCreate.Document.FileType
        Case iseDocumentFileType.Email
          ' =====
          ' Email
          ' =====
          Contacts = DocumentCreate.GetContactDetails(
                                      ,
                                      mIncludeGuarantors,
                                      mIncludeEmployees,
                                      mIncludeManager,
                                      mIncludeDealer,
                                      mIncludeBroker,
                                      mIncludeInsurer,
                                      mIncludeOtherRoles).ToJsonObject()
          DefaultContact = DocumentCreate.EmailTo

          ' NOTE: The Tags list for the Email Subject is a slightly cut down list
          TagsList = DocumentCreate.GetSourceTagList(False).ToCodeDescriptionList().ToJsonObject()
          'TagsListEmailSubject = DocumentCreate.GetSourceTagList(True).ToJsonObject()

        Case iseDocumentFileType.Sms
          ' ===
          ' SMS
          ' ===
          Contacts = DocumentCreate.GetContactDetails(
                                      ,
                                      mIncludeGuarantors,
                                      mIncludeEmployees,
                                      mIncludeManager,
                                      mIncludeDealer,
                                      mIncludeBroker,
                                      mIncludeInsurer,
                                      mIncludeOtherRoles).ToJsonObject()
          DefaultContact = DocumentCreate.SmsPhoneNumber

          TagsList = DocumentCreate.GetSourceTagList(False).ToCodeDescriptionList().ToJsonObject()
      End Select
    End If
  End If

  ' Validate
  If Success Then
    Select Case PageId
      Case "General"
        Data = New With {
          .Parameters = DocumentCreate.ParametersAsWsParameters(),
          .AllowModify = DocumentCreate.Document.TemplateAllowModify,
          .AllowEmailDocument = DocumentCreate.Document.EmailDocument &lt;&gt; iseYesNoPrompt.No AndAlso finBL.SettingsUser.EmailIsUnattendedAvailable(),
          .AllowExternalParty = finBL.Settings.AddOns.ExternalParty AndAlso DocumentCreate.Document.AllowExternalParty &lt;&gt; isefinDocumentAllowExternalParty.None,
          .ExternalPartiesFilter = ExternalPartiesFilter,
          .ExternalPartyMandatory = DocumentCreate.Document.AllowExternalParty = isefinDocumentAllowExternalParty.Mandatory,
          .EmailDocumentDefault = DocumentCreate.Document.EmailDocument = iseYesNoPrompt.Yes,
          .ChargeFee = DocumentCreate.Document.ChargeFee,
          .CanChargeFee = DocumentCreate.Account IsNot Nothing AndAlso DocumentCreate.Account.Status = isefinAccountStatus.Open,
          .CanUpdateFee = DocumentCreate.Account IsNot Nothing AndAlso finBL.CurrentUser.Permissions.Allow("Account.Logs.UpdateDocumentFee"),
          .DefaultBranchId = DocumentCreate.BranchId,
          .DefaultContact = DefaultContact,
          .DefaultFee = DocumentCreate.Document.Fee,
          .Contacts = Contacts,
          .EmailHtml = DocumentCreate.Document.EmailHtml,
          .EmailSubject = DocumentCreate.EmailSubject,
          .EmailMessage = DocumentCreate.EmailMessage,
          .SmsMessage = DocumentCreate.SmsMessage,
          .Tags = TagsList,
          .TagsEmailSubject = TagsListEmailSubject,
          .CanPublish = mRunningFromDesktop OrElse (DocumentCreate.Document.SupportsUnattendedPublish AndAlso DocumentCreate.Document.CloudConnectAllowPublish)
        }
    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;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

  ' Record
  Public RecordCaption As String
  Public RecordCode As String
  Public RecordDescription As String

  ' General
  Public BranchId As String
  Public DocumentId As String

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

  ' Lists
  Public Documents As Object

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

  ' Configuration
  Public AddOnCostCentre As Boolean
  Public PromptOnCommit As Boolean
  Public TestMode As Boolean

End Class



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

  Public DocumentShowApplicationShortcutUrl As String
  Public LogObjectType As isefinLogObjectType  
  Public LogPk As Integer
  Public WarningMessage As String

  Public Sub New(warningMessage As String,
                 documentShowApplicationShortcutUrl As String,
                 logObjectType As isefinLogObjectType,
                 logPk As Integer)

    With Me
      .WarningMessage = warningMessage
      .DocumentShowApplicationShortcutUrl = DocumentShowApplicationShortcutUrl
      .LogObjectType = logObjectType
      .LogPk = logPk
    End With

  End Sub

End Class



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

  ' Wizard Validation
  Public PageId As String

  ' Workflow
  Public WorkflowLinkCurrentItem As Boolean

  ' Document
  Public DocumentId As String
  Public Publish As Boolean

  ' General
  Public ParametersJson As String

  ' Email-specific
  Public UseDocumentRecipientsList As Boolean
  Public EmailTo As String
  Public EmailCc As String
  Public EmailBcc As String
  Public EmailSubject As String
  Public EmailMessage As String

  ' Email (may have been supplied by 'GenerateMessage' Script event)
  Public EmailSender As String
  Public EmailSenderName As String

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

  ' Notes
  Public ActionTimeZoneId As String
  Public ActionTzDate As Date?
  Public EmailDocument As Boolean
  Public ExternalPartyId As String
  Public Fee As Decimal
  Public LogSeverityId As String
  Public Notes As String
  Public PublishOnTimeZoneId As String
  Public PublishOnTzDate As Date?

End Class



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

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

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

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

  End Sub

End Class



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

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

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

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

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

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

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

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

  End Sub

End Class



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

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

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

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

  End Sub

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

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

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

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

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Select the Document to create"&gt;Document&lt;/li&gt;
        &lt;li tabId="Parameters" tooltipText=""&gt;Parameters&lt;/li&gt;
        &lt;li tabId="Email" tooltipText=""&gt;Email&lt;/li&gt;
        &lt;li tabId="Sms" tooltipText=""&gt;SMS&lt;/li&gt;
        &lt;li tabId="Preview" tooltipText="Review the message that will be sent."&gt;Preview&lt;/li&gt;
        &lt;li tabId="Notes" tooltipText=""&gt;Notes&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&gt;Recipient details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboRecord"&gt;Type:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboRecord" /&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&gt;Select a Document&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

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


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


    &lt;!-- Email --&gt;
    &lt;div id="pageEmail" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:0"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;
          
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblUseDocumentRecipientsList"&gt;Send an individual Email to each of the following Recipients?&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkEmailUseDocumentRecipientsList" type="checkbox"/&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr id="trUseDocumentRecipientsListRecipients"&gt;
            &lt;th colspan="2"&gt;&lt;div id="divUseDocumentRecipientsListRecipients" class="is-info-text info"&gt;&lt;/div&gt;&lt;/th&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblEmail"&gt;Email Recipients&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboEmailTo"&gt;To:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboEmailTo" autocomplete="off"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtEmailCc"&gt;CC:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtEmailCc" autocomplete="off"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtEmailBcc"&gt;BCC:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtEmailBcc" autocomplete="off"/&gt;&lt;/td&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;/table&gt;
      &lt;/div&gt;

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

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

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

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblRecipient"&gt;SMS Recipient&lt;/label&gt;&lt;/th&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="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;!-- Preview --&gt;
    &lt;div id="pagePreview" style="display:flex; flex-direction:column"&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"&gt;
        &lt;div id="wbPreview" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Notes --&gt;
    &lt;div id="pageNotes"&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(s) that will be created to record this Document&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtNotes"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateLogActionDate"&gt;Action:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateLogActionDate"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateLogPublishOnDate"&gt;To Send:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateLogPublishOnDate"&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 for sending this Document&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&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="lblExternalParty"&gt;Link to an External Party&lt;/label&gt;&lt;/th&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 colspan="2"&gt;&lt;label id="lblDocumentPublishDetails"&gt;Publish details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkEmailDocument" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;
            &lt;div id="divPublishDetails" class="is-info-text info small"&gt;&lt;/div&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&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="cmdSave" class="is-button ok"&gt;Save&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Publish&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;

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

// Global Collections
var mBranches;

// Controls
var C = {
  //   General
  cboRecord: null,

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

  gridDocuments: null,

  //   Parameters
  phParameters: null,

  //   Email
  lblUseDocumentRecipientsList: null,
  chkEmailUseDocumentRecipientsList: null,
  trUseDocumentRecipientsListRecipients: null,
  divUseDocumentRecipientsListRecipients: null,
  
  lblEmail: null,
  cboEmailTo: null,
  txtEmailCc: null,
  txtEmailBcc: null,

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

  //   SMS
  cboPhoneNumber: null,

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

  lblService: null,
  cboService: null,

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

  //   Preview
  divPreviewWarnings: null,
  wbPreview: null,

  //   Notes
  lblEmailDocument: null,
  chkEmailDocument: null,

  lblLog: null,
  txtNotes: null,
  dateLogActionDate: null,
  dateLogPublishOnDate: null,
  cboLogSeverity: null,

  lblFee: null,
  numFee: null,

  lblExternalParty: null,
  cboExternalParty: null,

  lblDocumentPublishDetails: null,
  divPublishDetails: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mDocument;
var mEmailSender;
var mEmailSenderName;
var mLastPreviewJson;
var mTimer;

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

  // Controls
  //   General
  C.cboRecord = widget.UI.DBCombo("cboRecord", {
    allowBlank: true,
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

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

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

  //   Email
  C.lblUseDocumentRecipientsList = widget.UI.Label("lblUseDocumentRecipientsList", {
    tooltipText: "This will create separate Logs and emails for each of the listed Account Clients.",
  });
  C.chkEmailUseDocumentRecipientsList = widget.UI.CheckBox("chkEmailUseDocumentRecipientsList", {
    caption: "Send individually to each of the following Account Clients?",
    
    onChange: chkEmailUseDocumentRecipientsList_Change,
  });
  C.trUseDocumentRecipientsListRecipients = $("#trUseDocumentRecipientsListRecipients");
  C.divUseDocumentRecipientsListRecipients = $("#divUseDocumentRecipientsListRecipients");
  
  C.lblEmail = widget.UI.Label("lblEmail", {
    tooltipText: "Separate multiple email addresses with ',' or ';'.",
  });
  C.cboEmailTo = widget.UI.DBCombo("cboEmailTo", {
    allowBlank: false,
    limitToList: false,
    maxLength: 0,
    showDescription: false
  });
  C.txtEmailCc = widget.UI.TextBox("txtEmailCc", {});
  C.txtEmailBcc = widget.UI.TextBox("txtEmailBcc", {});

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

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

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

  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,
    limitToList: true,
    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");

  //   Preview
  C.divPreviewWarnings = $("#divPreviewWarnings");
  C.wbPreview = widget.UI.PreviewPane("wbPreview", {});

  //   Notes
  C.lblLog = widget.UI.Label("lblLog", {
    tooltipText: "The 'To Send' date is ignored if you opt to publish now rather than saving the Log for later publication.",
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 8,
  });
  C.dateLogActionDate = widget.UI.DateTimeZone("dateLogActionDate", {
    timeZoneVisible: true,
  });
  C.dateLogPublishOnDate = widget.UI.DateTimeZone("dateLogPublishOnDate", {
    timeZoneVisible: true,
  });
  C.cboLogSeverity = widget.UI.DBCombo("cboLogSeverity", {
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });

  C.lblFee = widget.UI.Label("lblFee", {});
  C.numFee = widget.UI.NumberBox("numFee", {
    decimals: -1,
    minValue: 0,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: numFee_Change,
  });

  C.lblExternalParty = widget.UI.Label("lblExternalParty", {});
  C.cboExternalParty = widget.UI.DBCombo("cboExternalParty", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

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

    onChange: chkEmailDocument_Change,
  });
  C.divPublishDetails = $("#divPublishDetails");

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

    onInitialiseRow: gridDocuments_InitialiseRow,
    onRowDrilldown: gridDocuments_RowDrilldown,
  });

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

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

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

  // Reset Form
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

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

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

      // Global Collections
      mBranches = mRecord.Branches;

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

      // Load Fields
      Fields_Load();


      // Select Document and advance, e.g., when sending an Email or SMS Document from a Bank Account Enquiry
      if (mRecord &amp;&amp; mRecord.DocumentId) {
        for (var i = 0; i &lt; mRecord_Documents.length; i++) {
          var item = mRecord_Documents[i];
          if (item.DocumentId.toUpperCase() == mRecord.DocumentId.toUpperCase()) {
            C.gridDocuments.ActiveDataRowListIndex(i);
            tabWizard_Move(1);
            break;
          }
        }
      }
    },

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboRecord.Caption(mRecord.RecordCaption + ":");
    C.cboRecord.RefreshUnbound(mRecord.RecordCode, mRecord.RecordDescription);

    C.cboBranch.Text(mRecord.BranchId);

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

    gridDocuments_Refresh();

    // Parameters

    // Email

    // SMS

    // Preview

    // Notes
  }

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

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

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

    documentId: mDocument.DocumentId,

    notes: C.txtNotes.Text(),
    actionTimeZoneId: C.dateLogActionDate.TimeZoneId(),
    actionTzDate: C.dateLogActionDate.Value(),
    publishOnTimeZoneId: C.dateLogPublishOnDate.TimeZoneId(),
    publishOnTzDate: C.dateLogPublishOnDate.Value(),
    logSeverityId: C.cboLogSeverity.Text(),
    fee: C.numFee.Value(),
    externalPartyId: C.cboExternalParty.Text(),
    emailDocument: C.chkEmailDocument.Value(),
  }

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

  // File Type-specific
  switch(mDocument.FileType) {
    case "Email":
      params.useDocumentRecipientsList = C.chkEmailUseDocumentRecipientsList.Value();
      params.emailTo = C.cboEmailTo.Text();
      params.emailCc = C.txtEmailCc.Text();
      params.emailBcc = C.txtEmailBcc.Text();
      params.emailSubject = C.txtEmailSubject.Text();
      params.emailMessage = C.heEmailMessage.Text();

      // Special (may have been supplied by 'GenerateMessage' Script event
      if (mEmailSender) params.emailSender = mEmailSender;
      if (mEmailSenderName) params.emailSenderName = mEmailSenderName;
      break;

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

  return params;
}

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

  // Information Lists

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

  // Controls
  if (mRecord) {
    chkEmailUseDocumentRecipientsList_Change(null, null);
    
    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);
    }
  }

  // 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 (Publish)
      Form_ExecuteAction_Finish(true);
      break;

    case "SAVE":
      // Finish (Save)
      Form_ExecuteAction_Finish(false);
      break;

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

function Form_ExecuteAction_Finish(publish) {
  // Validate
  tabWizard_Validate(function() {
    if (mRecord.PromptOnCommit || C.numFee.Value() != 0 || (publish &amp;&amp; C.dateLogPublishOnDate.Value())) {
      // Confirm
      var heading = "Create Document";
      var message = "&lt;p&gt;Are you sure you want to create this Document Log?&lt;/p&gt;";
      if (publish &amp;&amp; C.dateLogPublishOnDate.Value()) {
        message += "&lt;p&gt;Since you are publishing this Log immediately, the 'To Send' date of &lt;b&gt;" + widget.FormatDate(C.dateLogPublishOnDate.Value()) + "&lt;/b&gt; will be ignored.&lt;/p&gt;";
      }
      if (mRecord.CanChargeFee &amp;&amp; C.numFee.Value() != 0) {
        message += "&lt;p&gt;NOTE: A fee of &lt;b&gt;" + widget.FormatCurrency(C.numFee.Value(), true) + "&lt;/b&gt; will be charged when this Document is published.&lt;/p&gt;";
      }

      widget.UI.MsgBoxConfirm(message,
                              {
                                heading: heading,
                                icon: "Document",
                                messageIsHtml: true,
                              },

                              function () {
                                Form_ExecuteAction_FinishPost(publish);
                              },
                              null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost(publish);
    }
  });
}

function Form_ExecuteAction_FinishPost(publish) {
  // Block UI
  widget.UI.Block("Creating Document, please wait...");

  // Get Parameters
  var params = CreateFinishParameters();

  // Publish/ Save
  params.Publish = publish;

  // 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 Document was created but the following warning was given:\n\n" + data.WarningMessage, {},
          function () {
            // Close
            widget.Close();
          }
        );
      }
      else {
        if (data.DocumentShowApplicationShortcutUrl) {
          // Prompt to show Document
          widget.UI.MsgBoxConfirm("Download a copy of the Document that was created?\n\nNOTE: Selecting 'OK' will immediately set the Document Log's Print Status to 'Printed'.", { heading: "Download Document" },
            function () {
              // Close
              // NOTE: Must be done before the download since the download may present an additional dialog
              widget.Close();
              
              // Flag Log as being Printed
              widget.GetString("SetLogPrinted", { logPk: data.LogPk, logObjectType: data.LogObjectType }, 
                function (data) {
                  // Do nothing
                },
                
                function (error) {
                  // Must block by using window.alert to show error (should never occur)
                  window.alert(error);
                }
              );

              // Download
              widget.ExecuteApplicationShortcutUrl(data.DocumentShowApplicationShortcutUrl);
            },

            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)) {
        case "Parameters":
          if (mDocument.HasParameters) found = true;
          break;

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

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

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

        default:
          found = true;
          break;
      }

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

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

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

      case "Sms":
        pageSms_Refresh();
        break;

      case "Preview":
        pagePreview_Refresh();
        break;

      case "Notes":
        pageNotes_Refresh();
        break;

      default:
        break;
    }
  }

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

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

  // Tweak fields

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

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

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

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

    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

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

  // Resize Wizard
  tabWizard_Resize();

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

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

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

    case "Email":
      C.cboEmailTo.WidthResizeFromParent();
      C.txtEmailCc.WidthResizeFromParent();
      C.txtEmailBcc.WidthResizeFromParent();
      break;

    case "Sms":
      break;

    case "Notes":
      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"));
    cmdSave.prop("disabled", !cmdNext.prop("disabled"));
  }

  // Publish not allowed?
  if (mRecord_Document &amp;&amp; !mRecord_Document.CanPublish) cmdFinish.prop("disabled", true);
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (C.gridDocuments.ActiveDataRowListIndex() == -1) {
          Ok = false;
          C.gridDocuments.Focus();
        }
        else {
          mDocument = mRecord_Documents[C.gridDocuments.ActiveDataRowListIndex()];
        }
        break;

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

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

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

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

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

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

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

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

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

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

        // Defaults
        switch(mDocument.FileType) {
          case "Email":
            // =====
            // Email
            // =====
            if (mRecord_Document.DefaultContact) C.cboEmailTo.Text(mRecord_Document.DefaultContact);

            C.txtEmailSubject.Text(mRecord_Document.EmailSubject);
            //C.txtEmailSubject.TagsListDefineFromCodeDescriptionList(mRecord_Document.TagsEmailSubject);

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

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

            C.cboEmailTo.RefreshFromCollection(mRecord_Document.Contacts, "Value", "Description", "Source,Name,Description,Value");
            break;

          case "Sms":
            // ===
            // SMS
            // ===
            if (mRecord_Document.DefaultContact) C.cboPhoneNumber.Text(mRecord_Document.DefaultContact);

            C.cboBranch.Text(mRecord_Document.DefaultBranchId);
            cboBranch_Change();

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

            C.cboPhoneNumber.RefreshFromCollection(mRecord_Document.Contacts, "Value", "Description", "Source,Name,Description,Value");
            break;
        }

        C.numFee.Value(mRecord_Document.DefaultFee);
        C.chkEmailDocument.Value(mRecord_Document.EmailDocumentDefault);

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =========
// pageEmail
// =========
function pageEmail_Refresh() {
  // Initialise
  mEmailSender = null;
  mEmailSenderName = null;

  // Get Parameters
  var params = CreateFinishParameters();

  // Block UI
  widget.UI.Block("Generating email message, please wait...");

  // Get Preview
  widget.GetString("GenerateMessage", params,
    // Success
    function (data) {
      // Parse
      data = JSON.parse(data);

      if (data.Subject) C.txtEmailSubject.Text(data.Subject);
      if (data.Message) C.heEmailMessage.Text(data.Message);
      if (data.EmailTo) C.cboEmailTo.Text(data.EmailTo);
      if (data.EmailCc) C.txtEmailCc.Text(data.EmailCc);
      if (data.EmailBcc) C.txtEmailBcc.Text(data.EmailBcc);
      if (data.EmailSender) mEmailSender = data.EmailSender;
      if (data.EmailSenderName) mEmailSenderName = data.EmailSenderName;
      
      // Controls
      if (data.EmailRecipients.length &lt; 2) {
        C.chkEmailUseDocumentRecipientsList.Value(false);
        
        C.lblUseDocumentRecipientsList.VisibleRow(false);
        C.chkEmailUseDocumentRecipientsList.VisibleRow(false);
        C.trUseDocumentRecipientsListRecipients.hide();
      }
      else {
        C.lblUseDocumentRecipientsList.VisibleRow(true);
        C.chkEmailUseDocumentRecipientsList.VisibleRow(true);
        C.trUseDocumentRecipientsListRecipients.show();
        
        var ul = "";
        ul += "&lt;ul&gt;";
        for (var i = 0; i &lt; data.EmailRecipients.length; i++) {
          var item = data.EmailRecipients[i];
          ul += "&lt;li&gt;" + widget.UI.HtmlEncode(item.Description) + " (" + widget.UI.HtmlEncode(item.Code) + ")&lt;/li&gt;";
        }
        ul += "&lt;/ul&gt;";
        C.divUseDocumentRecipientsListRecipients.html(ul);
      }
      
      // Ensure top header has a consistent gap
      tabWizard.AutoFormatPage();

      // Configure HTML Editor
      if (mRecord_Document.EmailHtml) {
        C.heEmailMessage.PlainText(false);
        C.heEmailMessage.ShowHtmlMarkup(false);
      }
      else {
        C.heEmailMessage.PlainText(true);
      }

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

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

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

}

// =======
// pageSms
// =======
function pageSms_Refresh() {
  // Get Parameters
  var params = CreateFinishParameters();

  // Block UI
  widget.UI.Block("Generating SMS message, please wait...");

  // Get Preview
  widget.GetString("GenerateMessage", params,
    // Success
    function (data) {
      // Parse
      data = JSON.parse(data);

      if (data.Message) C.txtMessage.Text(data.Message);
      if (data.SmsPhoneNumber) C.cboPhoneNumber.Text(data.SmsPhoneNumber);

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

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

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

}

// ===========
// pagePreview
// ===========
function pagePreview_Refresh() {
  // Get Parameters
  var params = CreateFinishParameters();

  // Re-preview?
  if (JSON.stringify(params) == mLastPreviewJson) {
    // Nothing has changed
    return;
  }
  else {
    // Track changes
    mLastPreviewJson = JSON.stringify(params);
  }

  // Initialise
  C.wbPreview.Clear();

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

  // Get Preview
  widget.GetString("GetMessagePreview", params,
    // Success
    function (data) {
      // Parse
      data = JSON.parse(data);

      // Preview
      C.wbPreview.SetContent(data.Html, true, {});

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

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

    // Fail
    function (error) {
      // Ignore
      console.warn("Failed to get message preview.");

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

// =========
// pageNotes
// =========
function pageNotes_Refresh() {
  if (mRecord_Document.CanChargeFee &amp;&amp; mRecord_Document.ChargeFee) {
    C.lblFee.VisibleRow(true);
    C.numFee.VisibleRow(true);
    C.numFee.ReadOnly(!mRecord_Document.CanUpdateFee);
  }
  else {
    C.lblFee.VisibleRow(false);
    C.numFee.VisibleRow(false);
  }

  if (mRecord_Document.AllowExternalParty) {
    C.lblExternalParty.VisibleRow(true);
    C.cboExternalParty.VisibleRow(true);
    C.cboExternalParty.AllowBlank(!mRecord_Document.ExternalPartyMandatory);

    // Refresh External Parties
    if (!C.cboExternalParty.Tag || C.cboExternalParty.Tag != mRecord_Document.ExternalPartiesFilter) {
      C.cboExternalParty.Tag = mRecord_Document.ExternalPartiesFilter;
      C.cboExternalParty.RefreshFromStandardRange("ExternalParties", mRecord_Document.ExternalPartiesFilter);
    }
  }
  else {
    C.lblExternalParty.VisibleRow(false);
    C.cboExternalParty.VisibleRow(false);
  }

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

  divPublishDetails_Refresh();
}

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

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

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

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

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

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

// ======
// numFee
// ======
function numFee_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  divPublishDetails_Refresh();
}

// =================
// divPublishDetails
// =================
function divPublishDetails_Refresh() {
  var s = "";

  // Information
  s += "&lt;p&gt;Log(s) to create Document &lt;b&gt;" + mDocument.DocumentId + "&lt;/b&gt;, '" + widget.UI.HtmlEncode(mDocument.Description) + "' will be added.&lt;/p&gt;";

  if (C.chkEmailDocument.Value()) {
    s += "&lt;p&gt;If possible, the Document, once published, will be sent by email.&lt;/p&gt;";
  }

  // Warnings
  var warnings = "";
  if (!mRecord_Document.CanPublish) {
    warnings += "&lt;p&gt;This type of Document cannot be published from here. Instead, the Document Log that is added will need to be published.&lt;/p&gt;";
  }
  if (warnings) {
    s += "&lt;div style='color:red'&gt;" + warnings + "&lt;/div&gt;";
  }


  C.divPublishDetails.html(s);
}

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

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

  // Update Service
  cboService_Change();
}

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

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


  // Update Message
  txtMessage_Change();
}

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

  // Refresh SMS Information
  txtMessage_RefreshInfo();
}

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

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

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

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

      // Refresh SMS Information
      divMessageInfo_Refresh();
    },

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

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

// =====================
// chkEmailUseDocumentRecipientsList
// =====================
function chkEmailUseDocumentRecipientsList_Change(sender, e) {
  // Controls
  C.lblEmail.VisibleRow(!C.chkEmailUseDocumentRecipientsList.Value());
  C.cboEmailTo.VisibleRow(!C.chkEmailUseDocumentRecipientsList.Value());
  C.txtEmailCc.VisibleRow(!C.chkEmailUseDocumentRecipientsList.Value());
  C.txtEmailBcc.VisibleRow(!C.chkEmailUseDocumentRecipientsList.Value());
  
  if (C.chkEmailUseDocumentRecipientsList.Value()) {
    C.divUseDocumentRecipientsListRecipients.css("font-weight", "bold");
  }
  else {
    C.divUseDocumentRecipientsListRecipients.css("font-weight", "normal");
  }
  
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>iLlx12UEX0aLoDzJoXhuWQ</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption>Create Document</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1024</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>Document</Icon>
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="OnlyIncludeDocumentsFlaggedForCloud" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="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>Account,AccountApp,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="AccountAppApplicantPk" 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="DocumentId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Documents</List>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="FilterByFileType" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="FileType" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>Email,ExcelWorkbook,Html,Log,Script,Sms,WordDocument</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ReplyLogPk" 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="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 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>