<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-07-25T03:40:34.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-11-15T20:29:16.6900000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-07-25T03:40:06.2430000</UpdatedUtcDate>
    <ScriptId>ACCOUNTCLIENT</ScriptId>
    <Description>Account Client</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountClient
Option Explicit On
Option Strict On

' #################################################################
' Account Client wizard HTML Widget
'
' Version: 1.06 (25/07/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.05  01/12/2023  ISS      J032532   Visual glitch when first loaded
'    1.06  04/07/2024  ISS      J033682   A new Client can now be added directly from this wizard
'          25/07/2024  ISS      J032663   Fixed when Insurance details are displayed
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountClient"

' Common Parameters
Private mAccountClientPk As Integer
Private mAccountId As String
Private mReadOnly As Boolean

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

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

  ' Assume Success
  Main = True

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

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

  ' Get Common Parameters
  With mCombinedParameters
    mAccountId = .GetString("AccountId")
    mAccountClientPk = .GetInteger("AccountClientPk")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return initial HTML content (excluding html and body tags)
      returnValue = Replace(ScriptInfo.TemplateText, "&lt;%[RecordId]%&gt;", mAccountId)

    Case "Delete"
      ' Delete
      Main = Delete(returnValue)

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

    Case "Form_AccountRole_Change"
      ' Role Change
      Main = Form_AccountRole_Change(returnValue)

    Case "Form_AccountClient_Change"
      ' Client Change
      Main = Form_AccountClient_Change(returnValue)

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

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

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

End Function

''' &lt;summary&gt;
'''  Get updated form information when the Account Role changes.
''' &lt;/summary&gt;
Public Function Form_AccountRole_Change(ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountRole As finAccountRoleRO
  Dim AccountRoleId As String
  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Account
  If Success Then
    Success = CreateAccount(Nothing, Account, Nothing)
  End If
  
  If Success Then
    ' Account Role
    If finBL.AccountRoles.Exists(AccountRoleId) Then
      AccountRole = finBL.AccountRoles(AccountRoleId)

      ' Create Response
      obj = New With {
        .ShowPrivacyConsent = AccountRole.UsePrivacyConsent,
        .ShowInsuranceDetails = (AccountRole.RecordInsuranceDetails AndAlso Account.ProductType.IncludeClientLevelInsurance),
        .AccountHidden = AccountRole.AccountHidden,
        .AccountSignatory = AccountRole.AccountSignatory,
        .SendDocuments = AccountRole.SendDocuments,
        .SecurityParty = AccountRole.IncludeInSecurityStatement
      }
    Else
      obj = New With {
        .ShowPrivacyConsent = True,
        .ShowInsuranceDetails = False
      }
    End If
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get updated form information when the Client changes.
''' &lt;/summary&gt;
Public Function Form_AccountClient_Change(ByRef response As String) As Boolean

  Dim Client As finClient
  Dim ClientId As String
  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Create Client object
  If Success Then
    Client = finBL.CreateClient()
    Success = Client.Load(ClientId)
  End If

  If Success Then
    ' Create Response
    obj = New With {
      .AddresseeBlankTip = Client.AddresseeNameDefault,
      .SalutationBlankTip = Client.SalutationDefault
    }
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create Context Data for Scripts.
''' &lt;/summary&gt;
Private Function CreateScriptContextData() As ISKeyValueList

  CreateScriptContextData = finBL.CreateKeyValueList()
  With CreateScriptContextData
    .SetObject("Target", ScriptInfo.Target)
    .SetBoolean("HighDpi", finBL.HighDpi)
    .SetString("FormKey", FORM_KEY)
    .SetString("FormRecordMode", iseFormRecordMode.Loaded.ToString())
  End With

End Function

''' &lt;summary&gt;
'''  Delete Account Client.
''' &lt;/summary&gt;
Private Function Delete(ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Create Account and Account Client objects
  If Success Then
    Success = CreateAccount(WizardFinishParameters, Account, AccountClient)
  End If

  ' Delete and Save
  If Success Then
    ' Remove from collection
    Success = Account.Clients.Remove(AccountClient)

    ' Save
    If Success Then
      Success = Account.Save()
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Commit changes.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim Index As Integer
  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 Account and Account Client objects
  If Success Then
    Success = CreateAccount(WizardFinishParameters, Account, AccountClient)
  End If

  ' If it's a new Account Client add to collection
  If Success AndAlso mAccountClientPk = -1 Then
    Account.Clients.Add(AccountClient)
  End If

  ' Move?
  If Success Then
    Select Case WizardFinishParameters.MoveAction
      Case "MoveTop"
        Index = Account.Clients.IndexOf(AccountClient)
        If Index &gt; 0 Then Success = Account.Clients.Move(Index, 0)
    End Select
  End If

  ' Execute
  If Success Then
    Success = Account.Save()
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Create a finAccount and finAccountClient object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccount(parameters As WizardFinishParameters,
                               ByRef account As finAccount,
                               ByRef accountClient As finAccountClient) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  account = finBL.CreateAccount()
  accountClient = Nothing

  ' Load Account
  If Success Then
    Success = account.Load(mAccountId)
  End If

  ' Get Account Client
  If Success Then
    If mAccountClientPk = -1 Then
      accountClient = account.Clients.CreateAccountClient()
    ElseIf account.Clients.ExistsPk(mAccountClientPk) Then
      accountClient = account.Clients.ItemByPk(mAccountClientPk)
    Else
      Success = False
      finBL.Error.ErrorBeginFormat("Invalid Account Client Pk {0}.", mAccountClientPk)
    End If
  End If

  ' Update Account Client
  If Success AndAlso parameters IsNot Nothing Then
    With accountClient
      .AccountRoleId = parameters.AccountRoleId
      .RoleJoint = parameters.RoleJoint
      .ClientIdSet(parameters.ClientId)
      .Addressee = parameters.Addressee
      .Salutation = parameters.Salutation
      .AccountHidden = parameters.AccountHidden
      .AccountSignatory = parameters.AccountSignatory
      .PrivacyConsent = parameters.PrivacyConsent
      .SendDocuments = parameters.SendDocuments
      .SecurityParty = parameters.SecurityParty
      .Notes = parameters.Notes
      .InsuranceInsurerExternalPartyId = parameters.InsuranceInsurerExternalPartyId
      .InsurancePolicyType = parameters.InsurancePolicyType
      .InsurancePolicyNumber = parameters.InsurancePolicyNumber
    End With
  End If

  Return Success

End Function

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

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim strTemp As String

  ' Assume Success
  Success = True

  ' Validate
  If Len(mAccountId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Id not specified.")
  ElseIf mAccountClientPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Client Pk not specified.")
  ElseIf finBL.CurrentUserInformation.IsAccountFilteredOut(mAccountId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Account.")
  ElseIf mAccountClientPk &lt; -1 Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Account Client Pk {0}.", mAccountClientPk)
  End If

  ' Create Account and Account Client objects
  If Success Then
    Success = CreateAccount(Nothing, Account, AccountClient)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Read Only?
      If finBL.Database.IsReadOnly OrElse mReadOnly Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .IsNew = AccountClient.IsNew
      .Timestamp = AccountClient.Timestamp

      ' Account Properties
      .RecordId = Account.AccountId
      .RecordDescription = Account.Name

      ' Details
      .AccountHidden = AccountClient.AccountHidden
      .AccountRole = AccountClient.AccountRoleId
      .AccountSignatory = AccountClient.AccountSignatory
      .Addressee = AccountClient.Addressee
      .AddresseeBlankTip = AccountClient.Client.AddresseeNameDefault
      .ClientId = AccountClient.ClientId
      .InsuranceInsurerExternalParty = AccountClient.InsuranceInsurerExternalPartyId
      .InsurancePolicyNumber = AccountClient.InsurancePolicyNumber
      .InsurancePolicyType = AccountClient.InsurancePolicyType
      .Notes = AccountClient.Notes
      .PrivacyConsent = AccountClient.PrivacyConsent
      .RoleJoint = AccountClient.RoleJoint
      .Salutation = AccountClient.Salutation
      .SalutationBlankTip = AccountClient.Client.SalutationDefault
      .SecurityParty = AccountClient.SecurityParty
      .SendDocuments = AccountClient.SendDocuments

      ' Permissions
      .CanAddClient = finBL.CurrentUser.Permissions.Allow("Client.Add")      

      ' Configuration
      .IsMainClient = AccountClient.Client Is Account.Clients(0).Client

      If .ReadOnly OrElse .IsNew Then
        .CanDelete = False
      Else
        .CanDelete = AccountClient.CanDelete
      End If
      If AccountClient.AccountRolePk = 0 Then
        .ShowPrivacyConsent = True
        .ShowInsuranceDetails = False
      Else
        .ShowPrivacyConsent = AccountClient.AccountRole.UsePrivacyConsent
        .ShowInsuranceDetails = (AccountClient.AccountRole.RecordInsuranceDetails AndAlso Account.ProductType.IncludeClientLevelInsurance)        
      End If
      If finBL.Settings.AddOns.SecurityRegister Then
        Select Case finBL.CountryCode
          Case "AU"
            .ShowSecurityParty = True
            .SecurityPartyCaption = "Include as a Grantor when Registering a Security Interest on the PPSR?"
          Case "NZ"
            .ShowSecurityParty = True
            .SecurityPartyCaption = "Include as a Debtor when registering a Financing Statement on the PPSR?"
          Case Else
            .ShowSecurityParty = False
        End Select
      Else
        .ShowSecurityParty = False
      End If
      
      .WidgetNewIndividualClient = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientNew_Individual, mCombinedParameters.GetBoolean("UseBuiltInNewIndividualClientHTMLWidget"), strTemp)
      .WidgetNewIndividualClient_StartupParametersJson = strTemp
      .WidgetNewOrganisationClient = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientNew_Organisation, mCombinedParameters.GetBoolean("UseBuiltInNewOrganisationClientHTMLWidget"), strTemp)
      .WidgetNewOrganisationClient_StartupParametersJson = strTemp
      .ShowInsurerExternalParty = finBL.Settings.AddOns.ExternalPartyInsurers
      .SupportsIndividualClients = (finBL.ClientTypes.GetIndividualPksList(False, True).Count &lt;&gt; 0)
      .SupportsOrganisationClients = (finBL.ClientTypes.GetOrganisationPksList(True, True).Count &lt;&gt; 0)

      ' Lists
      .InsurerExternalPartyListFilter = finBL.ExternalParties.GetDataViewFilter_SupportsLinkedAccounts(isefinExternalPartyType.Insurer)
      .RoleListFilter = Account.ProductType.AccountRoleDataViewFilter()

      ' Other Configuration
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
    End With
  End If

  ' Further Validations
  If Success Then
    If FormInitialisationInfo.ReadOnly AndAlso mAccountClientPk = -1 Then
      Success = False
      finBL.Error.ErrorBegin("Cannot add a new Client to the Account whilst form is Read-Only.")
    End If
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, response)
  End If

  Return Success

End Function

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

  Dim ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
      If WizardValidate_General(parametersJson, ConfirmList) Then
        Data = ConfirmList
      Else
        Success = False
      End If
  End Select

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

  Return Success

End Function

Private Function WizardValidate_General(parametersJson As String,
                                        ByRef confirmList As List(Of String)) As Boolean

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise ByRef
  confirmList = New List(Of String)()

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

  ' Create Account and Account Client objects
  If Success Then
    Success = CreateAccount(WizardFinishParameters, Account, AccountClient)
  End If

  ' Timestamp
  If Success Then
    If Not AccountClient.IsNew AndAlso AccountClient.Timestamp &lt;&gt; WizardFinishParameters.Timestamp Then
      confirmList.Add("The Item has changed since it was loaded, if you continue your update may overwrite these changes.")
    End If
  End If

  Return Success

End Function

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

  ' Record
  Public IsNew As Boolean
  Public Timestamp As Integer

  ' Account Properties
  Public RecordId As String
  Public RecordDescription As String

  ' Details
  Public AccountHidden As Boolean
  Public AccountRole As String
  Public AccountSignatory As Boolean
  Public Addressee As String
  Public AddresseeBlankTip As String
  Public ClientId As String
  Public InsuranceInsurerExternalParty As String
  Public InsurancePolicyNumber As String
  Public InsurancePolicyType As String
  Public Notes As String
  Public PrivacyConsent As Boolean
  Public RoleJoint As Boolean
  Public Salutation As String
  Public SalutationBlankTip As String
  Public SecurityParty As Boolean
  Public SendDocuments As Boolean

  ' Lists
  Public InsurerExternalPartyListFilter As String
  Public RoleListFilter As String

  ' Permissions
  Public CanAddClient As Boolean
  
  ' Configuration
  Public [ReadOnly] As Boolean
  Public CanDelete As Boolean
  Public IsMainClient As Boolean
  Public PromptOnSave As Boolean
  Public SecurityPartyCaption As String
  Public ShowInsuranceDetails As Boolean
  Public ShowInsurerExternalParty As Boolean
  Public ShowPrivacyConsent As Boolean
  Public ShowSecurityParty As Boolean
  Public SupportsIndividualClients As Boolean
  Public SupportsOrganisationClients As Boolean
  Public WidgetNewIndividualClient As String
  Public WidgetNewIndividualClient_StartupParametersJson As String
  Public WidgetNewOrganisationClient As String
  Public WidgetNewOrganisationClient_StartupParametersJson As String

End Class

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

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

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

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

  End Sub

End Class

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

  Public AccountHidden As Boolean
  Public AccountRoleId As String
  Public AccountSignatory As Boolean
  Public Addressee As String
  Public ClientId As String
  Public InsuranceInsurerExternalPartyId As String
  Public InsurancePolicyNumber As String
  Public InsurancePolicyType As String
  Public Notes As String
  Public PrivacyConsent As Boolean
  Public RoleJoint As Boolean
  Public Salutation As String
  Public SendDocuments As Boolean
  Public SecurityParty As Boolean

  ' Other
  Public MoveAction As String
  Public Timestamp As Integer

End Class

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

  Public AccountClientPk As Integer

  Public Sub New(accountClientPk As Integer)

    Me.AccountClientPk = accountClientPk

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountClient".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText=""&gt;Account Client&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"&gt;
      &lt;table class="is-form"&gt;

        &lt;tr&gt;&lt;td&gt;
          &lt;!-- Chrome sizing issue (May-2018) requires use of a sub-table --&gt;
          &lt;table class="is-form"&gt;
            &lt;colgroup&gt;
              &lt;col style="width:9em" /&gt;
              &lt;col /&gt;
            &lt;/colgroup&gt;

            &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblRole"&gt;Role details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboClientRecord"&gt;Client:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboClientRecord" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr id="trNewClient"&gt;
              &lt;th&gt;&lt;/th&gt;
              &lt;td&gt;&lt;button id="cmdAddClient" class="is-button small"&gt;Add New Client&lt;/button&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="chkRoleJoint"&gt;Joint Client:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="chkRoleJoint" type="checkbox"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboRole"&gt;Role:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboRole" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtAddressee"&gt;Addressee:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtAddressee"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtSalutation"&gt;Salutation:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtSalutation"/&gt;&lt;/td&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 colspan="2"&gt;&lt;label id="lblClientOptions"&gt;Options&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkAccountHidden" type="checkbox"/&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkAccountSignatory" type="checkbox"/&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkPrivacyConsent" type="checkbox"/&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkSendDocuments" type="checkbox"/&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkSecurityParty" type="checkbox"/&gt;&lt;/th&gt;
            &lt;/tr&gt;

            &lt;tr class="trInsurance"&gt;&lt;th colspan="2"&gt;&lt;label id="lblInsurance"&gt;Insurance details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
            &lt;tr class="trInsurance"&gt;
              &lt;th&gt;&lt;label for="cboInsuranceInsurerExternalParty"&gt;Insurer:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboInsuranceInsurerExternalParty" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr class="trInsurance"&gt;
              &lt;th&gt;&lt;label for="cboInsurancePolicyType"&gt;Policy Type:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboInsurancePolicyType"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr class="trInsurance"&gt;
              &lt;th&gt;&lt;label for="txtInsurancePolicyNumber"&gt;Policy Number:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtInsurancePolicyNumber"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/td&gt;&lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdActions"/&gt;

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

&lt;/div&gt;

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

// Controls
var C = {
  // General
  lblRole: null,
  cboRole: null,
  chkRoleJoint: null,
  cboClientRecord: null,
  trNewClient: null,
  txtAddressee: null,
  txtSalutation: null,

  lblClientOptions: null,
  chkAccountHidden: null,
  chkAccountSignatory: null,
  chkPrivacyConsent: null,
  chkSendDocuments: null,
  chkSecurityParty: null,

  lblNotes: null,
  txtNotes: null,

  lblInsurance: null,
  cboInsuranceInsurerExternalParty: null,
  cboInsurancePolicyType: null,
  txtInsurancePolicyNumber: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdAddClient;

// ==========
// Initialise
// ==========
$(function () {
  // Mobile optimisations
  var currencyWidth = "20em";
  $(window).resize(Form_Resize);

  // --------
  // Controls
  // --------
  //   General
  C.lblRole = widget.UI.Label("lblRole", {});
  C.cboClientRecord = widget.UI.DBCombo("cboClientRecord", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboClient_Change,
  });
  C.trNewClient = $("#trNewClient");
  C.chkRoleJoint = widget.UI.CheckBox("chkRoleJoint", {
    caption: "Joint Client?",

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

    onChange: cboRole_Change,
  });
  C.txtAddressee = widget.UI.TextBox("txtAddressee", {
    maxLength: 50
  });
  C.txtSalutation = widget.UI.TextBox("txtSalutation", {
    maxLength: 50
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });

  C.lblClientOptions = widget.UI.Label("lblClientOptions", {});
  C.chkAccountHidden = widget.UI.CheckBox("chkAccountHidden", {
    caption: "Hide the Account from this Client?",
  });
  C.chkAccountSignatory = widget.UI.CheckBox("chkAccountSignatory", {
    caption: "Is this Client a Signatory?",
  });
  C.chkPrivacyConsent = widget.UI.CheckBox("chkPrivacyConsent", {
    caption: "Has a Privacy Consent form been signed?",
  });
  C.chkSendDocuments = widget.UI.CheckBox("chkSendDocuments", {
    caption: "Send Mail to this Client?",
  });
  C.chkSecurityParty = widget.UI.CheckBox("chkSecurityParty", {
    caption: "",
  });

  C.lblInsurance = widget.UI.Label("lblInsurance", {});
  C.cboInsuranceInsurerExternalParty = widget.UI.DBCombo("cboInsuranceInsurerExternalParty", {
  });
  C.cboInsurancePolicyType = widget.UI.InformationListComboBox("cboInsurancePolicyType", {
    maxLength: 17
  });
  C.txtInsurancePolicyNumber = widget.UI.TextBox("txtInsurancePolicyNumber", {
    maxLength: 22
  });

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

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

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

  cmdAddClient = $("#cmdAddClient");
  cmdAddClient.click(function() { Form_ExecuteAction("AddClient"); });

  // Reset
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

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

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

      // Define Actions
      var actions = [];
      if (!mRecord.ReadOnly &amp;&amp; mRecord.CanDelete) actions.push({ groupId: "Record", actionId: "Delete", caption: "Delete", icon: "Delete" });
      if (!mRecord.ReadOnly &amp;&amp; !mRecord.IsNew) actions.push({ groupId: "Other", actionId: "MoveTop", caption: "Promote Client to top of List", icon: "Move_Up" });

      frmMain.ActionsDefine(actions, "cmdActions", Form_ExecuteAction);
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboClientRecord.Text(mRecord.ClientId);
    C.chkRoleJoint.Value(mRecord.RoleJoint);
    C.cboRole.Text(mRecord.AccountRole);
    C.txtAddressee.Text(mRecord.Addressee);
    C.txtAddressee.BlankTip(mRecord.AddresseeBlankTip);
    C.txtSalutation.Text(mRecord.Salutation);
    C.txtSalutation.BlankTip(mRecord.SalutationBlankTip);
    C.txtNotes.Text(mRecord.Notes);

    C.chkAccountHidden.Value(mRecord.AccountHidden);
    C.chkAccountSignatory.Value(mRecord.AccountSignatory);
    C.chkPrivacyConsent.Value(mRecord.PrivacyConsent);
    C.chkSendDocuments.Value(mRecord.SendDocuments);
    C.chkSecurityParty.Value(mRecord.SecurityParty);

    C.cboInsuranceInsurerExternalParty.Text(mRecord.InsuranceInsurerExternalParty);
    C.cboInsurancePolicyType.Text(mRecord.InsurancePolicyType);
    C.txtInsurancePolicyNumber.Text(mRecord.InsurancePolicyNumber);
  }

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

  // Update Controls
  if (mRecord) {
    C.chkSecurityParty.Caption(mRecord.SecurityPartyCaption);
  }

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Not used by this wizard since there is no concept of updating an object behind the wizard
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  var heading = "Account Client";
  if (mRecord &amp;&amp; mRecord.IsNew) heading = "New " + heading;
  widget.SetHeading(heading);

  // Lists
  if (mRecord) {
    C.cboClientRecord.RefreshFromStandardRange("Clients", "", false, mRecord.ClientId);
    C.cboRole.RefreshFromStandardRange("AccountRoles", mRecord.RoleListFilter);
    C.cboInsuranceInsurerExternalParty.RefreshFromStandardRange("ExternalParties", mRecord.InsurerExternalPartyListFilter);
    C.cboInsurancePolicyType.SetComboFromInformationList("InsurancePolicyTypes", true);
  }

  // Controls
  if (mRecord) {
    // Permissions
    if (!mRecord.IsReadOnly) {
      C.chkRoleJoint.ReadOnly(mRecord.IsMainClient);
      C.chkAccountHidden.ReadOnly(mRecord.IsMainClient);
      C.chkAccountSignatory.ReadOnly(mRecord.IsMainClient);
      C.chkSendDocuments.ReadOnly(mRecord.IsMainClient);
      C.chkSecurityParty.ReadOnly(mRecord.IsMainClient);
    }

    // Visible
    C.cboRole.VisibleRow(!mRecord.RoleJoint);
    C.txtAddressee.VisibleRow(!mRecord.RoleJoint);
    C.txtSalutation.VisibleRow(!mRecord.RoleJoint);
    if (mRecord.IsReadOnly || !mRecord.CanAddClient) C.trNewClient.hide();

    C.chkSecurityParty.VisibleRow(mRecord.ShowSecurityParty);
    C.chkPrivacyConsent.VisibleRow(mRecord.ShowPrivacyConsent);    
    if (mRecord.ShowInsuranceDetails) {
      $(".trInsurance").show();
      C.cboInsuranceInsurerExternalParty.VisibleRow(mRecord.ShowInsurerExternalParty);
    }
    else {
      $(".trInsurance").hide();
      C.cboInsuranceInsurerExternalParty.VisibleRow(false);
    }
  }

  // Check for Advanced options
  if (mRecord) {
  }

  // Update Buttons
  tabWizard_UpdateButtons();

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) frmMain.FormReadOnly(C, true);

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

  // Show History
  if (mRecord) {
  }

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

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

function tabWizard_UpdateButtons() {
  // Back and Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();
    cmdBack.prop("disabled", tabIndex &lt;= 0);
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
  }

  // Cancel/ Finish Button
  if (mRecord &amp;&amp; mRecord.ReadOnly) {
    cmdCancel.hide();
    cmdFinish.text("Close");
  }
  else {
    if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
    cmdFinish.text("Save");
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.cboClientRecord.WidthResizeFromParent();
      C.cboRole.WidthResizeFromParent();
      C.txtAddressee.WidthResizeFromParent();
      C.txtSalutation.WidthResizeFromParent();
      C.txtNotes.WidthResizeFromParent();
      C.cboInsuranceInsurerExternalParty.WidthResizeFromParent();
      C.cboInsurancePolicyType.WidthResizeFromParent();
      C.txtInsurancePolicyNumber.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

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

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

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

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

  // Special
  switch(tabWizard.SelectedTabId()) {
  }

  // Tweak fields

  // Update Heading
  tabWizard_Refresh_UpdateHeading();

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

  // Resize Wizard
  tabWizard_Resize();

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

function tabWizard_Refresh_UpdateHeading() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      frmMain.RefreshHeading("Account Client", "Enter details of the Client for Account '" + mRecord.RecordId + "', " + mRecord.RecordDescription + ".");
      break;

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

// ===============
// Validate Wizard
// ===============
function tabWizard_Validate(validCallback) {
  // Read-Only
  if (mRecord.ReadOnly) {
    // No validation because form is Read Only
    validCallback();
    return;
  }

  // Validate
  var Ok = tabWizard.Validate(true);

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

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

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

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

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

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

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

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

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

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

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "ADDCLIENT":
      if (mRecord.ReadOnly || !mRecord.CanAddClient) {
        // Ignore
      }
      else {
        Form_ExecuteAction_AddClient_Pre();
      }
      break;
  
    case "DELETE":
      Form_ExecuteAction_Delete();
      break;

    case "FINISH":
      // Finish
      if (mRecord.ReadOnly) {
        tabWizard_Cancel();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;

    case "MOVETOP":
      Form_ExecuteAction_MoveTop();
      break;

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

// =================
// Add Client Action
// =================
function Form_ExecuteAction_AddClient_Pre() {
  if (mRecord.SupportsIndividualClients &amp;&amp; mRecord.SupportsOrganisationClients) {
    var list = [];
    list.push({ key: "IND", caption: "Individual", icon: "Client", details: "Add a new Individual Client" });
    list.push({ key: "ORG", caption: "Organisation", icon: "BankAccount", details: "Add a new Organisation Client" });
    
    widget.UI.MsgBoxList("Select the type of Client to add", list, { closeOnEscape: true, showClose: true }, Form_ExecuteAction_AddClient);
  }  
  else if (mRecord.SupportsIndividualClients) {
    Form_ExecuteAction_AddClient("IND");
  }
  else if (mRecord.SupportsOrganisationClients) {
    Form_ExecuteAction_AddClient("ORG");
  }
  else {
    widget.UI.MsgBoxAlert("Cannot add a new Client as no Client Types have been configured.");
  }
}

function Form_ExecuteAction_AddClient(key) {
  var params = {};
  var htmlWidgetId = "";

  switch(key) {
    case "IND":
      htmlWidgetId = mRecord.WidgetNewIndividualClient;
      if (mRecord.WidgetNewIndividualClient_StartupParametersJson) params = JSON.parse(mRecord.WidgetNewIndividualClient_StartupParametersJson);
      break;
      
    case "ORG":
      htmlWidgetId = mRecord.WidgetNewOrganisationClient;
      if (mRecord.WidgetNewOrganisationClient_StartupParametersJson) params = JSON.parse(mRecord.WidgetNewOrganisationClient_StartupParametersJson);
      break;
  }
  
  // Open New Client wizard
  if (htmlWidgetId) {
    params.ShowNewRecordOnFinish = false;
    widget.UI.Forms.ShowHtmlWidgetModal(htmlWidgetId, { startupParametersJson: JSON.stringify(params) }, Form_ExecuteAction_AddClient_Notify);
  }
}

function Form_ExecuteAction_AddClient_Notify(actionId, data) {
  // Parse
  var dataRaw = data;
  data = JSON.parse(data);

  // Handle
  switch(actionId) {
    case "RecordAdded":
      C.cboClientRecord.Text(data.ClientId);
      cboClient_Change();
      break;
  }
}

// =============
// Delete Action
// =============
function Form_ExecuteAction_Delete() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    widget.UI.MsgBoxConfirmDelete("Are you sure you want to delete the Client from this Account?",
                            {},
                            Form_ExecuteAction_DeletePost);
  });
}

function Form_ExecuteAction_DeletePost() {
  // Disable Form
  widget.UI.Block("Deleting, please wait...");

  // Delete
  widget.GetString("Delete", {},
    function (data) {
      // Close Form
      widget.Close();

      // Refresh Parent (to show updated details)
      widget.RefreshParent();
    },

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

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

// ==================
// Move to Top Action
// ==================
function Form_ExecuteAction_MoveTop() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    if (mRecord.PromptOnSave) {
      widget.UI.MsgBoxConfirm("Move the Client to the top of the list (to become the 'Main' Client)?\n\nNOTE: This will also save your changes.",
                              { heading: "Update and Promote Client" },
                              function () {
                                // Save and Move
                                Form_ExecuteAction_FinishPost("MoveTop");
                              });
    }
    else {
      // Save and Move without prompting
      Form_ExecuteAction_FinishPost("MoveTop");
    }
  });
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mRecord.PromptOnSave) {
      // Confirm
      if (mRecord.IsNew) {
        var heading = "Add Client";
        var message = "Are you sure you want to add the Client to this Account?";
      }
      else {
        var heading = "Update Client";
        var message = "Are you sure you want to update the Client for this Account?";
      }
      widget.UI.MsgBoxConfirm(message,
                              {heading: heading},
                              Form_ExecuteAction_FinishPost,
                              null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishPost(moveAction) {
  // Disable Form
  widget.UI.Block("Committing, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();

  // Move?
  if (moveAction) {
    params.MoveAction = moveAction;
  }

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

      // Finalise
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The Account was successfully updated but the following warning was given:\n\n" + data.Warning, {}, function() { Form_ExecuteAction_FinishPost_Finalise(data); });
      }
      else {
        Form_ExecuteAction_FinishPost_Finalise(data);
      }
    },

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

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

function Form_ExecuteAction_FinishPost_Finalise(data) {
  // Close Form
  widget.Close();

  // Refresh Parent (to show updated details)
  // NOTE: Because a new Account Client might not appear at the end of the Clients collection, we must pass in additional data)
  if (mRecord.IsNew) {
    widget.RefreshParent(mRecord.RecordId, { accountClientPk: data.AccountClientPk});
  }
  else {
    widget.RefreshParent(mRecord.RecordId);
  }

}

// ============
// chkRoleJoint
// ============
function chkRoleJoint_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  C.cboRole.VisibleRow(!C.chkRoleJoint.Value());
  C.txtAddressee.VisibleRow(!C.chkRoleJoint.Value());
  C.txtSalutation.VisibleRow(!C.chkRoleJoint.Value());

  // Show Privacy Consent option
  if (C.chkRoleJoint.Value()) {
    C.chkPrivacyConsent.VisibleRow(true);
  }
  else {
    // Refresh Account Role?
    if (C.cboRole.Text().length &gt; 0) {
      cboRole_Change();
    }
  }

  tabWizard_Resize();
}

// =========
// cboClient
// =========
function cboClient_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Create Parameters
  var params = {
    ClientId: C.cboClientRecord.Text(),
  };

  widget.GetString("Form_AccountClient_Change", params, AccountClient_Change_Done, AccountClient_Change_Fail);
}

function AccountClient_Change_Done(data) {
  if (data) {
    // Parse
    var o = JSON.parse(data);

    // Update Record
    mRecord.Addressee = "";
    mRecord.Salutation = "";
    mRecord.AddresseeBlankTip = o.AddresseeBlankTip;
    mRecord.SalutationBlankTip = o.SalutationBlankTip;

    // Load Controls
    C.txtAddressee.Text(mRecord.Addressee);
    C.txtSalutation.Text(mRecord.Salutation);
    C.txtAddressee.BlankTip(mRecord.AddresseeBlankTip);
    C.txtSalutation.BlankTip(mRecord.SalutationBlankTip);
  }
}

function AccountClient_Change_Fail(data) {
  widget.UI.MsgBoxAlert(data);
}

// =======
// cboRole
// =======
function cboRole_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Create Parameters
  var params = {
    AccountRole: C.cboRole.Text(),
  };

  widget.GetString("Form_AccountRole_Change", params, AccountRole_Change_Done, AccountRole_Change_Fail);
}

function AccountRole_Change_Done(data) {
  if (data) {
    // Parse
    var o = JSON.parse(data);

    // Update Record
    mRecord.ShowPrivacyConsent = o.ShowPrivacyConsent;
    mRecord.ShowInsuranceDetails = o.ShowInsuranceDetails;
    mRecord.AccountHidden = o.AccountHidden;
    mRecord.AccountSignatory = o.AccountSignatory;
    mRecord.SendDocuments = o.SendDocuments;
    mRecord.SecurityParty = o.SecurityParty;

    // Load Fields
    C.chkAccountHidden.Value(mRecord.AccountHidden);
    C.chkAccountSignatory.Value(mRecord.AccountSignatory);
    C.chkSendDocuments.Value(mRecord.SendDocuments);
    C.chkSecurityParty.Value(mRecord.SecurityParty);

    // Update Controls
    if (mRecord.ShowInsuranceDetails) {
      $(".trInsurance").show();      
      C.cboInsuranceInsurerExternalParty.VisibleRow(mRecord.ShowInsurerExternalParty);
    }
    else {
      $(".trInsurance").hide();
      C.cboInsuranceInsurerExternalParty.VisibleRow(false);
    }
    C.chkPrivacyConsent.VisibleRow(mRecord.ShowPrivacyConsent);
  }
}

function AccountRole_Change_Fail(data) {
  widget.UI.MsgBoxAlert(data);
}

function CreateFinishParameters() {
  // Create Parameters
  var params = {
    AccountHidden: C.chkAccountHidden.Value(),
    AccountRoleId: C.cboRole.Text(),
    AccountSignatory: C.chkAccountSignatory.Value(),
    Addressee: C.txtAddressee.Text(),
    ClientId: C.cboClientRecord.Text(),
    InsuranceInsurerExternalPartyId: C.cboInsuranceInsurerExternalParty.Text(),
    InsurancePolicyNumber: C.txtInsurancePolicyNumber.Text(),
    InsurancePolicyType: C.cboInsurancePolicyType.Text(),
    Notes: C.txtNotes.Text(),
    PrivacyConsent: C.chkPrivacyConsent.Value(),
    RoleJoint: C.chkRoleJoint.Value(),
    Salutation: C.txtSalutation.Text(),
    SendDocuments: C.chkSendDocuments.Value(),
    SecurityParty: C.chkSecurityParty.Value(),

    Timestamp: mRecord.Timestamp,
  };

  return params;
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>EemksV3DpEeM+J9a+ydhgQ</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</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 />
    <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>If you do not specify a Default Transaction Type, the Transaction Type selection will be shown regardless of the settings specified below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ReadOnly" 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="" 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="AccountId" 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.Accounts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountClientPk" 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>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>