<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-23T00:10:31.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-06-11T02:17:16.0530000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-23T00:08:49.9700000</UpdatedUtcDate>
    <ScriptId>NEWORGANISATION</ScriptId>
    <Description>New Organisation Client</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ClientNew_Organisation
Option Explicit On
Option Strict On

' #################################################################
' New Organisation Client HTML Widget
'
' Version: 1.24 (23/08/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.13  03/08/2021  ISS      J027128   Updated Pass Code Tooltip
'    1.14  07/06/2022  ISS      J028452   User Defined fields not retaining indexes
'    1.15  26/07/2022  ISS      J029189   Added Aka support
'          02/09/2022  ISS      J029396   Added Form Override support for Client Employments
'          01/11/2022  ISS      J029792   'Green' Medicare cards now only allow Month &amp; Year expiry
'          04/11/2022  ISS      J029822   'Card Number' for AU Drivers Licences added
'    1.16  08/06/2023  ISS      J031101   Added buttons to paste name and DOB for Identification items
'          14/06/2023  ISS      J031198   File Uploads are now validated against the finPOWER Connect Cloud Configuration allowed File Type list
'    1.17  24/08/2023  ISS      J031859   Added ExternalId and Cross Reference fields
'          25/08/2023  ISS      J031442   Prevented blank Client Contact Addresses from adding
'    1.18  28/09/2023  ISS      J031326   Client post-create warning message can no longer be dismissed via the 'x' at the top of the modal
'    1.19  18/01/2024  ISS      J032752   Add DateReview
'    1.20  05/04/2024  ISS      J032717   Added Foreign Tax Reference
'    1.21  03/05/2024  ISS      J033083   Added Matches page
'    1.22  07/05/2024  ISS      J032704   Tax Country Mandatory property is now dependent on if the Client is a Tax Resident
'          07/05/2024  ISS      J032452   Changed Document Manager Validation to use IsAvailableResolved instead of IsAvailable
'          08/05/2024  ISS      J032839   Changed DOB min and max values to use UTC dates
'    1.23  17/06/2024  ISS      J033716   Changed the "Other Details" page to respect Advanced Client licencing
'          17/06/2024  ISS      J033718   Removed excess padding from name fields
'          25/06/2024  ISS      J033520   Added Client Code Field
'    1.24  11/07/2024  ISS      J032263   Added dedicated Contact Methods page          
'          22/08/2024  ISS      J034092   Updated 'Other' communication heading to use Global Settings, Client, General, Profile Captions 
'          23/08/2024  ISS      J032269   Added dedicated Employments page
' #################################################################

' Constants
Private Const FORM_KEY As String = "ClientNew"
Private Const MAX_IMAGE_WIDTH As Integer = 1024

' Common Parameters
Private Shared mShowFullContactsGrid As Boolean = True

' 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
    mShowFullContactsGrid = .GetBoolean("ShowFullContactsGrid", mShowFullContactsGrid)
  End With

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

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

    Case "GeneratePassword"
      ' Generate a new strong password
      Main = GeneratePassword(returnValue)  

    Case "GetEmploymentItemPreview"
      ' Get the HTML Summary Page for the active row on the grid
      Main = GetEmploymentItemPreview(returnValue)          
      
    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)

    Case "GetClientStatisticsSetSummary"
      ' Get Client Statistics Set Summary
      Main = GetClientStatisticsSetSummary(parametersJson, returnValue)

    Case "ValidateIdentification"
      ' Validates Identification
      Main = ValidateIdentification(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;
'''  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 Client As finClient
  Dim ImageError As String
  Dim ImageOk As Boolean
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  ImageOk = True
  Success = True

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

  ' Create Client object
  If Success Then
    Success = CreateClient(WizardFinishParameters, Client)
  End If

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

  ' Save Client Image to Document Manager
  ' NOTE: Must be done after the Client is saved since the Document Manager is not available for an unsaved Client
  If Success AndAlso finBL.DocumentManager.IsAvailableResolved AndAlso requestInfo.Files.Count &lt;&gt; 0 Then
    ' Validate and Add
    With requestInfo.Files(0)
      If finBL.HtmlWidgetUtilities.IsFileUploadValidImage(.FileData, .FileName, True) Then
        If Not Client.ImageFileAdd(.FileData, "", MAX_IMAGE_WIDTH, True) Then
          ImageOk = False
        End If
      Else 
        ImageOk = False        
      End If  
    End With
    
    If Not ImageOk Then      
      finBL.Error.ErrorExtendFormat("Client Image file {0} is invalid.", requestInfo.Files(0).FileName)
      ImageError = finBL.Error.Message(True)
    End If
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Create a finClient object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateClient(parameters As WizardFinishParameters,
                              ByRef client As finClient) As Boolean

  Dim Aka As Aka
  Dim ClientEmployment As finClientEmployment
  Dim ClientStatisticsSet As finClientStatisticsSet
  Dim ContactMethod As ContactMethodInfo
  Dim jsonClientEmployment As finClientEmployment.jsonHtmlWidgetClientEmployment
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  client = finBL.CreateClient()

  ' Update Account Client
  If Success AndAlso parameters IsNot Nothing Then
    With client
      ' New
      Success = (.ClientGroupIdSet(parameters.ClientGroup) AndAlso .ClientTypeIdSet(parameters.ClientType))

      If Success Then
        ' General
        .Name = parameters.OrganisationName
        .LegalName = parameters.LegalName
        .BranchId = parameters.Branch
        .ClientManagerUserId = parameters.Manager
        .BusinessNumber = parameters.BusinessNumber
        .TaxNumber = parameters.TaxNumber
        .GstNumber = parameters.GstNumber
        .OrganisationNumber = parameters.OrganisationNumber
        .CommencementDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.CommencementDate)

        .ClientId = parameters.ClientCode
        If finBL.SettingsUser.ClientShowExternalId Then
          .ExternalId = parameters.ExternalId        
        End If
        If finBL.SettingsUser.ClientShowCrossReference Then
          .CrossReference = parameters.CrossReference
        End If
        
        If .ClientType.UseIndustryCode Then
          .IndustryCode = parameters.IndustryCode
        Else
          .IndustryCode = ""
        End If

        .Title = parameters.Title
        .FirstName = parameters.FirstName
        .MiddleNames = parameters.MiddleNames
        .LastName = parameters.LastName
        .PreferredName = parameters.PreferredName
        .GenderText = parameters.Gender
        .MaritalStatus = parameters.MaritalStatus
        .DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateOfBirth)

        If .IsSoleTrader Then
          .Occupation = parameters.Occupation
        Else
          .JobTitle = parameters.JobTitle
        End If

        If .ClientGroup.NewWizardShowOtherInformation Then
          .CommunicationGeneral = parameters.CommunicationGeneral
          .CommunicationGeneralEmail = parameters.CommunicationGeneralEmail
          .CommunicationGeneralLetter = parameters.CommunicationGeneralLetter
          .CommunicationGeneralPhoneVoice = parameters.CommunicationGeneralPhone
          .CommunicationGeneralSms = parameters.CommunicationGeneralSms
          .CommunicationMarketing = parameters.CommunicationMarketing
          .CommunicationMarketingEmail = parameters.CommunicationMarketingEmail
          .CommunicationMarketingLetter = parameters.CommunicationMarketingLetter
          .CommunicationMarketingPhoneVoice = parameters.CommunicationMarketingPhone
          .CommunicationMarketingSms = parameters.CommunicationMarketingSms
          .CommunicationOther1 = parameters.CommunicationOther1
          .CommunicationOther2 = parameters.CommunicationOther2
          .CommunicationOther3 = parameters.CommunicationOther3
          .CommunicationOther4 = parameters.CommunicationOther4
          .CreditRating = parameters.CreditRating
          .GstExempt = parameters.GstExempt
          .PassCode = parameters.PassCode
          .Status = finBL.Enums.isefinClientStatus_FromString(parameters.Status)

          ' Akas
          If finBL.Settings.AddOns.ClientAdvanced Then
            For Each Aka In parameters.Akas
              If Not CreateClient_Aka(Aka, client) Then
                Success = False
                Exit For
              End If
            Next
          End If
        End If

        ' Contact Methods
        If Success AndAlso .ClientGroup.NewWizardShowContactMethods Then
          For Each ContactMethod In parameters.ContactMethods
            With ContactMethod
              AddContactMethod(client, ContactMethod)
            End With
          Next
        End If

        ' Contact Addresses
        If Success AndAlso .ClientGroup.NewWizardShowAddresses Then
          Success = AddContactAddress(client, .ClientGroup.PostalContactMethodPk, parameters.PostalAddressJson, True, parameters.PostalAndPhysicalAddressSame)
          If Success AndAlso Not parameters.PostalAndPhysicalAddressSame Then
            Success = AddContactAddress(client, .ClientGroup.PhysicalContactMethodPk, parameters.PhysicalAddressJson, False, True)
          End If
        End If

        ' Identification
        If Success AndAlso .ClientGroup.NewWizardShowIdentification Then
          Success = AddIdentification(client, parameters.Identification)
        End If

        ' Employments
        If Success AndAlso .ClientGroup.NewWizardShowEmployment AndAlso finBL.Settings.AddOns.ClientAdvanced AndAlso finBL.CurrentUser.Permissions.Allow("Client.Employments.Add") Then
          For Each jsonClientEmployment In parameters.Employments
            ClientEmployment = .Employments.CreateClientEmployment()
            
            If ClientEmployment.FromHtmlWidgetJsonObject(jsonClientEmployment) Then
              Success = client.Employments.Add(ClientEmployment)
            Else 
              Success = False
            End If
            
            ' Exit if error
            If Not Success Then Exit For
          Next 
        End If        
        
        ' Statistics
        If Success AndAlso .ClientGroup.NewWizardShowStatistics Then
          If Len(parameters.ClientStatisticsSetJson) &lt;&gt; 0 Then
            ClientStatisticsSet = client.StatisticsSets.CreateClientStatisticsSet()
            If ClientStatisticsSet.FromHtmlWidgetJsonString(parameters.ClientStatisticsSetJson) Then
              client.StatisticsSets.Add(ClientStatisticsSet)
            Else
              Success = False
            End If
          End If
        End If

        ' Bank Account
        If Success AndAlso .ClientGroup.NewWizardShowBankingDetails Then
          Success = AddBankAccount(client, parameters.BankingDetails)
        End If

        ' Tax Information
        If Success AndAlso .ClientGroup.NewWizardShowTaxInformation Then
          .Resident = parameters.Resident
          .TaxCategoryId = parameters.TaxCategoryId
          .ExemptionCertificate = parameters.ExemptionCertificate
          .ExemptionIssueDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.ExemptionIssueDate)
          .ExemptionExpiryDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.ExemptionExpiryDate)
          .TaxCountry = parameters.TaxCountry
          .TaxForeignReference = parameters.TaxForeignReference
        End If

        ' Web Access
        If Success AndAlso .ClientGroup.NewWizardShowWebAccess Then
          .WebAccess = parameters.AllowWebAccess
          .WebUserId = parameters.WebUserId
          .WebPasswordForceChange = parameters.ForcePasswordChange
          If Len(parameters.UserDataWebJson) &lt;&gt; 0 Then .UserDataWeb.UpdateFromSimpleJsonString(parameters.UserDataWebJson)
          If Len(parameters.WebPassword) &lt;&gt; 0 Then Success = .WebPasswordSet(parameters.WebPassword, False)
        End If

        ' Date Review
        If Success Then
          .DateReview = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateReview)
        End If
        
        ' User Defined
        If Success AndAlso .ClientGroup.NewWizardShowUserDefinedResolved AndAlso Len(parameters.UserDataJson) &lt;&gt; 0 Then
          .UserData.FromHtmlWidgetParametersJsonString(parameters.UserDataJson)
        End If
      End If
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Client Aka.
''' &lt;/summary&gt;
Private Function CreateClient_Aka(aka As Aka,
                                  ByRef client As finClient) As Boolean

  Dim ClientAka As finClientAka
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  ClientAka = client.Akas.CreateClientAka()

  ' Build Aka
  With ClientAka
    .Name = aka.Name
    .Notes = aka.Notes
  End With

  ' Add to Client
  Success = client.Akas.Add(ClientAka)

  Return Success

End Function

''' &lt;summary&gt;
'''  Creates a Client Identification Item.
''' &lt;/summary&gt;
Private Function CreateClient_IdentificationItem(specialType As isefinIdentificationTypeSpecialType,
                                                 identification As Identification,
                                                 isValidating As Boolean,
                                                 ByRef clientIdentificationItem As finClientIdentificationItem) As Boolean

  Dim Client As finClient
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  clientIdentificationItem = Nothing

   ' Get Client
  Success = CreateClient(Nothing, Client)

  ' Date of Birth (for validation purposes only)
  If Success Then
    Client.DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.DateOfBirth)
  End If

  ' Populate
  If Success Then
    Select Case specialType
      Case isefinIdentificationTypeSpecialType.AU_DriversLicence
        ' AU Drivers Licence
        If isValidating OrElse (Len(identification.DL_State) &lt;&gt; 0 OrElse Len(identification.DL_LicenceNumber) &lt;&gt; 0) Then
          clientIdentificationItem = Client.IdentificationItems.CreateClientIdentificationItem()

          If clientIdentificationItem.IdentificationTypeIdSet(finBL.Settings.DriversLicenceIdentificationTypeId) Then
            With clientIdentificationItem.AU_DriversLicence
              .Address = identification.DL_Address
              .DateExpiry = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.DL_DateExpiry)
              .DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.DL_DateOfBirth)
              .FamilyName = identification.DL_FamilyName
              .LicenceNumber = identification.DL_LicenceNumber
              .CardNumber = identification.DL_CardNumber
              .OtherNames = identification.DL_OtherNames
              .State = identification.DL_State
            End With
          Else
            Success = False
          End If
        End If

      Case isefinIdentificationTypeSpecialType.AU_Medicare
        ' AU Medicare
        If isValidating OrElse (Len(identification.Medicare_Colour) &lt;&gt; 0 OrElse Len(identification.Medicare_CardNumber) &lt;&gt; 0 OrElse Len(identification.Medicare_IndividualReference) &lt;&gt; 0) Then
          clientIdentificationItem = Client.IdentificationItems.CreateClientIdentificationItem()

          If clientIdentificationItem.IdentificationTypeIdSet(finBL.Settings.MedicareIdentificationTypeId) Then
            With clientIdentificationItem.AU_Medicare
              .CardName = identification.Medicare_CardName
              .CardNumber = identification.Medicare_CardNumber
              .Colour = identification.Medicare_Colour
              .DateExpiry = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Medicare_DateExpiry)
              .IndividualReference = identification.Medicare_IndividualReference
            End With
          Else
            Success = False
          End If
        End If

      Case isefinIdentificationTypeSpecialType.AU_Passport
        ' AU Passport
        If isValidating OrElse Len(identification.Passport_PassportNumber) &lt;&gt; 0 Then
          clientIdentificationItem = Client.IdentificationItems.CreateClientIdentificationItem()

          If clientIdentificationItem.IdentificationTypeIdSet(finBL.Settings.PassportIdentificationTypeId) Then
            With clientIdentificationItem.AU_Passport
              .DateExpiry = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateExpiry)
              .DateIssue = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateIssue)
              .DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateOfBirth)
              .GivenNames = identification.Passport_GivenNames
              .DocumentNumber = identification.Passport_PassportNumber
              .FamilyName = identification.Passport_Surname
            End With
          Else
            Success = False
          End If
        End If

      Case isefinIdentificationTypeSpecialType.NZ_DriversLicence
        ' NZ Drivers Licence
        If isValidating OrElse (Len(identification.DL_LicenceNumber) &lt;&gt; 0 OrElse Len(identification.DL_VersionNumber) &lt;&gt; 0) Then
          clientIdentificationItem = Client.IdentificationItems.CreateClientIdentificationItem()

          If clientIdentificationItem.IdentificationTypeIdSet(finBL.Settings.DriversLicenceIdentificationTypeId) Then
            With clientIdentificationItem.NZ_DriversLicence
              .DateExpiry = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.DL_DateExpiry)
              .DateIssue = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.DL_DateIssue)
              .DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.DL_DateOfBirth)
              .FamilyName = identification.DL_FamilyName
              .LicenceNumber = identification.DL_LicenceNumber
              .OtherNames = identification.DL_OtherNames
              .VersionNumber = identification.DL_VersionNumber
            End With
          Else
            Success = False
          End If
        End If

      Case isefinIdentificationTypeSpecialType.NZ_Passport
        ' NZ Passport
        If isValidating OrElse Len(identification.Passport_PassportNumber) &lt;&gt; 0 Then
          clientIdentificationItem = Client.IdentificationItems.CreateClientIdentificationItem()

          If clientIdentificationItem.IdentificationTypeIdSet(finBL.Settings.PassportIdentificationTypeId) Then
            With clientIdentificationItem.NZ_Passport
              .DateExpiry = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateExpiry)
              .DateIssue = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateIssue)
              .DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateOfBirth)
              .GivenNames = identification.Passport_GivenNames
              .PassportNumber = identification.Passport_PassportNumber
              .Surname = identification.Passport_Surname
            End With
          Else
            Success = False
          End If
        End If

      Case isefinIdentificationTypeSpecialType.US_DriversLicence
        ' US Drivers Licence
        If isValidating OrElse (Len(identification.DL_LicenceNumber) &lt;&gt; 0 OrElse Len(identification.DL_VersionNumber) &lt;&gt; 0) Then
          clientIdentificationItem = Client.IdentificationItems.CreateClientIdentificationItem()

          If clientIdentificationItem.IdentificationTypeIdSet(finBL.Settings.DriversLicenceIdentificationTypeId) Then
            With clientIdentificationItem.US_DriversLicence
              .DateExpiry = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.DL_DateExpiry)
              .DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.DL_DateOfBirth)
              .Surname = identification.DL_FamilyName
              .LicenceNumber = identification.DL_LicenceNumber
              .OtherNames = identification.DL_OtherNames
              .Address = identification.DL_Address
              .GenderText = identification.DL_Gender
              .State = identification.DL_State
            End With
          Else
            Success = False
          End If
        End If

      Case isefinIdentificationTypeSpecialType.US_Passport
        ' US Passport
        If isValidating OrElse Len(identification.Passport_PassportNumber) &lt;&gt; 0 Then
          clientIdentificationItem = Client.IdentificationItems.CreateClientIdentificationItem()

          If clientIdentificationItem.IdentificationTypeIdSet(finBL.Settings.PassportIdentificationTypeId) Then
            With clientIdentificationItem.US_Passport
              .DateExpiry = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateExpiry)
              .DateIssue = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateIssue)
              .DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(identification.Passport_DateOfBirth)
              .GivenNames = identification.Passport_GivenNames
              .PassportNumber = identification.Passport_PassportNumber
              .Surname = identification.Passport_Surname
            End With
          Else
            Success = False
          End If
        End If
    End Select
  End If

  ' Clear if no values have been entered
  If Success Then
    If Not CreateClient_IdentificationItem_HasValue(clientIdentificationItem) Then
      clientIdentificationItem = Nothing
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Determines if the Client Identification Item has any values populated at all.
''' &lt;/summary&gt;
Private Function CreateClient_IdentificationItem_HasValue(clientIdentificationItem As finClientIdentificationItem) As Boolean

  If clientIdentificationItem Is Nothing Then
    Return False
  ElseIf clientIdentificationItem.IdentificationTypePk = 0 Then
    Return False
  Else
    Select Case clientIdentificationItem.IdentificationType.SpecialType
      Case isefinIdentificationTypeSpecialType.None
        ' None
        Return False

      Case isefinIdentificationTypeSpecialType.AU_DriversLicence
        ' AU Drivers Licence
        With clientIdentificationItem.AU_DriversLicence
          If Len(.Address) = 0 Then
            If .DateExpiry = Nothing Then
              If .DateOfBirth = Nothing Then
                If Len(.FamilyName) = 0 Then
                  If Len(.LicenceNumber) = 0 Then
                    If Len(.OtherNames) = 0 Then
                      If Len(.State) = 0 Then
                        Return False
                      End If
                    End If
                  End If
                End If
              End If
            End If
          End If
        End With

      Case isefinIdentificationTypeSpecialType.AU_Medicare
        ' Medicare
        With clientIdentificationItem.AU_Medicare
          If Len(.CardName) = 0 Then
            If Len(.CardNumber) = 0 Then
              If Len(.Colour) = 0 Then
                If .DateExpiry = Nothing Then
                  If Len(.IndividualReference) = 0 Then
                    Return False
                  End If
                End If
              End If
            End If
          End If
        End With

      Case isefinIdentificationTypeSpecialType.AU_Passport
        ' AU Passport
        With clientIdentificationItem.AU_Passport
          If .DateExpiry = Nothing Then
            If .DateIssue = Nothing Then
              If .DateOfBirth = Nothing Then
                If Len(.GivenNames) = 0 Then
                  If Len(.DocumentNumber) = 0 Then
                    If Len(.FamilyName) = 0 Then
                      Return False
                    End If
                  End If
                End If
              End If
            End If
          End If
        End With

      Case isefinIdentificationTypeSpecialType.NZ_DriversLicence
        ' NZ Drivers Licence
        With clientIdentificationItem.NZ_DriversLicence
          If .DateExpiry = Nothing Then
            If .DateIssue = Nothing Then
              If .DateOfBirth = Nothing Then
                If Len(.FamilyName) = 0 Then
                  If Len(.LicenceNumber) = 0 Then
                    If Len(.OtherNames) = 0 Then
                      If Len(.VersionNumber) = 0 Then
                        Return False
                      End If
                    End If
                  End If
                End If
              End If
            End If
          End If
        End With

      Case isefinIdentificationTypeSpecialType.NZ_Passport
        ' NZ Passport
        With clientIdentificationItem.NZ_Passport
          If .DateExpiry = Nothing Then
            If .DateIssue = Nothing Then
              If .DateOfBirth = Nothing Then
                If Len(.GivenNames) = 0 Then
                  If Len(.PassportNumber) = 0 Then
                    If Len(.Surname) = 0 Then
                      Return False
                    End If
                  End If
                End If
              End If
            End If
          End If
        End With

      Case isefinIdentificationTypeSpecialType.US_DriversLicence
        ' US Drivers Licence
        With clientIdentificationItem.US_DriversLicence
          If .DateExpiry = Nothing Then
            If .DateOfBirth = Nothing Then
              If Len(.Surname) = 0 Then
                If Len(.LicenceNumber) = 0 Then
                  If Len(.OtherNames) = 0 Then
                    If Len(.Address) = 0 Then
                      If Len(.GenderText) = 0 OrElse .Gender = isefinGender.Unknown Then
                        If Len(.State) = 0 Then
                          Return False
                        End If
                      End If
                    End If
                  End If
                End If
              End If
            End If
          End If
        End With

      Case isefinIdentificationTypeSpecialType.US_Passport
        ' US Passport
        With clientIdentificationItem.US_Passport
          If .DateExpiry = Nothing Then
            If .DateIssue = Nothing Then
              If .DateOfBirth = Nothing Then
                If Len(.GivenNames) = 0 Then
                  If Len(.PassportNumber) = 0 Then
                    If Len(.Surname) = 0 Then
                      Return False
                    End If
                  End If
                End If
              End If
            End If
          End If
        End With
    End Select
  End If

  Return True

End Function

''' &lt;summary&gt;
'''  Add a Contact Method to a Client.
''' &lt;/summary&gt;
Private Function AddContactMethod(client As finClient,
                                  contactMethod As ContactMethodInfo) As Boolean

  Dim ClientContactMethod As finClientContactMethod
  Dim ContactMethodId As String
  Dim strTemp As String
  Dim Success As Boolean
  Dim Value As String

  ' Assume Success
  Success = True

  ' Get Contact Method
  If finBL.ContactMethods.ExistsPk(contactMethod.Pk) Then
    ContactMethodId = finBL.ContactMethods.ItemByPk(contactMethod.Pk).ContactMethodId
  End If

  ' Create Client Contact Method
  If contactMethod.ClientContactMethod IsNot Nothing AndAlso contactMethod.ClientContactMethod.ContactMethodPk &lt;&gt; 0 Then
    ' ===============================================
    ' Add Contacts from the full Contact Methods list
    ' ===============================================
    If Len(contactMethod.ClientContactMethod.Value) &lt;&gt; 0 OrElse Len(contactMethod.ClientContactMethod.LinkedClientId) &lt;&gt; 0 Then
      ' Create
      ClientContactMethod = client.ContactMethods.CreateClientContactMethod()
      
      ' Add
      If ClientContactMethod.FromHtmlWidgetJsonObject(contactMethod.ClientContactMethod) Then
        Success = client.ContactMethods.Add(ClientContactMethod)
      Else 
        Success = False
      End If
    End If    
    
  ElseIf Len(contactMethod.Value) &lt;&gt; 0 AndAlso Len(ContactMethodId) &lt;&gt; 0 Then
    ' ==========================================================
    ' Add Contacts from the flattened list (on the General page)
    ' ==========================================================
    ' Create
    ClientContactMethod = client.ContactMethods.CreateClientContactMethod()

    ' Set Value
    Value = contactMethod.Value
    
    ' Update
    With ClientContactMethod
      If .ContactMethodIdSet(ContactMethodId) Then
        ' Format Value
        Select Case .ContactMethod.ContactType
          Case isefinContactType.Phone
            If .ContactMethod.FormatPhoneNumbers Then
              strTemp = finBL.CurrentCountry.FormatPhoneNumber(Value)
              If Len(strTemp) = 0 Then
                ' Did not format as a Phone Number so preserve original value
              Else
                ' Update formatted value
                Value = strTemp
              End If
            End If
        End Select

        .Value = Value
      Else
        Success = False
      End If
    End With

    ' Add
    If Success Then Success = client.ContactMethods.Add(ClientContactMethod)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Add a Bank Account to a Client.
''' &lt;/summary&gt;
Private Function AddBankAccount(client As finClient,
                                bankingInformation As BankingDetails) As Boolean

  Dim BankingDetails As finBankingDetails
  Dim ClientBankAccount As finClientBankAccount
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  BankingDetails = finBL.CreateBankingDetails()

  ' Populate object
  If BankingDetails.FromHtmlWidgetJsonString(bankingInformation.BankingDetailsJson) Then
    If Not BankingDetails.HasValue Then Return True
  Else
    Success = False
  End If

  ' Add other details
  If Success Then
    ClientBankAccount = client.BankAccounts.CreateClientBankAccount()
    With ClientBankAccount
      .FromBankingDetails(BankingDetails)
      .CreditLimit = bankingInformation.CreditLimit
      .DateStart = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(bankingInformation.DateStart)
      .DebitLimit = bankingInformation.DebitLimit
      .FriendlyName = bankingInformation.FriendlyName
      .Notes = bankingInformation.Notes
      .ShowExternally = bankingInformation.ShowExternally
    End With

    ' Add
    Success = client.BankAccounts.Add(ClientBankAccount)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Add a Contact Address to a Client.
''' &lt;/summary&gt;
Private Function AddContactAddress(client As finClient,
                                   contactMethodPk As Integer,
                                   contactAddressJson As String,
                                   postal As Boolean,
                                   physical As Boolean) As Boolean

  Dim ClientContactAddress As finClientContactAddress
  Dim ContactMethodId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  If finBL.ContactMethods.ExistsPk(contactMethodPk) Then
    ContactMethodId = finBL.ContactMethods.ItemByPk(contactMethodPk).ContactMethodId
  End If

  If Len(ContactMethodId) &lt;&gt; 0 AndAlso Len(contactAddressJson) &lt;&gt; 0 Then
    ' Create
    ClientContactAddress = client.ContactAddresses.CreateClientContactAddress()

    ' Update
    With ClientContactAddress
      If .ContactMethodIdSet(ContactMethodId) Then
        .FromAddressDetailsHtmlWidgetJsonString(contactAddressJson)
        .AddressPostal = postal
        .AddressPhysical = physical
      Else
        Success = False
      End If
    End With

    ' Add
    If Success Then 
      If ClientContactAddress.HasValues() Then
        Success = client.ContactAddresses.Add(ClientContactAddress)
      End If      
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Add Identification.
''' &lt;/summary&gt;
Private Function AddIdentification(client As finClient,
                                   identification As Identification) As Boolean

  Dim ClientIdentificationItem As finClientIdentificationItem
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Drivers Licence
  If finBL.Settings.IsIdentificationValidDriversLicence(False) Then
    Select Case finBL.CountryCode
      Case "AU": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.AU_DriversLicence, identification, False, ClientIdentificationItem)
      Case "NZ": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.NZ_DriversLicence, identification, False, ClientIdentificationItem)
      Case "US": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.US_DriversLicence, identification, False, ClientIdentificationItem)
    End Select

    If Success AndAlso ClientIdentificationItem IsNot Nothing Then
      Success = client.IdentificationItems.Add(ClientIdentificationItem)
    End If
  End If

  ' Medicare
  If finBL.Settings.IsIdentificationValidMedicare(False) Then
    Select Case finBL.CountryCode
      Case "AU": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.AU_Medicare, identification, False, ClientIdentificationItem)
      Case Else: ClientIdentificationItem = Nothing
    End Select

    If Success AndAlso ClientIdentificationItem IsNot Nothing Then
      Success = client.IdentificationItems.Add(ClientIdentificationItem)
    End If
  End If

  ' Passport
  If finBL.Settings.IsIdentificationValidPassport(False) Then
    Select Case finBL.CountryCode
      Case "AU": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.AU_Passport, identification, False, ClientIdentificationItem)
      Case "NZ": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.NZ_Passport, identification, False, ClientIdentificationItem)
      Case "US": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.US_Passport, identification, False, ClientIdentificationItem)
    End Select

    If Success AndAlso ClientIdentificationItem IsNot Nothing Then
      Success = client.IdentificationItems.Add(ClientIdentificationItem)
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Generate a new strong Web Password.
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Public Function GeneratePassword(ByRef returnValue As String) As Boolean

  ' Generate Strong Password
  Return finBL.Security.CreateStrongPassword(finBL.Settings.ClientWebPasswordMinLength, "", returnValue, finBL.Settings.PasswordExcludeConfusingLetters)

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 BranchId As String
  Dim ClientGroupId As String
  Dim ClientGroupInfo As ClientGroupInfo
  Dim ClientGroupRO As finClientGroupRO
  Dim ClientType As finClientTypeRO
  Dim ContactMethodRO As finContactMethodRO
  Dim DefaultName As String
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ManagerUserId As String
  Dim Priority As Boolean
  Dim PriorityIndex As Integer
  Dim PriorityList As ISList
  Dim strTemp As String
  Dim Success As Boolean
  Dim TaxCategoryRO As finTaxCategoryRO

  ' Assume Success
  Success = True

  ' Combined Parameters
  With mCombinedParameters
    ClientGroupId = .GetString("ClientGroupId")
    If Len(ClientGroupId) = 0 Then ClientGroupId = finBL.SettingsUser.DefaultClientGroupIdResolved
    BranchId = .GetString("BranchId")
    If Len(BranchId) = 0 Then BranchId = finBL.SettingsUser.DefaultClientBranchIdResolved
    ManagerUserId = .GetString("ManagerUserId")
    DefaultName = .GetString("DefaultName")
  End With

  ' Validate
  If Len(BranchId) &lt;&gt; 0 AndAlso Not finBL.Branches.Exists(BranchId) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Branch '{0}' does not exist.", BranchId)
  ElseIf Len(ClientGroupId) &lt;&gt; 0 AndAlso Not finBL.ClientGroups.Exists(ClientGroupId) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Client Group '{0}' does not exist.", ClientGroupId)
  ElseIf Len(ClientGroupId) &lt;&gt; 0 AndAlso (Not finBL.ClientGroups(ClientGroupId).Active OrElse finBL.ClientGroups(ClientGroupId).HideInNewClientWizard) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Client Group '{0}' is not configured for use in the New Client Wizard.", ClientGroupId)
  ElseIf Not finBL.ClientGroups.HasClientGroupsForNewClientWizard() Then
    Success = False
    finBL.Error.ErrorBegin("There are no Client Groups configured for use in the New Client wizard.")
  ElseIf Len(ManagerUserId) &lt;&gt; 0 AndAlso Not finBL.Users.Exists(ManagerUserId) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Manager. User '{0}' does not exist.", ManagerUserId)
  ElseIf Len(ManagerUserId) &lt;&gt; 0 AndAlso Not finBL.Users(ManagerUserId).IsManager Then
    Success = False
    finBL.Error.ErrorBeginFormat("User '{0}' is not a Manager.", ManagerUserId)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      .BranchId = BranchId
      If finBL.Branches.Exists(BranchId) Then .BranchPk = finBL.Branches(BranchId).Pk

      .ClientGroupId = ClientGroupId

      ' Manager
      .ManagerUserId = ManagerUserId
      If Len(.ManagerUserId) = 0 Then .ManagerUserId = finBL.SettingsUser.DefaultClientManagerUserId

      .DefaultName = DefaultName
        
      ' Lists
      Select Case finBL.CountryCode
        Case "AU"
          .AU_DL_StatesList = DirectCast(finBL.SupportedCountries("AU"), finSupportedCountryAU).GetDriversLicenceStateList().ToCsvString()
          .AU_MedicareColourList = DirectCast(finBL.SupportedCountries("AU"), finSupportedCountryAU).GetMedicareCardColourList().ToCsvString()

        Case "US"
          .US_DL_StatesList = finBL.Addressing.GetStatesList("US").ToCsvString()
      End Select

      .ClientGroupFilter = finBL.ClientGroups.GetDataViewFilter(True, False)
      .GendersList = finBL.Enums.isefinGender_GetList.ToCsvString()
      .StatusesList = finBL.Enums.isefinClientStatus_GetList().ToCsvString()

      ' Contact Methods
      For Each ContactMethodRO In finBL.ContactMethods
        If ContactMethodRO.Active Then
          Select Case ContactMethodRO.ContactType
            Case isefinContactType.Address
              ' Do not include
            Case Else
              .ContactMethods.Add(New ContactMethodInfo(ContactMethodRO))
          End Select
        End If
      Next

      ' Client Groups
      For Each ClientGroupRO In finBL.ClientGroups
        If ClientGroupRO.Active AndAlso Not ClientGroupRO.HideInNewClientWizard Then
          .ClientGroups.Add(New ClientGroupInfo(ClientGroupRO))
        End If
      Next

      ' Client Types
      PriorityList = New ISList(mCombinedParameters.GetString("PriorityClientTypes"))
      For Each ClientType In finBL.ClientTypes
        If ClientType.Active AndAlso ClientType.IsOrganisation Then
          ' Priority?
          PriorityIndex = PriorityList.IndexOf(ClientType.ClientTypeId, True)
          Priority = PriorityIndex &lt;&gt; -1

          .ClientTypes.Add(New ClientTypeInfo(ClientType, Priority, PriorityIndex))
        End If
      Next

      ' Tax Categories
      For Each TaxCategoryRO In finBL.TaxCategories
        If TaxCategoryRO.Active Then
          .TaxCategories.Add(New TaxCategoryInfo(TaxCategoryRO))
        End If
      Next

      ' Advanced Sections
      .ShowBranch = mCombinedParameters.GetString("ShowBranch") : If Len(.ShowBranch) = 0 Then .ShowBranch = "Advanced"
      If Not finBL.Settings.AddOns.Branch Then
        .ShowBranch = "False"
      ElseIf Len(BranchId) = 0 Then
         .ShowBranch = "True"
      End If
      .ShowCrossReference = mCombinedParameters.GetString("ShowCrossReference") : If Len(.ShowCrossReference) = 0 Then .ShowCrossReference = "Advanced"
      If Not finBL.SettingsUser.ClientShowCrossReference Then
        .ShowCrossReference = "False"  
      End If
      .ShowClientCode = mCombinedParameters.GetString("ShowClientCode") : If Len(.ShowClientCode) = 0 Then .ShowClientCode = "Advanced"
      .ShowExternalId = mCombinedParameters.GetString("ShowExternalId") : If Len(.ShowExternalId) = 0 Then .ShowExternalId = "Advanced"
      If Not finBL.SettingsUser.ClientShowExternalId Then
        .ShowExternalId = "False"  
      End If
      .ShowClientGroup = mCombinedParameters.GetString("ShowClientGroup") : If Len(.ShowClientGroup) = 0 Then .ShowClientGroup = "Advanced"
      If Len(.ClientGroupId) = 0 Then
        .ShowClientGroup = "True"
      End If
      .ShowManager = mCombinedParameters.GetString("ShowManager") : If Len(.ShowManager) = 0 Then .ShowManager = "Advanced"
      If Len(.ManagerUserId) = 0 Then
        .ShowManager = "True"
      End If
      .ShowOtherBankingDetails = mCombinedParameters.GetString("ShowOtherBankingDetails") : If Len(.ShowOtherBankingDetails) = 0 Then .ShowOtherBankingDetails = "Advanced"
      .ShowAkas = mCombinedParameters.GetString("ShowAkas") : If Len(.ShowAkas) = 0 Then .ShowAkas = "Advanced"
      If Not finBL.Settings.AddOns.ClientAdvanced Then
        .ShowAkas = "False"
      End If
      
      ' Advanced Pages
      .PageBankingHasAdvanced = (.ShowOtherBankingDetails = "Advanced")
      .PageGeneralHasAdvanced = (.ShowCrossReference = "Advanced" OrElse .ShowExternalId = "Advanced" OrElse .ShowClientGroup = "Advanced" OrElse .ShowBranch = "Advanced" OrElse .ShowManager = "Advanced" OrElse .ShowAkas = "Advanced")

      ' Configuration
      .AllowCompanyLookup = finBL.CreditBureau.CanPerformCompanyLookup() AndAlso (finBL.CountryCode = "AU" OrElse finBL.CountryCode = "NZ")
      .CanEdit = mCombinedParameters.GetBoolean("CanEdit", True)
      .ClientStatisticsWidgetId = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientStatisticsSet, False)
      .CommunicationOtherText = finBL.Settings.ClientProfileOtherHeadingResolved
      .CommunicationOther1Text = finBL.Settings.ClientProfileOther1Resolved
      .CommunicationOther2Text = finBL.Settings.ClientProfileOther2Resolved
      .CommunicationOther3Text = finBL.Settings.ClientProfileOther3Resolved
      .CommunicationOther4Text = finBL.Settings.ClientProfileOther4Resolved
      .DefaultCountry = finBL.CurrentCountry.CountryName
      .DefaultCountryCode = finBL.CountryCode
      .DOBMaxValue = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
      .DOBMinValue = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(New Date(1900, 1, 1))      
      .IconListStyle = LCase(mCombinedParameters.GetString("IconListStyle", "grid"))
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .ShowGst = finBL.Settings.UseGst
      .ShowNewRecordOnFinish = mCombinedParameters.GetBoolean("ShowNewRecordOnFinish", True)
      .WidgetClientContactMethod = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientContactMethod, mCombinedParameters.GetBoolean("UseBuiltInClientContactMethodHTMLWidget"), strTemp)
      .WidgetClientContactMethod_StartupParametersJson = strTemp
      .WidgetClientEmployment = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientEmployment, mCombinedParameters.GetBoolean("UseBuiltInClientEmploymentHTMLWidget"), strTemp)
      .WidgetClientEmployment_StartupParametersJson = strTemp
      
      ' Licence
      .AddonsClientAdvanced = finBL.Settings.AddOns.ClientAdvanced
      .AddonsSecurityRegisterPPSR = finBL.Settings.AddOns.SecurityRegisterPPSR

      ' Permissions
      .AkaCanAdd = finBL.CurrentUser.Permissions.Allow("Client.Akas.Add")
      .AkaCanDelete = finBL.CurrentUser.Permissions.Allow("Client.Akas.Delete")

      ' Identification
      .ShowIdentification_DL = (finBL.Settings.DriversLicenceIdentificationTypePk &lt;&gt; 0 AndAlso finBL.Settings.IsIdentificationValidDriversLicence(True, .ShowIdentification_DL_Warning))
      .ShowIdentification_Passport = (finBL.Settings.PassportIdentificationTypePk &lt;&gt; 0 AndAlso finBL.Settings.IsIdentificationValidPassport(True, .ShowIdentification_Passport_Warning))
      .ShowIdentification_Medicare = (finBL.Settings.MedicareIdentificationTypePk &lt;&gt; 0 AndAlso finBL.Settings.IsIdentificationValidMedicare(True, .ShowIdentification_Medicare_Warning))

      If finBL.CurrentUser.Permissions.Allow("Client.IdentificationItems.Paste") Then
        If .ShowIdentification_DL Then
          With finBL.IdentificationTypes.ItemByPk(finBL.Settings.DriversLicenceIdentificationTypePk)
            FormInitialisationInfo.ShowIdentification_DL_AllowDateOfBirthPaste = .AllowDateOfBirthPaste
            FormInitialisationInfo.ShowIdentification_DL_AllowNamePaste = .AllowNamePaste
          End With        
        End If
        
        If .ShowIdentification_Passport Then
          With finBL.IdentificationTypes.ItemByPk(finBL.Settings.PassportIdentificationTypePk)
            FormInitialisationInfo.ShowIdentification_Passport_AllowDateOfBirthPaste = .AllowDateOfBirthPaste
            FormInitialisationInfo.ShowIdentification_Passport_AllowNamePaste = .AllowNamePaste
          End With  
        End If
        
        If .ShowIdentification_Medicare Then
          With finBL.IdentificationTypes.ItemByPk(finBL.Settings.MedicareIdentificationTypePk)          
            FormInitialisationInfo.ShowIdentification_Medicare_AllowNamePaste = .AllowNamePaste
          End With
        End If
      End If  
      
      ' Terminology
      .Terminology_BusinessNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.BusinessNumber)
      .Terminology_CompanyNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.CompanyNumber)
      .Terminology_GSTNumberOrganisation = finBL.CurrentCountry.Terminology(isefinCountryTerminology.GSTNumberOrganisation)
      .Terminology_TaxNumberOrganisation = finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberOrganisation)
    End With
  End If

  ' Update Client Groups which allow Identification if there is no Identification to show
  If Success Then
    With FormInitialisationInfo
      If Not .ShowIdentification_DL AndAlso Not .ShowIdentification_Passport AndAlso Not .ShowIdentification_Medicare Then
        If Len(.ShowIdentification_DL_Warning) = 0 AndAlso Len(.ShowIdentification_Passport_Warning) = 0 AndAlso Len(.ShowIdentification_Medicare_Warning) = 0 Then
          For Each ClientGroupInfo In .ClientGroups
            ClientGroupInfo.ShowIdentificationPage = False
          Next
        End If
      End If
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Gets a List of potential Client Matches as a ReadOnlyList of finClientMatch
''' &lt;/summary&gt;
''' &lt;param name="finishParameters"&gt;
'''  Wizard Finish Parameters
''' &lt;/param&gt;
''' &lt;param name="matches"&gt;
'''  List of Client Matches
''' &lt;/param&gt;
''' &lt;returns&gt;
'''  Success
''' &lt;/returns&gt;
Function GetClientMatches(finishParameters As WizardFinishParameters,
                          ByRef matches As ISReadOnlyList(Of finClientMatch)) As Boolean
                       
  Dim Client As finClient                                
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  Client = finBL.CreateClient()
  
  If Success Then
    ' Create temporary Client for Validation
    Success = CreateClient(finishParameters, Client)
  End If
  
  If Success Then
    ' Get a list of Matches
    Success = finBL.ClientFunctions.GetMatches(Client, Matches)
  End If

  Return Success
                                
End Function       

''' &lt;summary&gt;
'''  Get Client Statistics Summary.
''' &lt;/summary&gt;
Private Function GetClientStatisticsSetSummary(parametersJson As String,
                                         ByRef returnValue As String) As Boolean

  Dim ClientStatisticsSetJson As String
  Dim Client As finClient
  Dim ClientStatisticsSet As finClientStatisticsSet
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Create Client Statistics Set
  If Success Then
    Client = finBL.CreateClient()
    ClientStatisticsSet = client.StatisticsSets.CreateClientStatisticsSet()

    ' Populate
    If ClientStatisticsSet.FromHtmlWidgetJsonString(ClientStatisticsSetJson) Then
      Client.StatisticsSets.Add(ClientStatisticsSet)
    Else
      Success = False
    End If

    ' Get Summary
    If Success Then
      returnValue = finBL.SummaryPageFunctions.ClientStatisticsSetSummary(False, Client, 0, finBL.HtmlWidgetUtilities.CreateScriptContextData(Me.ScriptInfo, FORM_KEY))
    End If
  End If

  ' Never return an error
  If Not Success Then
    Success = True
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get the HTML Summary Page for the active row on the Employments grid.
''' &lt;/summary&gt;
Private Function GetEmploymentItemPreview(ByRef returnValue As String) As Boolean

  Dim Client As finClient
  Dim ClientEmployment As finClientEmployment
  Dim ClientEmploymentJson As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  Client = finBL.CreateClient()

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

  ' Add Client Employment for Summary Page
  ClientEmployment = Client.Employments.CreateClientEmployment()
  If ClientEmployment.FromHtmlWidgetJsonString(ClientEmploymentJson) Then
    Success = Client.Employments.Add(ClientEmployment)
  Else 
    Success = False
  End If

  ' Get Summary
  If Success Then
    returnValue = finBL.SummaryPageFunctions.ClientEmploymentSummary(False, Client, 0, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
  End If
  
  ' Error
  If Not Success Then
    ' Error HTML
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message, finBL.Error.Details)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate Identification.
''' &lt;/summary&gt;
Private Function ValidateIdentification(ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  Dim WarningList As ISList

  ' Assume Success
  Success = True

  ' Validate
  Success = WizardValidate_Identification(True, WarningList)

  ' Serialise
  If Success Then
    returnValue = WarningList.ToDelimitedString(vbNewLine)
  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 Aka As Aka
  Dim Akas As List(Of Aka)
  Dim AkasJson As String
  Dim BankingDetails As BankingDetails
  Dim BankingDetailsForValidation As finBankingDetails
  Dim BankingDetailsJson As String
  Dim Client As finClient
  Dim CompanyNumber As String
  Dim ConfirmList As List(Of String)
  Dim ContactMethod As ContactMethodInfo
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim FinishParameters As WizardFinishParameters
  Dim List As ISList
  Dim Matches As ISReadOnlyList(Of finClientMatch)
  Dim obj As Object
  Dim PageId As String
  Dim strTemp As String
  Dim Success As Boolean
  Dim TaxNumber As String
  Dim Warning As ISValidationItem
  Dim Warnings As ISValidationItems

  ' 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
    AkasJson = .GetString("AkasJson")
    BankingDetailsJson = .GetString("BankingDetailsJson")
    CompanyNumber = .GetString("CompanyNumber")
    PageId = .GetString("PageId")
    TaxNumber = .GetString("TaxNumber")
  End With

  ' Initialise
  ConfirmList = New List(Of String)

  ' Validate Page
  Select Case PageId
    Case "General"
      If Len(TaxNumber) &lt;&gt; 0 AndAlso Not finBL.CurrentCountry.Validate(isefinCountryValidate.TaxNumberOrganisation, TaxNumber, "", "") Then
        ConfirmList.Add(String.Format("The {0} '{1}' appears to be invalid?", finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberOrganisation), TaxNumber))
      End If

      If Len(CompanyNumber) &lt;&gt; 0 AndAlso Not finBL.CurrentCountry.Validate(isefinCountryValidate.OrganisationNumber, CompanyNumber, "", "") Then
        ConfirmList.Add(String.Format("The {0} '{1}' appears to be invalid?", finBL.CurrentCountry.Terminology(isefinCountryTerminology.CompanyNumber), CompanyNumber))
      End If

      ' Akas
      If finBL.Settings.AddOns.ClientAdvanced AndAlso Len(AkasJson) &lt;&gt; 0 Then
        ' Create temporary Client for Validation
        Client = finBL.CreateClient()

        ' Deserialise
        If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(AkasJson, GetType(List(Of Aka)), obj) Then
          Akas = DirectCast(obj, List(Of Aka))
        Else
          Success = False
        End If

        ' Test and Validate
        If Success Then
          For Each Aka In Akas
            If Not CreateClient_Aka(Aka, Client) Then
              Success = False
              Exit For
            End If
          Next

          If Success AndAlso Not Client.Akas.Validate(FailedMessage) Then
            FailedControlId = "gridAkas"
          End If
        End If
      End If

      If Success Then
        Data = New With {
          .ConfirmList = ConfirmList
        }
      End If

    Case "ContactMethods"
      If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(WizardFinishParameters), obj) Then
        FinishParameters = DirectCast(obj, WizardFinishParameters)
      Else
        Success = False
      End If

      ' Confirm that Contact Value formatting is not an issue
      If Success Then
        For Each ContactMethod In FinishParameters.ContactMethods
          If finBL.ContactMethods.ExistsPk(ContactMethod.Pk) Then
            With finBL.ContactMethods.ItemByPk(ContactMethod.Pk)
              Select Case .ContactType
                Case isefinContactType.Phone
                  strTemp = "Phone"
                  If .ContactMobile Then strTemp = "Mobile"
                  If Not finBL.Runtime.Validation.IsValidPhoneNumber(ContactMethod.Value, "", True) Then ConfirmList.Add(String.Format("The {0} Number '{1}' appears to be invalid?", strTemp, ContactMethod.Value))
  
                Case isefinContactType.Email
                  If Not finBL.Runtime.Validation.IsValidEmailAddress(ContactMethod.Value, "", True) Then ConfirmList.Add(String.Format("The Email Address '{0}' appears to be invalid?", ContactMethod.Value))
              End Select
            End With
          End If
        Next
        
        ' Get Client Matches
        Success = GetClientMatches(FinishParameters, Matches)
      End If
      
      If Success Then
        Data = New With {
          .ConfirmList = ConfirmList,
          .ClientMatches = Matches
        }        
      End If

    Case "IdentificationAU", "IdentificationNZ", "IdentificationUS"
      ' Validate
      Success = WizardValidate_Identification(False, List)

      ' Data
      If Success Then
        Data = List.ToList()
      End If

    Case "BankingDetails"
      If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(BankingDetailsJson, GetType(BankingDetails), obj) Then
        BankingDetails = DirectCast(obj, BankingDetails)
      Else
        Success = False
      End If

      ' Validate Banking Details
      If Success Then
        BankingDetailsForValidation = finBL.CreateBankingDetails()

        If BankingDetailsForValidation.FromHtmlWidgetJsonString(BankingDetails.BankingDetailsJson) Then
          If BankingDetailsForValidation.HasValue AndAlso Not BankingDetailsForValidation.IsValid(Warnings) Then
            For Each Warning In Warnings
              ConfirmList.Add(Warning.Message)
            Next
          End If
        Else
          Success = False
        End If

        Data = New With {
          .ConfirmList = ConfirmList
        }
      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_Identification(showNumbering As Boolean,
                                               ByRef warningList As ISList) As Boolean

  Dim ClientIdentificationItem As finClientIdentificationItem
  Dim Identification As Identification
  Dim IdentificationJson As String
  Dim obj As Object
  Dim strTemp As String
  Dim Success As Boolean
  Dim ValidateDriversLicence As Boolean
  Dim ValidateMedicare As Boolean
  Dim ValidatePassport As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  warningList = finBL.Runtime.CreateList()

  ' Get Parameters
  With mCombinedParameters
    IdentificationJson = .GetString("IdentificationJson")
    ValidateDriversLicence = .GetBoolean("ValidateDriversLicence")
    ValidateMedicare = .GetBoolean("ValidateMedicare")
    ValidatePassport = .GetBoolean("ValidatePassport")
  End With

  ' Get Identification
  If ValidateDriversLicence OrElse ValidateMedicare OrElse ValidatePassport Then
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(IdentificationJson, GetType(Identification), obj) Then
      Identification = DirectCast(obj, Identification)
    Else
      Success = False
    End If
  End If

  ' Drivers Licence
  If Success AndAlso ValidateDriversLicence Then
    Select Case finBL.CountryCode
      Case "AU": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.AU_DriversLicence, Identification, True, ClientIdentificationItem)
      Case "NZ": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.NZ_DriversLicence, Identification, True, ClientIdentificationItem)
      Case "US": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.US_DriversLicence, Identification, True, ClientIdentificationItem)
    End Select

    ' Validate
    If Success AndAlso ClientIdentificationItem IsNot Nothing Then
      If showNumbering Then
        strTemp = ClientIdentificationItem.GetWarnings().GetListNumbered(,,, True).ToDelimitedString(vbNewLine)
      Else
        strTemp = ClientIdentificationItem.GetWarnings().GetList().ToDelimitedString(vbNewLine)
      End If

      ' Add to warnings
      If Len(strTemp) &lt;&gt; 0 Then warningList.Add(strTemp, True, True)
    End If
  End If

  ' Passport
  If Success AndAlso ValidatePassport Then
    Select Case finBL.CountryCode
      Case "AU": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.AU_Passport, Identification, True, ClientIdentificationItem)
      Case "NZ": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.NZ_Passport, Identification, True, ClientIdentificationItem)
      Case "US": Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.US_Passport, Identification, True, ClientIdentificationItem)
    End Select

    ' Validate
    If Success AndAlso ClientIdentificationItem IsNot Nothing Then
      If showNumbering Then
        strTemp = ClientIdentificationItem.GetWarnings().GetListNumbered(,,, True).ToDelimitedString(vbNewLine)
      Else
        strTemp = ClientIdentificationItem.GetWarnings().GetList().ToDelimitedString(vbNewLine)
      End If

      ' Add to warnings
      If Len(strTemp) &lt;&gt; 0 Then warningList.Add(strTemp, True, True)
    End If
  End If

  ' Medicare
  If Success AndAlso ValidateMedicare Then
    Select Case finBL.CountryCode
      Case "AU"
        Success = CreateClient_IdentificationItem(isefinIdentificationTypeSpecialType.AU_Medicare, Identification, True, ClientIdentificationItem)
      Case Else
        Success = False
        finBL.Error.ErrorBegin("Medicare is not supported in this country.")
    End Select

    ' Validate
    If Success AndAlso ClientIdentificationItem IsNot Nothing Then
      If showNumbering Then
        strTemp = ClientIdentificationItem.GetWarnings().GetListNumbered(,,, True).ToDelimitedString(vbNewLine)
      Else
        strTemp = ClientIdentificationItem.GetWarnings().GetList().ToDelimitedString(vbNewLine)
      End If

      ' Add to warnings
      If Len(strTemp) &lt;&gt; 0 Then warningList.Add(strTemp, True, True)
    End If
  End If

  Return Success

End Function



''' &lt;summary&gt;
'''  Banking Details.
''' &lt;/summary&gt;
Public Class BankingDetails

  Public BankingDetailsJson As String
  Public CreditLimit As Decimal
  Public DateStart As Date?
  Public DebitLimit As Decimal
  Public FriendlyName As String
  Public Notes As String
  Public ShowExternally As Boolean

End Class



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

  ' Record
  Public BranchId As String
  Public BranchPk As Integer
  Public ClientGroupId As String
  Public ClientTypeId As String
  Public DefaultName As String
  Public ManagerUserId As String

  ' Lists
  Public AU_DL_StatesList As String
  Public AU_MedicareColourList As String
  Public ClientGroupFilter As String
  Public ClientTypes As New List(Of ClientTypeInfo)
  Public GendersList As String
  Public StatusesList As String
  Public US_DL_StatesList As String

  ' Collections
  Public ClientGroups As New List(Of ClientGroupInfo)
  Public ContactMethods As New List(Of ContactMethodInfo)
  Public TaxCategories As New List(Of TaxCategoryInfo)

  ' Advanced Sections
  Public PageBankingHasAdvanced As Boolean
  Public PageGeneralHasAdvanced As Boolean
  Public ShowAkas As String
  Public ShowBranch As String
  Public ShowClientGroup As String
  Public ShowCrossReference As String
  Public ShowClientCode As String
  Public ShowExternalId As String
  Public ShowManager As String
  Public ShowOtherBankingDetails As String

  ' Configuration
  Public AllowCompanyLookup As Boolean
  Public CanEdit As Boolean
  Public ClientStatisticsWidgetId As String
  Public CommunicationOtherText As String
  Public CommunicationOther1Text As String
  Public CommunicationOther2Text As String
  Public CommunicationOther3Text As String
  Public CommunicationOther4Text As String
  Public DefaultCountry As String
  Public DefaultCountryCode As String
  Public DOBMaxValue As Date
  Public DOBMinValue As Date    
  Public IconListStyle As String
  Public PromptOnSave As Boolean
  Public ShowGst As Boolean
  Public ShowNewRecordOnFinish As Boolean
  Public ShowPasscode As Boolean
  Public WidgetClientContactMethod As String
  Public WidgetClientContactMethod_StartupParametersJson As String
  Public WidgetClientEmployment As String
  Public WidgetClientEmployment_StartupParametersJson As String

  ' Licence
  Public AddonsClientAdvanced As Boolean
  Public AddonsSecurityRegisterPPSR As Boolean

  ' Permissions
  Public AkaCanAdd As Boolean
  Public AkaCanDelete As Boolean

  ' Identification
  Public ShowIdentification_DL As Boolean
  Public ShowIdentification_DL_Warning As String
  Public ShowIdentification_DL_AllowDateOfBirthPaste As Boolean
  Public ShowIdentification_DL_AllowNamePaste As Boolean
  Public ShowIdentification_Passport As Boolean
  Public ShowIdentification_Passport_Warning As String
  Public ShowIdentification_Passport_AllowDateOfBirthPaste As Boolean
  Public ShowIdentification_Passport_AllowNamePaste As Boolean  
  Public ShowIdentification_Medicare As Boolean
  Public ShowIdentification_Medicare_Warning As String
  Public ShowIdentification_Medicare_AllowNamePaste As Boolean  

  ' Terminology
  Public Terminology_BusinessNumber As String
  Public Terminology_CompanyNumber As String
  Public Terminology_GST As String
  Public Terminology_GSTNumberOrganisation As String
  Public Terminology_TaxNumberOrganisation As String

End Class



''' &lt;summary&gt;
'''  Client Aka.
''' &lt;/summary&gt;
Public Class Aka

  Public Name As String
  Public Notes As String

End Class



''' &lt;summary&gt;
'''  Identification details.
''' &lt;/summary&gt;
Public Class Identification

  ' Shared
  Public DateOfBirth As Date?

  ' Drivers Licence
  Public DL_Address As String
  Public DL_DateExpiry As Date?
  Public DL_DateIssue As Date?
  Public DL_DateOfBirth As Date?
  Public DL_FamilyName As String
  Public DL_Gender As String
  Public DL_LicenceNumber As String
  Public DL_CardNumber As String
  Public DL_OtherNames As String
  Public DL_State As String
  Public DL_VersionNumber As String

  ' Passport
  Public Passport_DateExpiry As Date?
  Public Passport_DateIssue As Date?
  Public Passport_DateOfBirth As Date?
  Public Passport_GivenNames As String
  Public Passport_PassportNumber As String
  Public Passport_Surname As String

  ' Medicare
  Public Medicare_CardName As String
  Public Medicare_CardNumber As String
  Public Medicare_Colour As String
  Public Medicare_DateExpiry As Date?
  Public Medicare_IndividualReference As String

End Class



''' &lt;summary&gt;
'''  Client Group.
''' &lt;/summary&gt;
Public Class ClientGroupInfo

  Public BusinessNumberMandatory As Boolean
  Public ClientGroupId As String
  Public CompanyNumberMandatory As Boolean
  Public ContactMethods As New List(Of Integer)
  Public HasUserData As Boolean
  Public HasUserDataWeb As Boolean
  Public ShowBankingPage As Boolean
  Public ShowContactMethodsPage As Boolean
  Public ShowEmploymentsPage As Boolean
  Public ShowFullContactsGrid As Boolean
  Public ShowIdentificationPage As Boolean
  Public ShowImagePage As Boolean
  Public ShowOtherInfo As Boolean
  Public ShowStatisticsPage As Boolean
  Public ShowTaxPage As Boolean
  Public ShowUserDefinedPage As Boolean
  Public ShowWebAccessPage As Boolean
  Public SupportsContactMethods As Boolean
  Public SupportsPhysicalAddress As Boolean
  Public SupportsPostalAddress As Boolean
  Public TaxNumberMandatory As Boolean
  Public UserDefinedParameters As ISWsParameters
  Public UserDefinedWebParameters As ISWsParameters

  Public Sub New(clientGroupRO As finClientGroupRO)

    Dim ContactMethodRO As finContactMethodRO

    With clientGroupRO
      Me.BusinessNumberMandatory = .NewWizardOrganisationBusinessNumberMandatory
      Me.ClientGroupId = .ClientGroupId
      Me.CompanyNumberMandatory = .NewWizardOrganisationCompanyNumberMandatory
      Me.TaxNumberMandatory = .NewWizardOrganisationTaxNumberMandatory

      ' Contact Addresses
      If .NewWizardShowAddresses Then
        Me.SupportsPhysicalAddress = (.PhysicalContactMethodPk &lt;&gt; 0)
        Me.SupportsPostalAddress = (.PostalContactMethodPk &lt;&gt; 0)
      End If

      ' Contact Methods
      If .NewWizardShowContactMethods Then
        For Each ContactMethodRO In clientGroupRO.GetContactMethodsList(True)
          Me.SupportsContactMethods = True
          Me.ContactMethods.Add(ContactMethodRO.Pk)
        Next
      End If
      Me.ShowFullContactsGrid = (mShowFullContactsGrid AndAlso .NewWizardShowContactMethods AndAlso Me.SupportsContactMethods)

      ' Web Access
      If .NewWizardShowWebAccess Then
        Me.UserDefinedWebParameters = finBLShared.CreateWsParameters(finBLShared.ClientFunctions.CreateUserDefinedWebParameters(clientGroupRO.UserDefinedWebParameterSetPk))
        Me.HasUserDataWeb = (Me.UserDefinedWebParameters.Count &lt;&gt; 0)
      End If

      ' User Defined
      If .NewWizardShowUserDefinedResolved Then
        Me.UserDefinedParameters = finBLShared.CreateWsParameters(finBLShared.ClientFunctions.CreateUserDefinedParameters(clientGroupRO.UserDefinedParameterSetPk))
        Me.HasUserData = (Me.UserDefinedParameters.Count &lt;&gt; 0)
      End If

      ' Pages
      Me.ShowBankingPage = .NewWizardShowBankingDetails
      Me.ShowEmploymentsPage = (.NewWizardShowEmployment AndAlso finBLShared.Settings.AddOns.ClientAdvanced AndAlso finBLShared.CurrentUser.Permissions.Allow("Client.Employments.Add"))
      Me.ShowIdentificationPage = .NewWizardShowIdentification
      Me.ShowContactMethodsPage = (Me.SupportsPhysicalAddress OrElse Me.SupportsPostalAddress OrElse Me.SupportsContactMethods)
      Me.ShowImagePage = (.NewWizardShowImage AndAlso finBLShared.DocumentManager.IsAvailableResolved)
      Me.ShowStatisticsPage = finBLShared.Settings.AddOns.ClientStatistics AndAlso clientGroupRO.NewWizardShowStatistics AndAlso clientGroupRO.OrganisationUseStatistics &lt;&gt; isefinClientGroupUseStatistics.No
      Me.ShowTaxPage = .NewWizardShowTaxInformation
      Me.ShowWebAccessPage = .NewWizardShowWebAccess
      Me.ShowUserDefinedPage = (Me.UserDefinedParameters IsNot Nothing AndAlso Me.UserDefinedParameters.Count &lt;&gt; 0)

      ' Other
      Me.ShowOtherInfo = .NewWizardShowOtherInformation
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Simple information about a Client Type.
''' &lt;/summary&gt;
Public Class ClientTypeInfo

  Public Caption As String
  Public ClientTypeId As String
  Public DefaultTaxCategoryId As String
  Public Icon As String
  Public IsSoleTrader As Boolean
  Public Priority As Boolean
  Public PriorityIndex As Integer
  Public SubTypeInformationListId As String
  Public TaxCategoryNonResidentFilter As String
  Public TaxCategoryResidentFilter As String
  Public UseIndustryCode As Boolean

  Public Sub New(clientType As finClientTypeRO,
                 priority As Boolean,
                 priorityIndex As Integer)

    With clientType
      Me.Priority = priority
      Me.PriorityIndex = priorityIndex

      Me.Caption = .Description
      Me.ClientTypeId = .ClientTypeId
      Me.DefaultTaxCategoryId = .DefaultTaxCategoryId
      Me.IsSoleTrader = .IsSoleTrader

      Me.TaxCategoryNonResidentFilter = finBLShared.TaxCategories.GetDataViewFilter(True, .Pk, True, False)
      Me.TaxCategoryResidentFilter = finBLShared.TaxCategories.GetDataViewFilter(True, .Pk, True, True)

      ' Icon
      If .IsSoleTrader Then
        Me.Icon = "Applicant"
      Else
        Select Case .ClientClass.ClientClassBase
          Case iseClientClassBase.FamilyPartnership, iseClientClassBase.LimitedPartnership, iseClientClassBase.Partnership
            Me.Icon = "UserGroup"

          Case iseClientClassBase.BuildingSociety, iseClientClassBase.CreditUnion
            Me.Icon = "Building|Money"

          Case iseClientClassBase.ForeignCompany
            Me.Icon = "Building|Internet"

          Case iseClientClassBase.IndustrialSociety
            Me.Icon = "Factory"

          Case iseClientClassBase.ReligiousBody
            Me.Icon = "Book"

          Case iseClientClassBase.Trust
            Me.Icon = "Briefcase"

          Case Else
            Me.Icon = "Building"
        End Select
      End If

      Me.UseIndustryCode = .UseIndustryCode
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Contact Method.
''' &lt;/summary&gt;
Public Class ContactMethodInfo

  Public AutoFormat As Boolean
  Public ClientContactMethod As finClientContactMethod.jsonHtmlWidgetClientContactMethod
  Public ContactMethodId As String
  Public ContactType As String
  Public Description As String
  Public Icon As String
  Public IsOther As Boolean
  Public Pk As Integer
  Public Value As String

  Public Sub New()
  End Sub

  Public Sub New(contactMethodRO As finContactMethodRO)

    With contactMethodRO
      Me.AutoFormat = .FormatPhoneNumbers
      Me.ClientContactMethod = .GetEmptyClientContactMethodJsonObject()
      Me.ContactMethodId = .ContactMethodId
      Me.ContactType = .ContactTypeText
      Me.Description = .DescriptionShortResolved            
      Me.IsOther = (.ContactType = isefinContactType.Other OrElse .ContactType = isefinContactType.WebPage)
      Me.Pk = .Pk
      
      If Len(.Icon) = 0 Then
        Me.Icon = "Blank"
      Else 
        Me.Icon = "ContactMethod_" &amp; .Icon
      End If
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Tax Category.
''' &lt;/summary&gt;
Public Class TaxCategoryInfo

  Public TaxCategoryId As String
  Public Exempt As Boolean
  Public Resident As Boolean

  Public Sub New (taxCategoryRO As finTaxCategoryRO)

    With taxCategoryRO
      Me.TaxCategoryId = .TaxCategoryId
      Me.Resident = .Resident
      Me.Exempt = .Exempt
    End With
  End Sub

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 ClientGroup As String
  Public ClientType As String

  Public OrganisationName As String
  Public LegalName As String

  Public CrossReference As String
  Public ClientCode As String
  Public ExternalId As String
  
  Public Branch As String
  Public Manager As String
  Public BusinessNumber As String
  Public TaxNumber As String
  Public GstNumber As String
  Public OrganisationNumber As String
  Public CommencementDate As Date?
  Public IndustryCode As String

  Public ContactMethods As List(Of ContactMethodInfo)

  Public Title As String
  Public FirstName As String
  Public MiddleNames As String
  Public LastName As String
  Public PreferredName As String
  Public DateOfBirth As Date?
  Public Gender As String
  Public MaritalStatus As String
  Public JobTitle As String
  Public Occupation As String
  Public GstExempt As Boolean
  Public CreditRating As String
  Public Status As String
  Public DateReview As Date?
  Public PassCode As String

  Public PostalAddressJson As String
  Public PostalAndPhysicalAddressSame As Boolean
  Public PhysicalAddressJson As String

  Public Akas As List(Of Aka)
  Public CommunicationGeneral As Boolean
  Public CommunicationGeneralLetter As Boolean
  Public CommunicationGeneralEmail As Boolean
  Public CommunicationGeneralSms As Boolean
  Public CommunicationGeneralPhone As Boolean
  Public CommunicationMarketing As Boolean
  Public CommunicationMarketingLetter As Boolean
  Public CommunicationMarketingEmail As Boolean
  Public CommunicationMarketingSms As Boolean
  Public CommunicationMarketingPhone As Boolean
  Public CommunicationOther1 As Boolean
  Public CommunicationOther2 As Boolean
  Public CommunicationOther3 As Boolean
  Public CommunicationOther4 As Boolean

  Public Identification As Identification

  Public Employments As List(Of finClientEmployment.jsonHtmlWidgetClientEmployment)
  
  Public ClientStatisticsSetJson As String

  Public BankingDetails As BankingDetails

  Public Resident As Boolean
  Public TaxCategoryId As String
  Public ExemptionCertificate As String
  Public ExemptionIssueDate As Date?
  Public ExemptionExpiryDate As Date?
  Public TaxCountry As String
  Public TaxForeignReference As String

  Public AllowWebAccess As Boolean
  Public WebUserId As String
  Public WebPassword As String
  Public ForcePasswordChange As Boolean
  Public UserDataWebJson As String

  Public UserDataJson As String

End Class



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

  Public ClientId As String
  Public ImageError As String

  Public Sub New(clientId As String,
                 imageError As String)

    Me.ClientId = clientId
    Me.ImageError = imageError

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "ClientNew".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
.name-details {
  display:flex;
  max-width: 120em;
  flex-direction:row;

  &gt; div {
    padding-right:2px;
    flex-grow: 1; 
    flex-shrink: 1; 
    flex-basis: auto;

    /* Title */
    &amp;:first-child {
      flex-grow:0;
    }
    
    &gt; span {
      width: 100%;
    }
  }

  /* Responsive */
  @media screen and (max-width: 640px) {
    flex-direction:column;

    &gt; div {
      margin-bottom:4px;
    }
  }
}

.linked-client {
  display: flex;
  
  span {
    padding-left: 4px;
  }
}
&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="New" tooltipText="Select a Client Type."&gt;Client Type&lt;/li&gt;
        &lt;li tabId="General" tooltipText=""&gt;Details&lt;/li&gt;
        &lt;li tabId="ContactMethods" tooltipText=""&gt;Contact &amp; Address Details&lt;/li&gt;
        &lt;li tabId="Matches" tooltipText="Check that this Client does not already exist in the database."&gt;Matches&lt;/li&gt;
        &lt;li tabId="ContactMethodsFull" tooltipText="Enter any additional Contact Methods not already entered on the 'Contact &amp; Address Details' page."&gt;Contact Methods&lt;/li&gt;
        &lt;li tabId="IdentificationAU" tooltipText="Add any items of Identification you wish to record for this Client."&gt;Identification&lt;/li&gt;
        &lt;li tabId="IdentificationNZ" tooltipText="Add any items of Identification you wish to record for this Client."&gt;Identification&lt;/li&gt;
        &lt;li tabId="IdentificationUS" tooltipText="Add any items of Identification you wish to record for this Client."&gt;Identification&lt;/li&gt;
        &lt;li tabId="Employments" tooltipText="Enter details about this organisation's personnel."&gt;Personnel&lt;/li&gt;
        &lt;li tabId="Statistics" tooltipText="Enter details of this Client's Income, Expenses, Assets and Liabilities."&gt;Statistics&lt;/li&gt;
        &lt;li tabId="BankingDetails" tooltipText="Enter Banking details for this Client."&gt;Banking Details&lt;/li&gt;
        &lt;li tabId="Image" tooltipText="Optionally, upload an Image for this Client."&gt;Image&lt;/li&gt;
        &lt;li tabId="TaxInformation" tooltipText="Specify Tax Information for this Client."&gt;Tax Information&lt;/li&gt;
        &lt;li tabId="WebAccess" tooltipText="Enter Web Access details for this Client."&gt;Web Access&lt;/li&gt;
        &lt;li tabId="UserDefined" tooltipText="Enter User Defined details for this Client."&gt;User Defined&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- New --&gt;
    &lt;div id="pageNew" style="text-align:center !important"&gt;
      &lt;div id="blClientTypes"&gt;&lt;/div&gt;
    &lt;/div&gt;


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

          &lt;tbody&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblOrganisationName"&gt;Organisation Name&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtOrganisationName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtOrganisationName" mandatory="true"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr advancedId="ClientCode"&gt;
              &lt;th&gt;&lt;label for="txtClientCode"&gt;Client Code:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtClientCode" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr advancedId="ExternalId"&gt;
              &lt;th&gt;&lt;label for="txtExternalId"&gt;External Id:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtExternalId" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr advancedId="CrossReference"&gt;
              &lt;th&gt;&lt;label for="txtCrossReference"&gt;Cross Ref:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtCrossReference" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblLegalName"&gt;Legal Name (if different from above)&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtLegalName"&gt;Legal Name:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtLegalName"/&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr advancedId="ClientGroup"&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblClientGroup"&gt;Select the Client Group&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr advancedId="ClientGroup"&gt;
              &lt;th&gt;&lt;label for="cboClientGroup"&gt;Client Group:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboClientGroup" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr id="trBranchManager"&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblBranchManager"&gt;Select the Branch and Client Manager&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr advancedId="Branch"&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 advancedId="Manager"&gt;
              &lt;th&gt;&lt;label for="cboManager"&gt;Manager:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboManager" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblCompanyDetails"&gt;Company details&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtBusinessNumber"&gt;Business No:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtBusinessNumber"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtTaxNumber"&gt;Tax Number:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtTaxNumber"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtGstNumber"&gt;GST Number:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtGstNumber"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtOrganisationNumber"&gt;Organisation No:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtOrganisationNumber"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="dateCommencementDate"&gt;Commenced:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateCommencementDate"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboIndustryCode"&gt;Industry Code:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboIndustryCode"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkGstExempt" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;

          &lt;!-- Credit Rating --&gt;
          &lt;tbody id="tbCreditRating"&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblCreditRating"&gt;Select Credit Rating and Status&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboCreditRating"&gt;Credit Rating:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboCreditRating" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboStatus"&gt;Status:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboStatus" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="dateReview"&gt;Review Date:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateReview"/&gt;&lt;/td&gt;
            &lt;/tr&gt;            
          &lt;/tbody&gt;

          &lt;!-- Pass Code --&gt;
          &lt;tbody id="tbPassCode"&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblPasscode"&gt;Specify a challenge Pass Code&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtPassCode"&gt;Pass Code:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtPassCode" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;

          &lt;!-- Person Acting --&gt;
          &lt;tbody&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblPersonActing"&gt;Person Acting's details&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtFirstName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;
                &lt;div class="name-details"&gt;
                  &lt;div&gt;&lt;input id="cboTitle"/&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input id="txtFirstName"/&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input id="txtMiddleNames"/&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input id="txtLastName"/&gt;&lt;/div&gt;
                &lt;/div&gt;
              &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtPreferredName"&gt;Preferred:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtPreferredName"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="dateDateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateDateOfBirth"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboGender"&gt;Gender:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboGender"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboMaritalStatus"&gt;Marital Status:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboMaritalStatus"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboJobTitle"&gt;Job Title:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboJobTitle"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboOccupation"&gt;Occupation:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboOccupation"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;

          &lt;tbody id="tbAkas" advancedId="ClientAkas"&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblAkas"&gt;Enter any "Also Known As" details&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;!-- Akas --&gt;
      &lt;div style="flex-grow:2; display:flex; flex-direction:row; position:relative"&gt;
        &lt;div advancedId="ClientAkas" style="flex-grow:1; position:relative; min-height:200px;"&gt;
          &lt;div id="gridAkas"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Contact Methods and Contact Addresses --&gt;
    &lt;div id="pageContactMethods" class="is-tab-page"&gt;

      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblContactDetails"&gt;Contact details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
        &lt;tbody id="tbContactMethods"&gt;&lt;/tbody&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAddressPostal"&gt;Postal Address&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
        &lt;tbody id="adAddressPostal"&gt;&lt;/tbody&gt;
        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkPostalAndPhysicalAddressSame" type="checkbox"/&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAddressPhysical"&gt;Physical Address&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
        &lt;tbody id="adAddressPhysical"&gt;&lt;/tbody&gt;

        &lt;!-- Communication --&gt;
        &lt;tbody id="tbCommunication"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblCommunication"&gt;Specify Communication settings&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkCommunicationGeneral" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationGeneralLetter" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationGeneralEmail" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationGeneralSms" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationGeneralPhone" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkCommunicationMarketing" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationMarketingLetter" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationMarketingEmail" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationMarketingSms" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationMarketingPhone" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th&gt;&lt;label id="lblCommunicationOther" type="checkbox"&gt;Other?&lt;/label&gt;&lt;/th&gt;
            &lt;td /&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationOther1" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationOther2" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationOther3" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkCommunicationOther4" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Matches --&gt;
    &lt;div id="pageMatches" class="is-tab-page" style="display:flex; flex-direction:column"&gt;
      &lt;!-- Top Panel --&gt;
      &lt;div&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="lblMatches"&gt;A Ranked list of possible matches for this Client is shown below&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;
      
      &lt;!-- Bottom Panel --&gt;
      &lt;div style="flex-grow:2; display:flex; flex-direction:row; position:relative"&gt;
        &lt;!-- Matches Grid --&gt;
        &lt;div style="flex-grow:1; position:relative"&gt;        
          &lt;div id="gridMatches" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Contact Methods --&gt;
    &lt;div id="pageContactMethodsFull" class="is-tab-page" style="display:flex; flex-direction:column"&gt;
      &lt;!-- Top Panel --&gt;
      &lt;div&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;div id="divContacts" class="is-info-text info"&gt;&lt;/div&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;
      
      &lt;!-- Bottom Panel --&gt;
      &lt;div style="flex-grow:2; display:flex; flex-direction:row; position:relative"&gt;
        &lt;!-- Matches Grid --&gt;
        &lt;div style="flex-grow:1; position:relative"&gt;        
          &lt;div id="gridContactMethods" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Identification (AU) --&gt;
    &lt;div id="pageIdentificationAU" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;!-- AU Drivers Licence --&gt;
        &lt;tbody id="tbAU_DL_Identification"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAU_DL_Identification"&gt;Australian Drivers Licence details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboAU_DL_State"&gt;State:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboAU_DL_State"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_DL_LicenceNumber"&gt;Licence Number:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_DL_LicenceNumber"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_DL_CardNumber"&gt;Card Number:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_DL_CardNumber"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_DL_FamilyName"&gt;Family Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_DL_FamilyName"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_DL_OtherNames"&gt;Other Names:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_DL_OtherNames"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_DL_Address"&gt;Address:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_DL_Address"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateAU_DL_DateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateAU_DL_DateOfBirth"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateAU_DL_DateExpiry"&gt;Expiry Date:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateAU_DL_DateExpiry"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;div style="padding-top:8px"&gt;
                &lt;button id="cmdAU_DL_PasteName" class="is-button small icon" icon="Client"&gt;Paste Name&lt;/button&gt;
                &lt;button id="cmdAU_DL_PasteDOB" class="is-button small icon" icon="Calendar"&gt;Paste Date of Birth&lt;/button&gt;
              &lt;/div&gt;
            &lt;/th&gt;
          &lt;/tr&gt;             
          &lt;tr&gt;
            &lt;td colspan="2"&gt;&lt;div id="div_AU_DL_Warnings" style="color:red;display:none;" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- AU Passport --&gt;
        &lt;tbody id="tbAU_Passport_Identification"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAU_Passport_Identification"&gt;Australian Passport details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_Passport_DocumentNumber"&gt;Document No:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_Passport_DocumentNumber"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_Passport_FamilyName"&gt;Family Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_Passport_FamilyName"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_Passport_GivenNames"&gt;Given Names:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_Passport_GivenNames"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateAU_Passport_DateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateAU_Passport_DateOfBirth"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateAU_Passport_DateIssue"&gt;Date of Issue:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateAU_Passport_DateIssue"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateAU_Passport_DateExpiry"&gt;Date of Expiry:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateAU_Passport_DateExpiry"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;div style="padding-top:8px"&gt;
                &lt;button id="cmdAU_Passport_PasteName" class="is-button small icon" icon="Client"&gt;Paste Name&lt;/button&gt;
                &lt;button id="cmdAU_Passport_PasteDOB" class="is-button small icon" icon="Calendar"&gt;Paste Date of Birth&lt;/button&gt;
              &lt;/div&gt;
            &lt;/th&gt;
          &lt;/tr&gt;          
          &lt;tr&gt;
            &lt;td colspan="2"&gt;&lt;div id="div_AU_Passport_Warnings" style="color:red;display:none;" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- AU Medicare --&gt;
        &lt;tbody id="tbAU_Medicare_Identification"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAU_Medicare_Identification"&gt;Australian Medicare details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboAU_Medicare_Colour"&gt;Card Colour:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboAU_Medicare_Colour"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_Medicare_CardNumber"&gt;Card Number:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_Medicare_CardNumber"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_Medicare_IndividualReference"&gt;Individual Ref No.:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_Medicare_IndividualReference"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtAU_Medicare_CardName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtAU_Medicare_CardName"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateAU_Medicare_DateExpiry"&gt;Valid To Date:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateAU_Medicare_DateExpiry"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;div style="padding-top:8px"&gt;
                &lt;button id="cmdAU_Medicare_PasteName" class="is-button small icon" icon="Client"&gt;Paste Name&lt;/button&gt;
              &lt;/div&gt;
            &lt;/th&gt;
          &lt;/tr&gt;          
          &lt;tr&gt;
            &lt;td colspan="2"&gt;&lt;div id="div_AU_Medicare_Warnings" style="color:red;display:none;" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Identification (NZ) --&gt;
    &lt;div id="pageIdentificationNZ" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;!-- NZ Drivers Licence --&gt;
        &lt;tbody id="tbNZ_DL_Identification"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblNZ_DL_Identification"&gt;New Zealand Drivers Licence details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtNZ_DL_FamilyName"&gt;1. Family Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNZ_DL_FamilyName" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtNZ_DL_OtherNames"&gt;2. Other Names:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNZ_DL_OtherNames" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateNZ_DL_DateOfBirth"&gt;3. Date of Birth:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateNZ_DL_DateOfBirth" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateNZ_DL_DateIssue"&gt;4a. Issue Date:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateNZ_DL_DateIssue" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateNZ_DL_DateExpiry"&gt;4b. Expiry Date:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateNZ_DL_DateExpiry" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtNZ_DL_LicenceNumber"&gt;5a. Licence:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNZ_DL_LicenceNumber" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtNZ_DL_VersionNumber"&gt;5b. Version:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNZ_DL_VersionNumber" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;div style="padding-top:8px"&gt;
                &lt;button id="cmdNZ_DL_PasteName" class="is-button small icon" icon="Client"&gt;Paste Name&lt;/button&gt;
                &lt;button id="cmdNZ_DL_PasteDOB" class="is-button small icon" icon="Calendar"&gt;Paste Date of Birth&lt;/button&gt;
              &lt;/div&gt;
            &lt;/th&gt;
          &lt;/tr&gt;          
          &lt;tr&gt;
            &lt;td colspan="2"&gt;&lt;div id="div_NZ_DL_Warnings" style="color:red;display:none;" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- NZ Passport --&gt;
        &lt;tbody id="tbNZ_Passport_Identification"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblNZ_Passport_Identification"&gt;New Zealand Passport details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtNZ_Passport_PassportNumber"&gt;Passport No:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNZ_Passport_PassportNumber" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtNZ_Passport_Surname"&gt;Surname:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNZ_Passport_Surname" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtNZ_Passport_GivenNames"&gt;Given Names:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNZ_Passport_GivenNames" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateNZ_Passport_DateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateNZ_Passport_DateOfBirth" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateNZ_Passport_DateIssue"&gt;Date of Issue:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateNZ_Passport_DateIssue" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateNZ_Passport_DateExpiry"&gt;Date of Expiry:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateNZ_Passport_DateExpiry" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;div style="padding-top:8px"&gt;
                &lt;button id="cmdNZ_Passport_PasteName" class="is-button small icon" icon="Client"&gt;Paste Name&lt;/button&gt;
                &lt;button id="cmdNZ_Passport_PasteDOB" class="is-button small icon" icon="Calendar"&gt;Paste Date of Birth&lt;/button&gt;
              &lt;/div&gt;
            &lt;/th&gt;
          &lt;/tr&gt;          
          &lt;tr&gt;
            &lt;td colspan="2"&gt;&lt;div id="div_NZ_Passport_Warnings" style="color:red;display:none;" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Identification (US) --&gt;
    &lt;div id="pageIdentificationUS" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;!-- US Drivers Licence --&gt;
        &lt;tbody id="tbUS_DL_Identification"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblUS_DL_Identification"&gt;United States Drivers Licence details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboUS_DL_State"&gt;State:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboUS_DL_State"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtUS_DL_LicenceNumber"&gt;Licence Number:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtUS_DL_LicenceNumber"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtUS_DL_FamilyName"&gt;Surname:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtUS_DL_FamilyName"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtUS_DL_OtherNames"&gt;Other Names:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtUS_DL_OtherNames"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtUS_DL_Address"&gt;Address:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtUS_DL_Address"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateUS_DL_DateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateUS_DL_DateOfBirth"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateUS_DL_DateExpiry"&gt;Expiry Date:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateUS_DL_DateExpiry"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboUS_DL_Gender"&gt;Gender:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboUS_DL_Gender"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;div style="padding-top:8px"&gt;
                &lt;button id="cmdUS_DL_PasteName" class="is-button small icon" icon="Client"&gt;Paste Name&lt;/button&gt;
                &lt;button id="cmdUS_DL_PasteDOB" class="is-button small icon" icon="Calendar"&gt;Paste Date of Birth&lt;/button&gt;
              &lt;/div&gt;
            &lt;/th&gt;
          &lt;/tr&gt;          
          &lt;tr&gt;
            &lt;td colspan="2"&gt;&lt;div id="div_US_DL_Warnings" style="color:red;display:none;" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- US Passport --&gt;
        &lt;tbody id="tbUS_Passport_Identification"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblUS_Passport_Identification"&gt;United States Passport details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtUS_Passport_PassportNumber"&gt;Passport No:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtUS_Passport_PassportNumber"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtUS_Passport_Surname"&gt;Surname:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtUS_Passport_Surname"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtUS_Passport_GivenNames"&gt;Given Names:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtUS_Passport_GivenNames"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateUS_Passport_DateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateUS_Passport_DateOfBirth"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateUS_Passport_DateIssue"&gt;Date of Issue:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateUS_Passport_DateIssue"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateUS_Passport_DateExpiry"&gt;Date of Expiry:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateUS_Passport_DateExpiry"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;div style="padding-top:8px"&gt;
                &lt;button id="cmdUS_Passport_PasteName" class="is-button small icon" icon="Client"&gt;Paste Name&lt;/button&gt;
                &lt;button id="cmdUS_Passport_PasteDOB" class="is-button small icon" icon="Calendar"&gt;Paste Date of Birth&lt;/button&gt;
              &lt;/div&gt;
            &lt;/th&gt;
          &lt;/tr&gt;          
          &lt;tr&gt;
            &lt;td colspan="2"&gt;&lt;div id="div_US_Passport_Warnings" style="color:red;display:none;" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Employments --&gt;
    &lt;div id="pageEmployments"&gt;
      &lt;div class="is-dock-fill is-split-container split5050"&gt;
        &lt;div class="panel"&gt;
          &lt;div id="gridEmployments" class="is-dock-fill"&gt;&lt;/div&gt;          
        &lt;/div&gt;
        &lt;div class="panel"&gt;
          &lt;div id="wbEmployments" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Statistics --&gt;
    &lt;div id="pageStatistics" style="display:flex; flex-direction:column"&gt;
      &lt;div&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="lblClientStatistics"&gt;Use the button below to enter Client Statistics&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;button id="cmdStatistics" class="is-button ok"&gt;Statistics&lt;/button&gt;&lt;button id="cmdStatisticsClear" class="is-button"&gt;Clear&lt;/button&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div id="wbClientStatistics" style="flex-grow:1; margin-top:8px;"&gt;&lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Banking Details --&gt;
    &lt;div id="pageBankingDetails" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblBankingDetails"&gt;Banking Details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
        &lt;tbody id="cbdBankingDetails"&gt;&lt;/tbody&gt;

        &lt;tbody&gt;
          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblFriendlyName"&gt;Select a Friendly Name to identify these Banking Details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th&gt;&lt;label for="txtFriendlyName"&gt;Friendly&amp;nbsp;Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtFriendlyName" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblValid"&gt;Specify the period for which these details are valid&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th&gt;&lt;label for="dateStart"&gt;Valid From:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateStart"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblOther"&gt;Specify other options&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkShowExternally" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th&gt;&lt;label for="numCreditLimit"&gt;Credit Limit:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numCreditLimit" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th&gt;&lt;label for="numDebitLimit"&gt;Debit Limit:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numDebitLimit" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th colspan="2"&gt;&lt;label for="txtNotes"&gt;Enter Notes&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="BankingDetails"&gt;
            &lt;th colspan="2"&gt;&lt;input id="txtNotes" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Image --&gt;
    &lt;div id="pageImage" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label&gt;Choose an Image to Upload&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;
            &lt;label for="fileImageFile"&gt;The maximum image size saved to the Document Manager will be 1024 x 728 and the orientation will automatically be adjusted if necessary.&lt;/label&gt;
            &lt;input id="fileImageFile" type="file" accept="image/*" field-type="file" max-files="1"/&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Tax Information --&gt;
    &lt;div id="pageTaxInformation"&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="lblWithholdingTax"&gt;Enter Withholding Tax details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkTaxResident" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboTaxCategory"&gt;Tax Category:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboTaxCategory" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="ExemptionCertificate"&gt;Exemption:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="ExemptionCertificate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="ExemptionIssueDate"&gt;Date Issued:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="ExemptionIssueDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="ExemptionExpiryDate"&gt;Expires:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="ExemptionExpiryDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboTaxCountry"&gt;Tax Country:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboTaxCountry" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtTaxForeignReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtTaxForeignReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;        
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Web Access --&gt;
    &lt;div id="pageWebAccess"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblWebAccess"&gt;Web Access Details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkAllowWebAccess" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="tbWebAccessDetails"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblWebUserId"&gt;Web User Id&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtWebUserId"&gt;Web User Id:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtWebUserId" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblWebPassword"&gt;Web Password&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtWebPassword"&gt;Password:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtWebPassword" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkForceChangePassword" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;

      &lt;div id="phUserDefinedWeb" style="display:block; margin-top:8px"&gt;&lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- User Defined --&gt;
    &lt;div id="pageUserDefined"&gt;
      &lt;div id="phUserDefined" style="display:block"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;


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

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

&lt;/div&gt;

&lt;script&gt;
// Record
var mRecord;
var mRecord_Akas;
var mRecord_Matches;
var mRecord_ContactMethods;
var mRecord_ClientStatisticsSetJson;
var mRecord_Employments;

var mOriginalJson;

// Global Collections
var mClientGroups;
var mClientTypes;
var mContactMethods;
var mTaxCategories;

// Controls
var C = {
  //   New
  blClientTypes: null,

  // General
  lblOrganisationName: null,
  txtOrganisationName: null,
  txtClientCode: null,
  txtExternalId: null,
  txtCrossReference: null,
  
  lblLegalName: null,
  txtLegalName: null,

  lblClientGroup: null,
  cboClientGroup: null,

  lblBranchManager: null,
  cboBranch: null,
  cboManager: null,

  lblCompanyDetails: null,
  txtBusinessNumber: null,
  txtTaxNumber: null,
  txtGstNumber: null,
  txtOrganisationNumber: null,
  dateCommencementDate: null,
  cboIndustryCode: null,
  chkGstExempt: null,

  tbCreditRating: null,
  lblCreditRating: null,
  cboCreditRating: null,
  cboStatus: null,
  dateReview: null,

  tbPassCode: null,
  lblPasscode: null,
  txtPassCode: null,

  lblPersonActing: null,
  cboTitle: null,
  txtFirstName: null,
  txtMiddleNames: null,
  txtLastName: null,
  txtPreferredName: null,
  dateDateOfBirth: null,
  cboGender: null,
  cboMaritalStatus: null,
  cboJobTitle: null,
  cboOccupation: null,

  // Address
  lblContactDetails: null,
  lblContact: null,
  tbContactMethods: null,

  lblAddressPostal: null,
  adAddressPostal: null,
  chkPostalAndPhysicalAddressSame: null,

  lblAddressPhysical: null,
  adAddressPhysical: null,

  tbCommunication: null,
  lblCommunication: null,
  chkCommunicationGeneral: null,
  chkCommunicationGeneralLetter: null,
  chkCommunicationGeneralEmail: null,
  chkCommunicationGeneralSms: null,
  chkCommunicationGeneralPhone: null,
  chkCommunicationMarketing: null,
  chkCommunicationMarketingLetter: null,
  chkCommunicationMarketingEmail: null,
  chkCommunicationMarketingSms: null,
  chkCommunicationMarketingPhone: null,
  lblCommunicationOther: null,
  chkCommunicationOther1: null,
  chkCommunicationOther2: null,
  chkCommunicationOther3: null,
  chkCommunicationOther4: null,
  
  tbAkas: null,
  lblAkas: null,
  gridAkas: null,

  // Matches
  lblMatches: null,
  gridMatches: null,

  // Contact Methods
  divContacts: null,
  gridContactMethods: null,

  // Identification (AU)
  tbAU_DL_Identification: null,
  lblAU_DL_Identification: null,
  cboAU_DL_State: null,
  txtAU_DL_LicenceNumber: null,
  txtAU_DL_CardNumber: null,
  txtAU_DL_FamilyName: null,
  txtAU_DL_OtherNames: null,
  txtAU_DL_Address: null,
  dateAU_DL_DateOfBirth: null,
  dateAU_DL_DateExpiry: null,
  div_AU_DL_Warnings: null,

  tbAU_Passport_Identification: null,
  lblAU_Passport_Identification: null,
  txtAU_Passport_DocumentNumber: null,
  txtAU_Passport_FamilyName: null,
  txtAU_Passport_GivenNames: null,
  dateAU_Passport_DateOfBirth: null,
  dateAU_Passport_DateIssue: null,
  dateAU_Passport_DateExpiry: null,
  div_AU_Passport_Warnings: null,

  tbAU_Medicare_Identification: null,
  lblAU_Medicare_Identification: null,
  cboAU_Medicare_Colour: null,
  txtAU_Medicare_CardNumber: null,
  txtAU_Medicare_IndividualReference: null,
  txtAU_Medicare_CardName: null,
  dateAU_Medicare_DateExpiry: null,
  div_AU_Medicare_Warnings: null,

  // Identification (NZ)
  tbNZ_DL_Identification: null,
  lblNZ_DL_Identification: null,
  txtNZ_DL_FamilyName: null,
  txtNZ_DL_OtherNames: null,
  dateNZ_DL_DateOfBirth: null,
  dateNZ_DL_DateIssue: null,
  dateNZ_DL_DateExpiry: null,
  txtNZ_DL_LicenceNumber: null,
  txtNZ_DL_VersionNumber: null,
  div_NZ_DL_Warnings: null,

  tbNZ_Passport_Identification: null,
  lblNZ_Passport_Identification: null,
  txtNZ_Passport_PassportNumber: null,
  txtNZ_Passport_Surname: null,
  txtNZ_Passport_GivenNames: null,
  dateNZ_Passport_DateOfBirth: null,
  dateNZ_Passport_DateIssue: null,
  dateNZ_Passport_DateExpiry: null,
  div_NZ_Passport_Warnings: null,

  // Identification (US)
  tbUS_DL_Identification: null,
  lblUS_DL_Identification: null,
  cboUS_DL_State: null,
  txtUS_DL_LicenceNumber: null,
  txtUS_DL_FamilyName: null,
  txtUS_DL_OtherNames: null,
  txtUS_DL_Address: null,
  dateUS_DL_DateOfBirth: null,
  dateUS_DL_DateExpiry: null,
  cboUS_DL_Gender: null,
  div_US_DL_Warnings: null,

  tbUS_Passport_Identification: null,
  lblUS_Passport_Identification: null,
  txtUS_Passport_PassportNumber: null,
  txtUS_Passport_Surname: null,
  txtUS_Passport_GivenNames: null,
  dateUS_Passport_DateOfBirth: null,
  dateUS_Passport_DateIssue: null,
  dateUS_Passport_DateExpiry: null,
  div_US_Passport_Warnings: null,

  // Employments
  gridEmployments: null,
  wbEmployments: null,

  // Statistics
  lblClientStatistics: null,
  cmdStatistics: null,
  cmdStatisticsClear: null,

  wbClientStatistics: null,

  // Banking Details
  lblBankingDetails: null,
  cbdBankingDetails: null,

  lblFriendlyName: null,
  txtFriendlyName: null,

  lblValid: null,
  dateStart: null,

  lblOther: null,
  chkShowExternally: null,
  numCreditLimit: null,
  numDebitLimit: null,

  txtNotes: null,

  // Image

  // Tax Information
  lblWithholdingTax: null,
  chkTaxResident: null,
  cboTaxCategory: null,
  ExemptionCertificate: null,
  ExemptionIssueDate: null,
  ExemptionExpiryDate: null,
  cboTaxCountry: null,
  txtTaxForeignReference: null,

  // Web Access
  lblWebAccess: null,
  tbWebAccessDetails: null,
  chkAllowWebAccess: null,
  lblWebUserId: null,
  txtWebUserId: null,
  lblWebPassword: null,
  txtWebPassword: null,
  chkForceChangePassword: null,
  phUserDefinedWeb: null,

  // User Defined
  phUserDefined: null
}

// Form
var frmMain;
var tabWizard;

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

var cmdAdvanced;

var cmdAU_DL_PasteName;
var cmdAU_DL_PasteDOB;
var cmdAU_Passport_PasteName;
var cmdAU_Passport_PasteDOB;
var cmdAU_Medicare_PasteName;

var cmdNZ_DL_PasteName;
var cmdNZ_DL_PasteDOB;
var cmdNZ_Passport_PasteName;
var cmdNZ_Passport_PasteDOB;

var cmdUS_DL_PasteName;
var cmdUS_DL_PasteDOB;
var cmdUS_Passport_PasteName;
var cmdUS_Passport_PasteDOB;

// Other
var mAdvancedVisible = false;
var mClientGroup;
var mClientType;
var mEditClientContactMethodIndex;
var mEditClientEmploymentIndex;
var mRequiresRefresh = false;

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

  // --------
  // Controls
  // --------
  //   New
  C.blClientTypes = widget.UI.ButtonList("blClientTypes", {
    onChange: blClientTypes_Change
  });

  //   General
  C.lblOrganisationName = widget.UI.Label("lblOrganisationName", {});
  C.txtOrganisationName = widget.UI.TextBox("txtOrganisationName", {
    allowBlank: false,
    maxLength: 125,

    onButtonClick: txtOrganisationName_ButtonClick,
  });
  C.txtClientCode = widget.UI.TextBox("txtClientCode", {
    maxLength: 10,
  }); 
  C.txtExternalId = widget.UI.TextBox("txtExternalId", {
    maxLength: 40,
  });
  C.txtCrossReference = widget.UI.TextBox("txtCrossReference", {
    maxLength: 20,
  });

  C.lblLegalName = widget.UI.Label("lblLegalName", {});
  C.txtLegalName = widget.UI.TextBox("txtLegalName", {
    allowBlank: true,
    maxLength: 125,

    onButtonClick: txtLegalName_ButtonClick,
  });

  C.lblClientGroup = widget.UI.Label("lblClientGroup", {});
  C.cboClientGroup = widget.UI.DBCombo("cboClientGroup", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,

    onChange: cboClientGroup_Change,
  });

  C.lblBranchManager = widget.UI.Label("lblBranchManager", {});
  C.cboBranch = widget.UI.DBCombo("cboBranch", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.cboManager = widget.UI.DBCombo("cboManager", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

  C.lblCompanyDetails = widget.UI.Label("lblCompanyDetails", {});
  C.txtBusinessNumber = widget.UI.TextBox("txtBusinessNumber", {
    maxLength: 20,
    widthButtonsInclusive: false,

    onButtonClick: txtBusinessNumber_ButtonClick,
  });
  C.txtTaxNumber = widget.UI.TextBox("txtTaxNumber", {
    allowBlank: true,
    dataType: "taxnumberorganisation",
    maxLength: 20,
  });
  C.txtGstNumber = widget.UI.TextBox("txtGstNumber", {
    allowBlank: true,
    maxLength: 20,
  });
  C.txtOrganisationNumber = widget.UI.TextBox("txtOrganisationNumber", {
    allowBlank: true,
    dataType: "companynumber",
    maxLength: 20,
    widthButtonsInclusive: false,

    onButtonClick: txtOrganisationNumber_ButtonClick,
  });
  C.dateCommencementDate = widget.UI.DateBox("dateCommencementDate", {
    allowBlank: true,
    historic: true,
  });
  C.cboIndustryCode = widget.UI.InformationListComboBox("cboIndustryCode", {
    allowBlank: true,
  });
  C.chkGstExempt = widget.UI.CheckBox("chkGstExempt", {
    caption: "GST Exempt?"
  });

  C.tbCreditRating = $("#tbCreditRating");
  C.lblCreditRating = widget.UI.Label("lblCreditRating", {});
  C.cboCreditRating = widget.UI.InformationListComboBox("cboCreditRating", {});
  C.cboStatus = widget.UI.IconComboBox("cboStatus", {
    iconPrefix: "ClientStatus_",
    limitToList: true,
    width: "8em"
  });
  C.dateReview = widget.UI.DateBox("dateReview", {
    allowBlank: true,
    historic: false,
  });
  
  C.tbPassCode = $("#tbPassCode");
  C.lblPasscode = widget.UI.Label("lblPasscode", {
    tooltipText: "The Pass Code is used to challenge and identify a person before providing information regarding the Client."
  })
  C.txtPassCode = widget.UI.TextBox("txtPassCode", {
    maxLenth: 20,

    onButtonClick: txtPassCode_ButtonClick,
  });
  C.txtPassCode.ButtonsDefine([{ id: "GeneratePassword", icon: "Password_Generate", tooltipText: "Generate a new strong Pass Code" }]);

  //   Person Details
  C.lblPersonActing = widget.UI.Label("lblPersonActing", {});
  C.cboTitle = widget.UI.InformationListComboBox("cboTitle", {
    allowBlank: true,
    blankTip: "Title",
    limitToList: false,
    maxLength: 20,
    width: "6em",
  });
  C.txtFirstName = widget.UI.TextBox("txtFirstName", {
    allowBlank: true,
    blankTip: "First",
    maxLength: 40,
    width: "100%"
  });
  C.txtMiddleNames = widget.UI.TextBox("txtMiddleNames", {
    allowBlank: true,
    blankTip: "Middle",
    maxLength: 60,
    width: "100%"
  });
  C.txtLastName = widget.UI.TextBox("txtLastName", {
    allowBlank: true,
    blankTip: "Last",
    maxLength: 40,
    width: "100%"
  });
  C.txtPreferredName = widget.UI.TextBox("txtPreferredName", {
    allowBlank: true,
    maxLength: 40,
  });
  C.dateDateOfBirth = widget.UI.DateBox("dateDateOfBirth", {
    allowBlank: true,
    historic: true,
    showAge: true,
  });
  C.cboGender = widget.UI.ComboBox("cboGender", {
    allowBlank: true,
    limitToList: true,
    width: "10em",
  });
  C.cboMaritalStatus = widget.UI.InformationListComboBox("cboMaritalStatus", {
    allowBlank: true,
  });
  C.cboJobTitle = widget.UI.InformationListComboBox("cboJobTitle", {
    allowBlank: true,
  });
  C.cboOccupation = widget.UI.InformationListComboBox("cboOccupation", {
    allowBlank: true,
  });

  //   Address
  C.lblContactDetails = widget.UI.Label("lblContactDetails", {});
  C.tbContactMethods = $("#tbContactMethods");

  //   Address Postal
  C.lblAddressPostal = widget.UI.Label("lblAddressPostal", {});
  C.adAddressPostal = widget.UI.AddressDetails("adAddressPostal", {
    autoValidateAddress: true,
    showDeliveryType: true,
    showPostalId: true,
    showPropertyName: true,
  });
  C.chkPostalAndPhysicalAddressSame = widget.UI.CheckBox("chkPostalAndPhysicalAddressSame", {
    caption: "This is also the Physical Address",
    onChange: chkPostalAndPhysicalAddressSame_Change
  });

  //   Address Physical
  C.lblAddressPhysical = widget.UI.Label("lblAddressPhysical", {});
  C.adAddressPhysical = widget.UI.AddressDetails("adAddressPhysical", {
    showDeliveryType: false,
    showPropertyName: true,
  });

  C.tbCommunication = $("#tbCommunication");
  C.lblCommunication = widget.UI.Label("lblCommunication", {
    tooltipText: "finPOWER Connect does not automatically use these flags. However, they can be used by Scripts and Documents to determine whether to communicate with a Client."
  });
  C.chkCommunicationGeneral = widget.UI.CheckBox("chkCommunicationGeneral", {
    caption: "General?",

    onChange: chkCommunicationGeneral_Change
  });
  C.chkCommunicationGeneralLetter = widget.UI.CheckBox("chkCommunicationGeneralLetter", {
    caption: "Letter?"
  });
  C.chkCommunicationGeneralEmail = widget.UI.CheckBox("chkCommunicationGeneralEmail", {
    caption: "Email?"
  });
  C.chkCommunicationGeneralSms = widget.UI.CheckBox("chkCommunicationGeneralSms", {
    caption: "SMS?"
  });
  C.chkCommunicationGeneralPhone = widget.UI.CheckBox("chkCommunicationGeneralPhone", {
    caption: "Phone (Voice)?"
  });
  C.chkCommunicationMarketing = widget.UI.CheckBox("chkCommunicationMarketing", {
    caption: "Marketing?",

    onChange: chkCommunicationMarketing_Change
  });
  C.chkCommunicationMarketingLetter = widget.UI.CheckBox("chkCommunicationMarketingLetter", {
    caption: "Letter?"
  });
  C.chkCommunicationMarketingEmail = widget.UI.CheckBox("chkCommunicationMarketingEmail", {
    caption: "Email?"
  });
  C.chkCommunicationMarketingSms = widget.UI.CheckBox("chkCommunicationMarketingSms", {
    caption: "SMS?"
  });
  C.chkCommunicationMarketingPhone = widget.UI.CheckBox("chkCommunicationMarketingPhone", {
    caption: "Phone (Voice)?"
  });
  C.lblCommunicationOther = widget.UI.Label("lblCommunicationOther", {
    style: "normal"
  });
  C.chkCommunicationOther1 = widget.UI.CheckBox("chkCommunicationOther1", {
    caption: "Other 1?"
  });
  C.chkCommunicationOther2 = widget.UI.CheckBox("chkCommunicationOther2", {
    caption: "Other 2?"
  });
  C.chkCommunicationOther3 = widget.UI.CheckBox("chkCommunicationOther3", {
    caption: "Other 3?"
  });
  C.chkCommunicationOther4 = widget.UI.CheckBox("chkCommunicationOther4", {
    caption: "Other 4?"
  });

  C.tbAkas = $("#tbAkas");
  C.lblAkas = widget.UI.Label("lblAkas", {});
  
  //   Matches
  C.lblMatches = widget.UI.Label("lblMatches", {}); 

  //   Contact Methods
  C.divContacts = $("#divContacts");

  //   Identification (AU)
  C.tbAU_DL_Identification = $("#tbAU_DL_Identification");
  C.lblAU_DL_Identification = widget.UI.Label("lblAU_DL_Identification", {});
  C.cboAU_DL_State = widget.UI.DBCombo("cboAU_DL_State", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: DriversLicence_Change,
  });
  C.txtAU_DL_LicenceNumber = widget.UI.TextBox("txtAU_DL_LicenceNumber", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.txtAU_DL_CardNumber = widget.UI.TextBox("txtAU_DL_CardNumber", {
    allowBlank: true,
    maxLength: 20,
    
    onChange: DriversLicence_Change,
  });
  C.txtAU_DL_FamilyName = widget.UI.TextBox("txtAU_DL_FamilyName", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.txtAU_DL_OtherNames = widget.UI.TextBox("txtAU_DL_OtherNames", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.txtAU_DL_Address = widget.UI.TextBox("txtAU_DL_Address", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.dateAU_DL_DateOfBirth = widget.UI.DateBox("dateAU_DL_DateOfBirth", {
    historic: true,

    onChange: DriversLicence_Change,
  });
  C.dateAU_DL_DateExpiry = widget.UI.DateBox("dateAU_DL_DateExpiry", {
    onChange: DriversLicence_Change,
  });
  C.div_AU_DL_Warnings = $("#div_AU_DL_Warnings");

  C.tbAU_Passport_Identification = $("#tbAU_Passport_Identification");
  C.lblAU_Passport_Identification = widget.UI.Label("lblAU_Passport_Identification", {});
  C.txtAU_Passport_DocumentNumber = widget.UI.TextBox("txtAU_Passport_DocumentNumber", {
    maxLength: 20,

    onChange: Passport_Change,
  });
  C.txtAU_Passport_FamilyName = widget.UI.TextBox("txtAU_Passport_FamilyName", {
    maxLength: 100,

    onChange: Passport_Change,
  });
  C.txtAU_Passport_GivenNames = widget.UI.TextBox("txtAU_Passport_GivenNames", {
    maxLength: 100,

    onChange: Passport_Change,
  });
  C.dateAU_Passport_DateOfBirth = widget.UI.DateBox("dateAU_Passport_DateOfBirth", {
    historic: true,

    onChange: Passport_Change,
  });
  C.dateAU_Passport_DateIssue = widget.UI.DateBox("dateAU_Passport_DateIssue", {
    historic: true,

    onChange: Passport_Change,
  });
  C.dateAU_Passport_DateExpiry = widget.UI.DateBox("dateAU_Passport_DateExpiry", {
    onChange: Passport_Change,
  });
  C.div_AU_Passport_Warnings = $("#div_AU_Passport_Warnings");

  C.tbAU_Medicare_Identification = $("#tbAU_Medicare_Identification");
  C.lblAU_Medicare_Identification = widget.UI.Label("lblAU_Medicare_Identification", {});
  C.cboAU_Medicare_Colour = widget.UI.DBCombo("cboAU_Medicare_Colour", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: Medicare_Change,
  });
  C.txtAU_Medicare_CardNumber = widget.UI.TextBox("txtAU_Medicare_CardNumber", {
    maxLength: 12,

    onChange: Medicare_Change,
  });
  C.txtAU_Medicare_IndividualReference = widget.UI.TextBox("txtAU_Medicare_IndividualReference", {
    maxLength: 12,

    onChange: Medicare_Change,
  });
  C.txtAU_Medicare_CardName = widget.UI.TextBox("txtAU_Medicare_CardName", {
    maxLength: 100,

    onChange: Medicare_Change,
  });
  C.dateAU_Medicare_DateExpiry = widget.UI.ExpiryDate("dateAU_Medicare_DateExpiry", {
    onChange: Medicare_Change,
  });
  C.div_AU_Medicare_Warnings = $("#div_AU_Medicare_Warnings");

  //   Identification (NZ)
  C.tbNZ_DL_Identification = $("#tbNZ_DL_Identification");
  C.lblNZ_DL_Identification = widget.UI.Label("lblNZ_DL_Identification", {});
  C.txtNZ_DL_FamilyName = widget.UI.TextBox("txtNZ_DL_FamilyName", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.txtNZ_DL_OtherNames = widget.UI.TextBox("txtNZ_DL_OtherNames", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.dateNZ_DL_DateOfBirth = widget.UI.DateBox("dateNZ_DL_DateOfBirth", {
    historic: true,

    onChange: DriversLicence_Change,
  });
  C.dateNZ_DL_DateIssue = widget.UI.DateBox("dateNZ_DL_DateIssue", {
    historic: true,

    onChange: DriversLicence_Change,
  });
  C.dateNZ_DL_DateExpiry = widget.UI.DateBox("dateNZ_DL_DateExpiry", {
    onChange: DriversLicence_Change,
  });
  C.txtNZ_DL_LicenceNumber = widget.UI.TextBox("txtNZ_DL_LicenceNumber", {
    maxLength: 8,

    onChange: DriversLicence_Change,
  });
  C.txtNZ_DL_VersionNumber = widget.UI.TextBox("txtNZ_DL_VersionNumber", {
    maxLength: 3,
    width: "3em",

    onChange: DriversLicence_Change,
  });
  C.div_NZ_DL_Warnings = $("#div_NZ_DL_Warnings");

  C.tbNZ_Passport_Identification = $("#tbNZ_Passport_Identification");
  C.lblNZ_Passport_Identification = widget.UI.Label("lblNZ_Passport_Identification", {});
  C.txtNZ_Passport_PassportNumber = widget.UI.TextBox("txtNZ_Passport_PassportNumber", {
    maxLength: 20,

    onChange: Passport_Change,
  });
  C.txtNZ_Passport_Surname = widget.UI.TextBox("txtNZ_Passport_Surname", {
    maxLength: 100,

    onChange: Passport_Change,
  });
  C.txtNZ_Passport_GivenNames = widget.UI.TextBox("txtNZ_Passport_GivenNames", {
    maxLength: 100,

    onChange: Passport_Change,
  });
  C.dateNZ_Passport_DateOfBirth = widget.UI.DateBox("dateNZ_Passport_DateOfBirth", {
    historic: true,

    onChange: Passport_Change,
  });
  C.dateNZ_Passport_DateIssue = widget.UI.DateBox("dateNZ_Passport_DateIssue", {
    historic: true,

    onChange: Passport_Change,
  });
  C.dateNZ_Passport_DateExpiry = widget.UI.DateBox("dateNZ_Passport_DateExpiry", {
    onChange: Passport_Change,
  });
  C.div_NZ_Passport_Warnings = $("#div_NZ_Passport_Warnings");

  //   Identification (US)
  C.tbUS_DL_Identification = $("#tbUS_DL_Identification");
  C.lblUS_DL_Identification = widget.UI.Label("lblUS_DL_Identification", {});
  C.cboUS_DL_State = widget.UI.DBCombo("cboUS_DL_State", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: DriversLicence_Change,
  });
  C.txtUS_DL_LicenceNumber = widget.UI.TextBox("txtUS_DL_LicenceNumber", {
    maxLength: 15,

    onChange: DriversLicence_Change,
  });
  C.txtUS_DL_FamilyName = widget.UI.TextBox("txtUS_DL_FamilyName", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.txtUS_DL_OtherNames = widget.UI.TextBox("txtUS_DL_OtherNames", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.txtUS_DL_Address = widget.UI.TextBox("txtUS_DL_Address", {
    maxLength: 100,

    onChange: DriversLicence_Change,
  });
  C.dateUS_DL_DateOfBirth = widget.UI.DateBox("dateUS_DL_DateOfBirth", {
    historic: true,

    onChange: DriversLicence_Change,
  });
  C.dateUS_DL_DateExpiry = widget.UI.DateBox("dateUS_DL_DateExpiry", {
    onChange: DriversLicence_Change,
  });
  C.cboUS_DL_Gender = widget.UI.ComboBox("cboUS_DL_Gender", {
    limitToList: true,
    maxLength: 20,
    width: "10em",

    onChange: DriversLicence_Change,
  });
  C.div_US_DL_Warnings = $("#div_US_DL_Warnings");

  C.tbUS_Passport_Identification = $("#tbUS_Passport_Identification");
  C.lblUS_Passport_Identification = widget.UI.Label("lblUS_Passport_Identification", {});
  C.txtUS_Passport_PassportNumber = widget.UI.TextBox("txtUS_Passport_PassportNumber", {
    maxLength: 9,

    onChange: Passport_Change,
  });
  C.txtUS_Passport_Surname = widget.UI.TextBox("txtUS_Passport_Surname", {
    maxLength: 100,

    onChange: Passport_Change,
  });
  C.txtUS_Passport_GivenNames = widget.UI.TextBox("txtUS_Passport_GivenNames", {
    maxLength: 100,

    onChange: Passport_Change,
  });
  C.dateUS_Passport_DateOfBirth = widget.UI.DateBox("dateUS_Passport_DateOfBirth", {
    historic: true,

    onChange: Passport_Change,
  });
  C.dateUS_Passport_DateIssue = widget.UI.DateBox("dateUS_Passport_DateIssue", {
    historic: true,

    onChange: Passport_Change,
  });
  C.dateUS_Passport_DateExpiry = widget.UI.DateBox("dateUS_Passport_DateExpiry", {
    onChange: Passport_Change,
  });
  C.div_US_Passport_Warnings = $("#div_US_Passport_Warnings");

  //   Employments
  C.wbEmployments = widget.UI.PreviewPane("wbEmployments", {});

  //   Statistics
  C.lblClientStatistics = widget.UI.Label("lblClientStatistics", {});
  C.cmdStatistics = $("#cmdStatistics");
  C.cmdStatistics.click(cmdStatistics_Click);
  C.cmdStatisticsClear = $("#cmdStatisticsClear");
  C.cmdStatisticsClear.click(cmdStatisticsClear_Click);

  C.wbClientStatistics = widget.UI.PreviewPane("wbClientStatistics", {});

  //   Banking Details
  C.lblBankingDetails = widget.UI.Label("lblBankingDetails", {});
  C.cbdBankingDetails = widget.UI.BankingDetails("cbdBankingDetails", {
    allowBlank: true
  });

  C.lblFriendlyName = widget.UI.Label("lblFriendlyName", {});
  C.txtFriendlyName = widget.UI.TextBox("txtFriendlyName", {
    maxLength: 50
  });

  C.lblValid = widget.UI.Label("lblValid", {});
  C.dateStart = widget.UI.DateBox("dateStart", {});

  C.lblOther = widget.UI.Label("lblOther", {});
  C.chkShowExternally = widget.UI.CheckBox("chkShowExternally", {
    caption: "Make these details visible to External applications?",
    captionWrap: true
  });
  C.numCreditLimit = widget.UI.NumberBox("numCreditLimit", {});
  C.numDebitLimit = widget.UI.NumberBox("numDebitLimit", {});

  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 5
  });

  //   Image

  //   Tax Information
  C.lblWithholdingTax = widget.UI.Label("lblWithholdingTax", {});
  C.chkTaxResident = widget.UI.CheckBox("chkTaxResident", {
    caption: "Is the Client a Resident for tax purposes?",
    captionWrap: true,

    onChange: chkTaxResident_Change
  });
  C.cboTaxCategory = widget.UI.DBCombo("cboTaxCategory", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,

    onChange: cboTaxCategory_Change
  });
  C.ExemptionCertificate = widget.UI.TextBox("ExemptionCertificate", {
    maxLength: 20
  });
  C.ExemptionIssueDate = widget.UI.DateBox("ExemptionIssueDate", {});
  C.ExemptionExpiryDate = widget.UI.DateBox("ExemptionExpiryDate", {});
  C.cboTaxCountry = widget.UI.InformationListComboBox("cboTaxCountry", {
    allowBlank: false
  });
  C.txtTaxForeignReference = widget.UI.TextBox("txtTaxForeignReference", {
    maxLength: 20
  });

  // Web Access
  C.lblWebAccess = widget.UI.Label("lblWebAccess", {});
  C.tbWebAccessDetails = $("#tbWebAccessDetails");
  C.chkAllowWebAccess = widget.UI.CheckBox("chkAllowWebAccess", {
    caption: "Allow Client to access web-based applications and Portals?",
    captionWrap: true,

    onChange: chkAllowWebAccess_Change
  });
  C.lblWebUserId = widget.UI.Label("lblWebUserId", {
    tooltipText: "You can specify a sign-in User Id for this Client, e.g., an Email address.\n\nThis can be used as an alternative to the Client's code when signing in."
  });
  C.txtWebUserId = widget.UI.TextBox("txtWebUserId", {
    maxLenth: 100
  });
  C.lblWebPassword = widget.UI.Label("lblWebPassword", {
    tooltipText: "It is up to the Portal or external application to check whether the Client should be forced to change their Web Password and act accordingly."
  });
  C.txtWebPassword = widget.UI.TextBox("txtWebPassword", {
    maxLenth: 50,

    onButtonClick: txtWebPassword_ButtonClick,
  });
  C.txtWebPassword.ButtonsDefine([{ id: "GeneratePassword", icon: "Password_Generate", tooltipText: "Generate a new strong Web Password" }]);
  C.chkForceChangePassword = widget.UI.CheckBox("chkForceChangePassword", {
    caption: "Force Client to change their Web Password the next time they sign in?",
    captionWrap: true
  });
  C.phUserDefinedWeb = widget.UI.ParametersHost("phUserDefinedWeb", {});

  //   User Defined
  C.phUserDefined = widget.UI.ParametersHost("phUserDefined", {});

  // Grids
  C.gridAkas = widget.UI.Grid("gridAkas", {
    allowAddRows: true,
    stickyHeader: true,
    showContextMenu: false,
    showRowSelectors: true,
    allowMultiRowSelect: true,

    onBeforeCellUpdate: gridAkas_BeforeCellUpdate,
    onInitialiseRow: gridAkas_InitialiseRow,
    onAfterRowActivate: gridAkas_AfterRowActivate,
    onAction: gridAkas_Action,
    onRowAdd: gridAkas_RowAdd,
  });
  
  C.gridMatches = widget.UI.Grid("gridMatches", {
    stickyHeader: true,

    onInitialiseRow: gridMatches_InitialiseRow,   
  });   

  C.gridContactMethods = widget.UI.Grid("gridContactMethods", {
    stickyHeader: true,
    showRowSelectors: true,
    allowMultiRowSelect: true,
  
    onAction: gridContactMethods_Action,
    onAfterRowActivate: gridContactMethods_AfterRowActivate,
    onInitialiseRow: gridContactMethods_InitialiseRow,   
    onRowDrilldown: gridContactMethods_RowDrilldown,
    onSelectedRowsChanged: gridContactMethods_SelectedRowsChanged,
  });

  C.gridEmployments = widget.UI.Grid("gridEmployments", {
    stickyHeader: true,
    showRowSelectors: true,
    allowMultiRowSelect: true,
    
    onAction: gridEmployments_Action,
    onAfterRowActivate: gridEmployments_AfterRowActivate,
    onInitialiseRow: gridEmployments_InitialiseRow,   
    onRowDrilldown: gridEmployments_RowDrilldown,
    onSelectedRowsChanged: gridEmployments_SelectedRowsChanged,
  });

  // Create Widget form
  frmMain = new widget.UI.Form("frmMain", {});

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

  // Disable Close Button (this causes the 'FormClose' notification action to be invoked instead)
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler)

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

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(AdvancedToggle);

  cmdAU_DL_PasteName = $("#cmdAU_DL_PasteName");
  cmdAU_DL_PasteName.click(function() { Identification_PasteData("AU_DL_PasteName"); });
  cmdAU_DL_PasteDOB = $("#cmdAU_DL_PasteDOB");
  cmdAU_DL_PasteDOB.click(function() { Identification_PasteData("AU_DL_PasteDOB"); });
  cmdAU_Passport_PasteName = $("#cmdAU_Passport_PasteName");
  cmdAU_Passport_PasteName.click(function() { Identification_PasteData("AU_Passport_PasteName"); });
  cmdAU_Passport_PasteDOB = $("#cmdAU_Passport_PasteDOB");
  cmdAU_Passport_PasteDOB.click(function() { Identification_PasteData("AU_Passport_PasteDOB"); });
  cmdAU_Medicare_PasteName = $("#cmdAU_Medicare_PasteName");
  cmdAU_Medicare_PasteName.click(function() { Identification_PasteData("AU_Medicare_PasteName"); });
  
  cmdNZ_DL_PasteName = $("#cmdNZ_DL_PasteName");
  cmdNZ_DL_PasteName.click(function() { Identification_PasteData("NZ_DL_PasteName"); });
  cmdNZ_DL_PasteDOB = $("#cmdNZ_DL_PasteDOB");
  cmdNZ_DL_PasteDOB.click(function() { Identification_PasteData("NZ_DL_PasteDOB"); });
  cmdNZ_Passport_PasteName = $("#cmdNZ_Passport_PasteName");
  cmdNZ_Passport_PasteName.click(function() { Identification_PasteData("NZ_Passport_PasteName"); });
  cmdNZ_Passport_PasteDOB = $("#cmdNZ_Passport_PasteDOB");
  cmdNZ_Passport_PasteDOB.click(function() { Identification_PasteData("NZ_Passport_PasteDOB"); });
  
  cmdUS_DL_PasteName = $("#cmdUS_DL_PasteName");
  cmdUS_DL_PasteName.click(function() { Identification_PasteData("US_DL_PasteName"); });
  cmdUS_DL_PasteDOB = $("#cmdUS_DL_PasteDOB");
  cmdUS_DL_PasteDOB.click(function() { Identification_PasteData("US_DL_PasteDOB"); });
  cmdUS_Passport_PasteName = $("#cmdUS_Passport_PasteName");
  cmdUS_Passport_PasteName.click(function() { Identification_PasteData("US_Passport_PasteName"); });
  cmdUS_Passport_PasteDOB = $("#cmdUS_Passport_PasteDOB");
  cmdUS_Passport_PasteDOB.click(function() { Identification_PasteData("US_Passport_PasteDOB"); });

  // Reset
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_Akas = [];
  mRecord_ClientStatisticsSetJson = null;
  mRecord_ContactMethods = null;
  mRecord_Employments = [];

  // Hide content
  frmMain.Visible(false);

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

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

      // Global Collections
      mClientGroups = mRecord.ClientGroups;
      mClientTypes = mRecord.ClientTypes;
      mContactMethods = mRecord.ContactMethods;
      mTaxCategories = mRecord.TaxCategories;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mClientGroups, "ClientGroupId");
      widget.ArrayAllowLookupById(mClientTypes, "ClientTypeId");
      widget.ArrayAllowLookupById(mContactMethods, "ContactMethodId");
      widget.ArrayAllowLookupById(mTaxCategories, "TaxCategoryId");

      // If only one Client Type then use this
      if(mClientTypes.length == 1) {
        mRecord.ClientTypeId = mClientTypes[0].ClientTypeId;
      }

      // Load Fields
      Fields_Load();

      // Save original JSON for Form_IsDirty
      mOriginalJson = JSON.stringify(CreateFinishParameters());
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    C.cboClientGroup.Text(mRecord.ClientGroupId);

    C.cboBranch.Text(mRecord.BranchId);
    C.cboManager.Text(mRecord.ManagerUserId);

    if (mRecord.DefaultName) C.txtOrganisationName.Text(mRecord.DefaultName);

    C.cbdBankingDetails.Initialise({});
  }

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

  // Update Controls
  ContactMethodControls_Create();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

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

  // Information Lists
  C.cboTitle.SetComboFromInformationList("Titles", true);
  C.cboIndustryCode.SetComboFromInformationList("IndustryCodes");
  C.cboMaritalStatus.SetComboFromInformationList("MaritalStatus");
  C.cboOccupation.SetComboFromInformationList("Occupations");
  C.cboJobTitle.SetComboFromInformationList("JobTitles");

  // Lists
  if (mRecord) {
    if (mRecord.AU_DL_StatesList) C.cboAU_DL_State.ListFromCsvString(mRecord.AU_DL_StatesList);
    if (mRecord.AU_MedicareColourList) C.cboAU_Medicare_Colour.ListFromCsvString(mRecord.AU_MedicareColourList);
    if (mRecord.US_DL_StatesList) C.cboUS_DL_State.ListFromCsvString(mRecord.US_DL_StatesList);

    C.cboClientGroup.RefreshFromStandardRange("ClientGroups", mRecord.ClientGroupFilter);

    C.cboBranch.RefreshFromStandardRange("Branches");
    C.cboManager.RefreshFromStandardRange("AccountManagers");

    C.cboCreditRating.SetComboFromInformationList("CreditRatings", true, null, true);
    C.cboStatus.ListFromCsvString(mRecord.StatusesList);

    C.cboGender.ListFromCsvString(mRecord.GendersList);

    C.cboTaxCountry.SetComboFromInformationList("TaxCountries", false, null, true);
  }

  // Controls
  if (mRecord) {
    C.blClientTypes.Style(mRecord.IconListStyle);

    if (!mRecord.CanEdit) {
      // Lock fields that already have default values
      C.cboClientGroup.ReadOnly(mRecord.ClientGroupId.length != 0);

      C.cboBranch.ReadOnly(mRecord.BranchId.length != 0);
      C.cboManager.ReadOnly(mRecord.ManagerUserId.length != 0);
    }
    
    C.lblCommunicationOther.Text(mRecord.CommunicationOtherText);
    C.chkCommunicationOther1.Caption(mRecord.CommunicationOther1Text);
    C.chkCommunicationOther2.Caption(mRecord.CommunicationOther2Text);
    C.chkCommunicationOther3.Caption(mRecord.CommunicationOther3Text);
    C.chkCommunicationOther4.Caption(mRecord.CommunicationOther4Text);
    
    C.lblCommunicationOther.VisibleRow(mRecord.AddonsClientAdvanced);
    C.chkCommunicationOther1.VisibleRow(mRecord.AddonsClientAdvanced);
    C.chkCommunicationOther2.VisibleRow(mRecord.AddonsClientAdvanced);
    C.chkCommunicationOther3.VisibleRow(mRecord.AddonsClientAdvanced);
    C.chkCommunicationOther4.VisibleRow(mRecord.AddonsClientAdvanced);        
    
    C.dateDateOfBirth.MaxValue(mRecord.DOBMaxValue);
    C.dateDateOfBirth.MinValue(mRecord.DOBMinValue);

    blClientTypes_Change();
    cboClientGroup_Change();
    chkAllowWebAccess_Change();

    // Company Lookup
    if (mRecord.AllowCompanyLookup) {
      var buttons = [{id: "CompanyLookup", icon: "Find", tooltipText: "Company Lookup"}];
      C.txtOrganisationName.ButtonsDefine(buttons);
      C.txtLegalName.ButtonsDefine(buttons);
      C.txtBusinessNumber.ButtonsDefine(buttons);
      C.txtOrganisationNumber.ButtonsDefine(buttons);
    }

    // Initialise Advanced
    AdvancedInitialise();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Set default Advanced headings
  AdvancedToggle_General();

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

// ========
// Is Dirty
// ========
function Form_IsDirty() {
  if (mRecord) {
    return mOriginalJson != JSON.stringify(CreateFinishParameters());
  }
  else {
    return false;
  }
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (Form_IsDirty()) {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form without saving your changes?", { heading: "Close Form" }, tabWizard_Cancel_Finalise);
  }
  else {
    // Cancel immediately
    tabWizard_Cancel_Finalise();
  }
}

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

function tabWizard_UpdateButtons() {
  // Back, Next, Finish Buttons Valid?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 0);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
  cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

  // Exceptions
  var finalPage = "General";
  if (mClientGroup) {
    if (mClientGroup.ShowUserDefinedPage) {
      finalPage = "UserDefined";
    }
    else if (mClientGroup.ShowWebAccessPage) {
      finalPage = "WebAccess";
    }
    else if (mClientGroup.ShowTaxPage) {
      finalPage = "TaxInformation";
    }
    else if (mClientGroup.ShowImagePage) {
      finalPage = "Image";
    }
    else if (mClientGroup.ShowBankingPage) {
      finalPage = "BankingDetails";
    }
    else if (mClientGroup.ShowStatisticsPage) {
      finalPage = "Statistics";
    }
    else if (mClientGroup.ShowIdentificationPage &amp;&amp; mRecord.DefaultCountryCode == "AU") {
      finalPage = "IdentificationAU";
    }
    else if (mClientGroup.ShowIdentificationPage &amp;&amp; mRecord.DefaultCountryCode == "NZ") {
      finalPage = "IdentificationNZ";
    }
    else if (mClientGroup.ShowIdentificationPage &amp;&amp; mRecord.DefaultCountryCode == "US") {
      finalPage = "IdentificationUS";
    }
    else if (mClientGroup.ShowContactMethodsPage) {
      finalPage = "ContactMethods";
    }
  }

  if (tabWizard.SelectedTabId() == finalPage) {
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
  }

  // "New" page tweaks
  if (tabIndex == 0 &amp;&amp; !mClientType) {
    cmdNext.prop("disabled", true);
  }

  // Only show Advanced button on relevant pages
  if (mRecord) {
    cmdAdvanced.hide()
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (mRecord.PageGeneralHasAdvanced) cmdAdvanced.show();
        break;

      case "BankingDetails":
        if (mRecord.PageBankingHasAdvanced) cmdAdvanced.show();
        break;
    }
  }
  else {
    cmdAdvanced.hide();
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "New":
      break;

    case "General":
      C.txtOrganisationName.WidthResizeFromParent();
      C.txtLegalName.WidthResizeFromParent();

      C.cboClientGroup.WidthResizeFromParent();
      C.cboBranch.WidthResizeFromParent();
      C.cboManager.WidthResizeFromParent();

      C.txtBusinessNumber.WidthResizeFromParent();
      C.txtTaxNumber.WidthResizeFromParent();
      C.txtGstNumber.WidthResizeFromParent();
      C.txtOrganisationNumber.WidthResizeFromParent();
      C.cboIndustryCode.WidthResizeFromParent();

      C.txtPreferredName.WidthResizeFromParent();
      C.cboMaritalStatus.WidthResizeFromParent();
      C.cboJobTitle.WidthResizeFromParent();
      C.cboOccupation.WidthResizeFromParent();
      break;

    case "ContactMethods":
      // Resize all Contact Method controls
      if (mContactMethods) {
        for (var i = 0; i &lt; mContactMethods.length; i++) {
          var item = mContactMethods[i];          
          if (!item.IsOther) item.control.WidthResizeFromParent();        
        }
      }
      break;

    case "IdentificationAU":
      C.cboAU_DL_State.WidthResizeFromParent();
      C.txtAU_DL_LicenceNumber.WidthResizeFromParent();
      C.txtAU_DL_CardNumber.WidthResizeFromParent();
      C.txtAU_DL_FamilyName.WidthResizeFromParent();
      C.txtAU_DL_OtherNames.WidthResizeFromParent();
      C.txtAU_DL_Address.WidthResizeFromParent();

      C.txtAU_Passport_DocumentNumber.WidthResizeFromParent();
      C.txtAU_Passport_FamilyName.WidthResizeFromParent();
      C.txtAU_Passport_GivenNames.WidthResizeFromParent();

      C.cboAU_Medicare_Colour.WidthResizeFromParent();
      C.txtAU_Medicare_CardNumber.WidthResizeFromParent();
      C.txtAU_Medicare_IndividualReference.WidthResizeFromParent();
      C.txtAU_Medicare_CardName.WidthResizeFromParent();
      break;

    case "IdentificationNZ":
      C.txtNZ_DL_FamilyName.WidthResizeFromParent();
      C.txtNZ_DL_OtherNames.WidthResizeFromParent();
      C.txtNZ_DL_LicenceNumber.WidthResizeFromParent();

      C.txtNZ_Passport_PassportNumber.WidthResizeFromParent();
      C.txtNZ_Passport_Surname.WidthResizeFromParent();
      C.txtNZ_Passport_GivenNames.WidthResizeFromParent();
      break;

    case "IdentificationUS":
      C.cboUS_DL_State.WidthResizeFromParent();
      C.txtUS_DL_LicenceNumber.WidthResizeFromParent();
      C.txtUS_DL_FamilyName.WidthResizeFromParent();
      C.txtUS_DL_OtherNames.WidthResizeFromParent();
      C.txtUS_DL_Address.WidthResizeFromParent();
      C.cboUS_DL_Gender.WidthResizeFromParent();

      C.txtUS_Passport_PassportNumber.WidthResizeFromParent();
      C.txtUS_Passport_Surname.WidthResizeFromParent();
      C.txtUS_Passport_GivenNames.WidthResizeFromParent();
      break;

    case "Statistics":
      break;

    case "BankingDetails":
      C.txtFriendlyName.WidthResizeFromParent();
      C.numCreditLimit.WidthResizeFromParent();
      C.numDebitLimit.WidthResizeFromParent();
      C.txtNotes.WidthResizeFromParent();
      break;

    case "TaxInformation":
      C.cboTaxCategory.WidthResizeFromParent();
      C.ExemptionCertificate.WidthResizeFromParent();
      C.cboTaxCountry.WidthResizeFromParent();
      C.txtTaxForeignReference.WidthResizeFromParent();
      break;

    case "WebAccess":
      C.txtWebUserId.WidthResizeFromParent();
      C.txtWebPassword.WidthResizeFromParent();
      C.phUserDefinedWeb.ResizeFromParent();
      break;

    case "UserDefined":
      C.phUserDefined.ResizeFromParent();
      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)) {
        case "ContactMethods":
          // Only display Address page if supported by the Client Group
          found = mClientGroup.ShowContactMethodsPage;
          break;
          
        case "Matches":
          found = (mRecord_Matches &amp;&amp; mRecord_Matches.length != 0)
          break;          

        case "ContactMethodsFull":
          found = mClientGroup.ShowFullContactsGrid;
          break;

        case "IdentificationAU":
          found = (mClientGroup.ShowIdentificationPage &amp;&amp; mRecord.DefaultCountryCode == "AU");
          break;

        case "IdentificationNZ":
          found = (mClientGroup.ShowIdentificationPage &amp;&amp; mRecord.DefaultCountryCode == "NZ");
          break;

        case "IdentificationUS":
          found = (mClientGroup.ShowIdentificationPage &amp;&amp; mRecord.DefaultCountryCode == "US");
          break;

        case "Employments":
          found = mClientGroup.ShowEmploymentsPage;
          break;

        case "Statistics":
          found = mClientGroup.ShowStatisticsPage;
          break;

        case "BankingDetails":
          found = mClientGroup.ShowBankingPage;
          break;

        case "Image":
          found = mClientGroup.ShowImagePage;
          break;

        case "TaxInformation":
          found = mClientGroup.ShowTaxPage;
          break;

        case "WebAccess":
          found = mClientGroup.ShowWebAccessPage;
          break;

        case "UserDefined":
          found = mClientGroup.ShowUserDefinedPage;
          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);
  }
}

// ===================
// txtOrganisationName
// ===================
function txtOrganisationName_ButtonClick(sender, e) {
  if (C.txtOrganisationName.Text()) {
    CompanyLookup("OrganisationName", C.txtOrganisationName);
  }
  else {
    C.txtOrganisationName.Focus();
  }
}

// ============
// txtLegalName
// ============
function txtLegalName_ButtonClick(sender, e) {
  if (C.txtLegalName.Text()) {
    CompanyLookup("LegalName", C.txtLegalName);
  }
  else {
    C.txtLegalName.Focus();
  }
}

// =================
// txtBusinessNumber
// =================
function txtBusinessNumber_ButtonClick(sender, e) {
  if (C.txtBusinessNumber.Text()) {
    CompanyLookup("BusinessNumber", C.txtBusinessNumber);
  }
  else {
    C.txtBusinessNumber.Focus();
  }
}

// =====================
// txtOrganisationNumber
// =====================
function txtOrganisationNumber_ButtonClick(sender, e) {
  if (C.txtOrganisationNumber.Text()) {
    CompanyLookup("OrganisationNumber", C.txtOrganisationNumber);
  }
  else {
    C.txtOrganisationNumber.Focus();
  }
}

// =======================
// txtPassCode_ButtonClick
// =======================
function txtPassCode_ButtonClick(source, e) {
  switch(e.id) {
    case "GeneratePassword":
      widget.GetString("GeneratePassword", {},
        function(data) { C.txtPassCode.Text(data); },
        function(errorMessage) { widget.UI.MsgBoxAlert(errorMessage); }
      );
      break;
  }
}

// ==============
// Company Lookup
// ==============
function CompanyLookup(lookupType, ctl) {
  // Build options
  var o = { branchPk: mRecord.BranchPk };
  switch(lookupType) {
    case "BusinessNumber":
      o.searchBy = "BusinessNumber";
      o.businessNumber = ctl.Text();
      o.autoClose = true;
      break;

    case "LegalName":
      o.searchBy = "LegalName";
      o.legalName = ctl.Text();
      break;

    case "OrganisationName":
      o.searchBy = "CompanyName";
      o.companyName = ctl.Text();
      break;

    case "OrganisationNumber":
      o.searchBy = "CompanyNumber";
      o.companyNumber = ctl.Text();
      o.autoClose = true;
      break;

    default:
      window.alert("Unhandled Lookup Type '" + lookupType + "'.");
      break;
  }

  // Show Lookup
  widget.UI.Forms.ShowCompanyLookup(o,
  function (data) { CompanyLookup_Done(data, ctl); },
  CompanyLookup_Fail);
}

function CompanyLookup_Done(data, ctl) {
  // Parse
  if (data) {
    data = JSON.parse(data);

    // Update fields
    C.txtOrganisationName.Text(data.companyName);
    C.txtBusinessNumber.Text(data.businessNumber);
    C.txtOrganisationNumber.Text(data.companyNumber);
    if (data.commencementDate) C.dateCommencementDate.Value(data.commencementDate);
  }
  else {
    // Cancelled by User
  }

  // Focus
  ctl.Focus();
}

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

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

      case "General":
        pageGeneral_Refresh();
        break;
        
      case "Matches":
        pageMatches_Refresh();
        break;        

      case "ContactMethodsFull":
        // Contact Methods (Full)
        pageContactMethodsFull_Refresh();
        break;

      case "IdentificationAU":
        // Identification (AU)
        pageIdentificationAU_Refresh();
        break;

      case "IdentificationNZ":
        // Identification (NZ)
        pageIdentificationNZ_Refresh();
        break;

      case "IdentificationUS":
        // Identification (US)
        pageIdentificationUS_Refresh();
        break;

      case "Employments":
        // Employments
        pageEmployments_Refresh();
        break;

      case "Statistics":
        // Statistics
        wbClientStatistics_Preview();
        break;

      case "ContactMethods":
        pageContactMethods_Refresh();
        break;

      case "TaxInformation":
        pageTaxInformation_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "General":
      frmMain.RefreshHeading(mClientType.Caption + " Details", "Enter Name and other details for this '" + mClientType.Caption + "'.");
      break;

    case "ContactMethods":
      if (mClientGroup.SupportsContactMethods &amp;&amp; (mClientGroup.SupportsPhysicalAddress || mClientGroup.SupportsPostalAddress)) {
        frmMain.RefreshHeading(mClientType.Caption + " Contact &amp; Address Details", "Enter Contact and Address details for this '" + mClientType.Caption + "'.");
      }
      else if (mClientGroup.SupportsContactMethods) {
        frmMain.RefreshHeading(mClientType.Caption + " Contact Details", "Enter Contact details for this '" + mClientType.Caption + "'.");
      }
      else {
        frmMain.RefreshHeading(mClientType.Caption + " Address Details", "Enter Address details for this '" + mClientType.Caption + "'.");
      }
      break;

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

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

  // Resize Wizard
  tabWizard_Resize();

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

// =======
// pageNew
// =======
function pageNew_Refresh() {
  // Build Contact Methods List
  if (mRecord) {
    // Define buttons
    var buttons = [];

    for(var i = 0; i &lt; mClientTypes.length; i++) {
      var item = mClientTypes[i];

      buttons.push({ id: item.ClientTypeId,
                     caption: item.Caption,
                     icon: item.Icon,
                     priority: item.Priority });

      // Get current Contact Method
      if (item.ClientTypeId == mRecord.ClientTypeId) {
        mClientType = item;
      }
    }
    C.blClientTypes.ButtonsDefine(buttons);

    // Select
    C.blClientTypes.SelectedItemId(mRecord.ClientTypeId);
  }
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {

  C.txtTaxNumber.Caption(mRecord.Terminology_TaxNumberOrganisation + ":");
  C.txtTaxNumber.VisibleRow(mRecord.Terminology_TaxNumberOrganisation != "");

  C.txtBusinessNumber.Caption(mRecord.Terminology_BusinessNumber + ":");
  C.txtBusinessNumber.VisibleRow(mRecord.ClientHasBusinessNumber &amp;&amp; mRecord.Terminology_BusinessNumber != "");

  C.txtGstNumber.Caption(mRecord.Terminology_GSTNumberOrganisation + ":");
  C.txtGstNumber.VisibleRow(mRecord.Terminology_GSTNumberOrganisation != "");

  C.txtOrganisationNumber.Caption(mRecord.Terminology_CompanyNumber + ":");

  if (mClientType) {
    // Sole Trader
    if (mClientType.IsSoleTrader) {
      C.lblLegalName.VisibleRow(false);
      C.txtLegalName.VisibleRow(false);
      C.lblCompanyDetails.Text("Organisation details");
  
      C.txtOrganisationNumber.VisibleRow(false);
      C.cboJobTitle.VisibleRow(false);
      C.cboOccupation.VisibleRow(true);
    }
    else {
      C.lblLegalName.VisibleRow(true);
      C.txtLegalName.VisibleRow(true);
      C.lblCompanyDetails.Text("Company details");
  
      C.txtOrganisationNumber.VisibleRow(mRecord.Terminology_CompanyNumber != "");
      C.cboJobTitle.VisibleRow(true);
      C.cboOccupation.VisibleRow(false);
    }
  }
}

// ==================
// pageContactMethods
// ==================
function pageContactMethods_Refresh() {
  // Update Controls
  chkPostalAndPhysicalAddressSame_Change();
}

// ===========
// pageMatches
// ===========
function pageMatches_Refresh() {
  if (mRecord_Matches) {
    gridMatches_Refresh();
  }
}

// ======================
// pageContactMethodsFull
// ======================
function pageContactMethodsFull_Refresh() {
  // Update Controls
  var Contacts = CreateFinishParameters_ContactMethods(false);
  
  // Have Contacts been entered into the flattened data entry fields?
  if (Contacts.length &gt; 0) {
    var html = "";
    html = "The following Contact Methods have been added on the &lt;b&gt;Name &amp; Details&lt;/b&gt; page:&lt;/br&gt;";
    html += "&lt;ul&gt;";    
    for (var i = 0; i &lt; Contacts.length; i++) {
      var item = Contacts[i];      
      html += "&lt;li&gt;" + widget.UI.HtmlEncode(item.description) + ": &lt;b&gt;" + widget.UI.HtmlEncode(item.value) + "&lt;/b&gt;&lt;/li&gt;";
    }    
    html += "&lt;/ul&gt;";
    html += "&lt;button class='is-button small' onClick='javascript:tabWizard_Refresh(" + tabWizard.GetTabIndexById("ContactMethods") + ");'&gt;Review&lt;/button&gt;";
    
    C.divContacts.html(html);
    C.divContacts.show();
  }
  else {
    C.divContacts.hide();
  }

  // Refresh Grid
  gridContactMethods_Refresh();
}

function GoToFirstPage() {
  tabWizard_Refresh(0);
}

// ===============
// pageEmployments
// ===============
function pageEmployments_Refresh() {
  // Refresh Grid
  gridEmployments_Refresh();
}

// ============================
// pageIdentificationAU_Refresh
// ============================
function pageIdentificationAU_Refresh() {
  // Reset Controls
  cmdAU_DL_PasteName.show();
  cmdAU_DL_PasteDOB.show();
  cmdAU_Passport_PasteName.show();
  cmdAU_Passport_PasteDOB.show();
  cmdAU_Medicare_PasteName.show();
  
  // Reset Validations
  if (mRecord.ShowIdentification_DL &amp;&amp; !mRecord.ShowIdentification_DL_Warning) DriversLicence_Change();
  if (mRecord.ShowIdentification_Passport &amp;&amp; !mRecord.ShowIdentification_Passport_Warning) Passport_Change();
  if (mRecord.ShowIdentification_Medicare &amp;&amp; !mRecord.ShowIdentification_Medicare_Warning) Medicare_Change();

  // Drivers Licence
  if (mRecord.ShowIdentification_DL || mRecord.ShowIdentification_DL_Warning) {
    // Configuration Error
    if (mRecord.ShowIdentification_DL_Warning) {
      C.cboAU_DL_State.VisibleRow(false);
      C.txtAU_DL_LicenceNumber.VisibleRow(false);
      C.txtAU_DL_CardNumber.VisibleRow(false);
      C.txtAU_DL_FamilyName.VisibleRow(false);
      C.txtAU_DL_OtherNames.VisibleRow(false);
      C.txtAU_DL_Address.VisibleRow(false);
      C.dateAU_DL_DateOfBirth.VisibleRow(false);
      C.dateAU_DL_DateExpiry.VisibleRow(false);

      C.div_AU_DL_Warnings.html(widget.UI.HtmlEncode(mRecord.ShowIdentification_DL_Warning));
      C.div_AU_DL_Warnings.show();
    }

    // Paste Buttons
    if (mRecord.ShowIdentification_DL_Warning || !mRecord.ShowIdentification_DL_AllowNamePaste || !Identification_CanPasteName()) cmdAU_DL_PasteName.hide();
    if (mRecord.ShowIdentification_DL_Warning || !mRecord.ShowIdentification_DL_AllowDateOfBirthPaste || !C.dateDateOfBirth.Value()) cmdAU_DL_PasteDOB.hide();    

    // Show
    C.tbAU_DL_Identification.show();
  }
  else {
    C.tbAU_DL_Identification.hide();
  }

  // Passport
  if (mRecord.ShowIdentification_Passport || mRecord.ShowIdentification_Passport_Warning) {
    // Configuration Error
    if (mRecord.ShowIdentification_Passport_Warning) {
      C.txtAU_Passport_DocumentNumber.VisibleRow(false);
      C.txtAU_Passport_FamilyName.VisibleRow(false);
      C.txtAU_Passport_GivenNames.VisibleRow(false);
      C.dateAU_Passport_DateOfBirth.VisibleRow(false);
      C.dateAU_Passport_DateIssue.VisibleRow(false);
      C.dateAU_Passport_DateExpiry.VisibleRow(false);

      C.div_AU_Passport_Warnings.html(widget.UI.HtmlEncode(mRecord.ShowIdentification_Passport_Warning));
      C.div_AU_Passport_Warnings.show();
    }

    // Paste Buttons
    if (mRecord.ShowIdentification_Passport_Warning || !mRecord.ShowIdentification_Passport_AllowNamePaste || !Identification_CanPasteName()) cmdAU_Passport_PasteName.hide();
    if (mRecord.ShowIdentification_Passport_Warning || !mRecord.ShowIdentification_Passport_AllowDateOfBirthPaste || !C.dateDateOfBirth.Value()) cmdAU_Passport_PasteDOB.hide();   

    // Show
    C.tbAU_Passport_Identification.show();
  }
  else {
    C.tbAU_Passport_Identification.hide();
  }

  // Medicare
  if (mRecord.ShowIdentification_Medicare || mRecord.ShowIdentification_Medicare_Warning) {
    // Configuration Error
    if (mRecord.ShowIdentification_Medicare_Warning) {
      C.cboAU_Medicare_Colour.VisibleRow(false);
      C.txtAU_Medicare_CardNumber.VisibleRow(false);
      C.txtAU_Medicare_IndividualReference.VisibleRow(false);
      C.txtAU_Medicare_CardName.VisibleRow(false);
      C.dateAU_Medicare_DateExpiry.VisibleRow(false);

      C.div_AU_Medicare_Warnings.html(widget.UI.HtmlEncode(mRecord.ShowIdentification_Medicare_Warning));
      C.div_AU_Medicare_Warnings.show();
    }

    // Paste Buttons
    if (mRecord.ShowIdentification_Medicare_Warning || !mRecord.ShowIdentification_Medicare_AllowNamePaste || !Identification_CanPasteName()) cmdAU_Medicare_PasteName.hide();  

    // Show
    C.tbAU_Medicare_Identification.show();
  }
  else {
    C.tbAU_Medicare_Identification.hide();
  }
}

// ============================
// pageIdentificationNZ_Refresh
// ============================
function pageIdentificationNZ_Refresh() {
  // Reset Controls
  cmdNZ_DL_PasteName.show();
  cmdNZ_DL_PasteDOB.show();
  cmdNZ_Passport_PasteName.show();
  cmdNZ_Passport_PasteDOB.show();

  // Reset Validations
  if (mRecord.ShowIdentification_DL &amp;&amp; !mRecord.ShowIdentification_DL_Warning) DriversLicence_Change();
  if (mRecord.ShowIdentification_Passport &amp;&amp; !mRecord.ShowIdentification_Passport_Warning) Passport_Change();

  // Drivers Licence
  if (mRecord.ShowIdentification_DL || mRecord.ShowIdentification_DL_Warning) {
    // Configuration Error
    if (mRecord.ShowIdentification_DL_Warning) {
      C.txtNZ_DL_FamilyName.VisibleRow(false);
      C.txtNZ_DL_OtherNames.VisibleRow(false);
      C.dateNZ_DL_DateOfBirth.VisibleRow(false);
      C.dateNZ_DL_DateIssue.VisibleRow(false);
      C.dateNZ_DL_DateExpiry.VisibleRow(false);
      C.txtNZ_DL_LicenceNumber.VisibleRow(false);
      C.txtNZ_DL_VersionNumber.VisibleRow(false);

      C.div_NZ_DL_Warnings.html(widget.UI.HtmlEncode(mRecord.ShowIdentification_DL_Warning));
      C.div_NZ_DL_Warnings.show();
    }

    // Paste Buttons
    if (mRecord.ShowIdentification_DL_Warning || !mRecord.ShowIdentification_DL_AllowNamePaste || !Identification_CanPasteName()) cmdNZ_DL_PasteName.hide();
    if (mRecord.ShowIdentification_DL_Warning || !mRecord.ShowIdentification_DL_AllowDateOfBirthPaste || !C.dateDateOfBirth.Value()) cmdNZ_DL_PasteDOB.hide();   

    // Show
    C.tbNZ_DL_Identification.show();
  }
  else {
    C.tbNZ_DL_Identification.hide();
  }

  // Passport
  if (mRecord.ShowIdentification_Passport || mRecord.ShowIdentification_Passport_Warning) {
    // Configuration Error
    if (mRecord.ShowIdentification_Passport_Warning) {
      C.txtNZ_Passport_PassportNumber.VisibleRow(false);
      C.txtNZ_Passport_Surname.VisibleRow(false);
      C.txtNZ_Passport_GivenNames.VisibleRow(false);
      C.dateNZ_Passport_DateOfBirth.VisibleRow(false);
      C.dateNZ_Passport_DateIssue.VisibleRow(false);
      C.dateNZ_Passport_DateExpiry.VisibleRow(false);

      C.div_NZ_Passport_Warnings.html(widget.UI.HtmlEncode(mRecord.ShowIdentification_Passport_Warning));
      C.div_NZ_Passport_Warnings.show();
    }

    // Paste Buttons
    if (mRecord.ShowIdentification_Passport_Warning || !mRecord.ShowIdentification_Passport_AllowNamePaste || !Identification_CanPasteName()) cmdNZ_Passport_PasteName.hide();
    if (mRecord.ShowIdentification_Passport_Warning || !mRecord.ShowIdentification_Passport_AllowDateOfBirthPaste || !C.dateDateOfBirth.Value()) cmdNZ_Passport_PasteDOB.hide();  

    // Show
    C.tbNZ_Passport_Identification.show();
  }
  else {
    C.tbNZ_Passport_Identification.hide();
  }
}

// ============================
// pageIdentificationUS_Refresh
// ============================
function pageIdentificationUS_Refresh() {
  // Reset Controls
  cmdUS_DL_PasteName.show();
  cmdUS_DL_PasteDOB.show();
  cmdUS_Passport_PasteName.show();
  cmdUS_Passport_PasteDOB.show();

  // Reset Validations
  if (mRecord.ShowIdentification_DL &amp;&amp; !mRecord.ShowIdentification_DL_Warning) DriversLicence_Change();
  if (mRecord.ShowIdentification_Passport &amp;&amp; !mRecord.ShowIdentification_Passport_Warning) Passport_Change();

  // Drivers Licence
  if (mRecord.ShowIdentification_DL || mRecord.ShowIdentification_DL_Warning) {
    // Configuration Error
    if (mRecord.ShowIdentification_DL_Warning) {
      C.cboUS_DL_State.VisibleRow(false);
      C.txtUS_DL_LicenceNumber.VisibleRow(false);
      C.txtUS_DL_FamilyName.VisibleRow(false);
      C.txtUS_DL_OtherNames.VisibleRow(false);
      C.txtUS_DL_Address.VisibleRow(false);
      C.dateUS_DL_DateOfBirth.VisibleRow(false);
      C.dateUS_DL_DateExpiry.VisibleRow(false);
      C.cboUS_DL_Gender.VisibleRow(false);

      C.div_US_DL_Warnings.html(widget.UI.HtmlEncode(mRecord.ShowIdentification_DL_Warning));
      C.div_US_DL_Warnings.show();
    }

    // Paste Buttons
    if (mRecord.ShowIdentification_DL_Warning || !mRecord.ShowIdentification_DL_AllowNamePaste || !Identification_CanPasteName()) cmdUS_DL_PasteName.hide();
    if (mRecord.ShowIdentification_DL_Warning || !mRecord.ShowIdentification_DL_AllowDateOfBirthPaste || !C.dateDateOfBirth.Value()) cmdUS_DL_PasteDOB.hide();  

    // Show
    C.tbUS_DL_Identification.show();
  }
  else {
    C.tbUS_DL_Identification.hide();
  }

  // Passport
  if (mRecord.ShowIdentification_Passport || mRecord.ShowIdentification_Passport_Warning) {
    // Configuration Error
    if (mRecord.ShowIdentification_Passport_Warning) {
      C.txtUS_Passport_PassportNumber.VisibleRow(false);
      C.txtUS_Passport_Surname.VisibleRow(false);
      C.txtUS_Passport_GivenNames.VisibleRow(false);
      C.dateUS_Passport_DateOfBirth.VisibleRow(false);
      C.dateUS_Passport_DateIssue.VisibleRow(false);
      C.dateUS_Passport_DateExpiry.VisibleRow(false);

      C.div_US_Passport_Warnings.html(widget.UI.HtmlEncode(mRecord.ShowIdentification_Passport_Warning));
      C.div_US_Passport_Warnings.show();
    }

    // Paste Buttons
    if (mRecord.ShowIdentification_Passport_Warning || !mRecord.ShowIdentification_Passport_AllowNamePaste || !Identification_CanPasteName()) cmdUS_Passport_PasteName.hide();
    if (mRecord.ShowIdentification_Passport_Warning || !mRecord.ShowIdentification_Passport_AllowDateOfBirthPaste || !C.dateDateOfBirth.Value()) cmdUS_Passport_PasteDOB.hide();  

    // Show
    C.tbUS_Passport_Identification.show();
  }
  else {
    C.tbUS_Passport_Identification.hide();
  }
}

// ==================
// pageTaxInformation
// ==================
function pageTaxInformation_Refresh() {
  // Client Type
  if (mClientType) {
    C.cboTaxCategory.Text(mClientType.DefaultTaxCategoryId);

    if (C.cboTaxCategory.Text()) {
      var taxCategory = mTaxCategories.GetItem(C.cboTaxCategory.Text());
    }
  }

  if (taxCategory) {
    C.chkTaxResident.Value(taxCategory.Resident);
  }

  // Update Controls
  cboTaxCategory_Change();
  chkTaxResident_Change();
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "New":
        if (C.blClientTypes.SelectedItemIndex() == -1) {
          Ok = false;
        }
        break;

      case "General":
        if (!mAdvancedVisible) {
          if (!C.cboClientGroup.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboClientGroup.Focus();
          }
          else if (!C.cboManager.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboManager.Focus();
          }
        }
        break;

      case "ContactMethods":
      case "BankingDetails":
        // Server side validation required
        break;

      case "IdentificationAU":
      case "IdentificationNZ":
      case "IdentificationUS":
        // Server side validation required
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        params = {
          companyNumber: C.txtOrganisationNumber.Text(),
          taxNumber: C.txtTaxNumber.Text(),
        };

        if (mRecord.AddonsClientAdvanced &amp;&amp; mRecord_Akas &amp;&amp; mRecord_Akas.length != 0) {
          params.AkasJson = JSON.stringify(mRecord_Akas);
        }
        break;

      case "ContactMethods":
        params = CreateFinishParameters();
        break;

      case "IdentificationAU":
      case "IdentificationNZ":
      case "IdentificationUS":
        params = {
          IdentificationJson: CreateFinishParameters_Identification(),
          ValidateDriversLicence: mRecord.ShowIdentification_DL,
          ValidatePassport: mRecord.ShowIdentification_Passport,
          ValidateMedicare: mRecord.ShowIdentification_Medicare,
        }
        break;

      case "BankingDetails":
        params = {
          bankingDetailsJson: CreateFinishParameters_BankingDetails()
        }
        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 "ContactMethods":
        if (o.Data.ClientMatches) {
          mRecord_Matches = o.Data.ClientMatches
        }
        break;
    }
    
    if (o.Data.ConfirmList &amp;&amp; o.Data.ConfirmList.length != 0) {
      // Confirm warnings
      widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                  o.Data.ConfirmList,
                                  {
                                    heading: "Additional Confirmation",
                                    icon: "Warning",
                                  },
                                  function () { validCallback(); },
                                  null);

      // Allow callbacks to continue
      return;
    };    

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId) {
     case "FormClose":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabWizard_Cancel();
      break;
   }
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      tabWizard_Cancel();
      break;

    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mRecord.PromptOnSave) {
      // Confirm
      widget.UI.MsgBoxConfirm("Add a New Client?", {heading: "Save"}, Form_ExecuteAction_FinishPost, null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

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

  // Create Parameters
  var params = CreateFinishParameters();

  // Finish
  // NOTE: Use UploadFiles rather that GetString so that the Image file is uploaded
  widget.UploadFiles("Finish", params, fileImageFile,
    function (data) {
      data = JSON.parse(data);

      // Finalise
      if (data.ImageError) {
        // Unblock
        widget.UI.Unblock();
      
        // Warning Message
        var options = {
          showClose: false,
        }
        
        widget.UI.MsgBoxAlert("The New Client '" + data.ClientId + "' was successfully created but the following warning was given:\n\n" + data.ImageError, options, 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) {
  // Notify parent (e.g., New Account wizard) that a new Client has been created
  // NOTE: This is essential if this wizard needs to notify another that it has created a new record
  widget.ParentNotify("RecordAdded", { ClientId: data.ClientId });

  // Close Form
  widget.Close();

  // Show New Client record (after closing Widget to avoid notification on Web)
  if (mRecord.ShowNewRecordOnFinish) {
    widget.ExecuteApplicationShortcutUrl("app://formshow?form=Clients&amp;id=" + data.ClientId);
  }
}

// ==============
// cboClientGroup
// ==============
function cboClientGroup_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Really Changed?
  if (mClientGroup &amp;&amp; mClientGroup.ClientGroupId === C.cboClientGroup.Text()) return;

  // Get Client Group
  mClientGroup = mClientGroups.GetItem(C.cboClientGroup.Text());

  if (mClientGroup) {
    // Mandatory Fields
    C.txtBusinessNumber.AllowBlank(!mClientGroup.BusinessNumberMandatory);
    C.txtOrganisationNumber.AllowBlank(!mClientGroup.CompanyNumberMandatory);
    C.txtTaxNumber.AllowBlank(!mClientGroup.TaxNumberMandatory);

    // GST
    C.chkGstExempt.VisibleRow(mRecord.ShowGst &amp;&amp; mClientGroup.ShowOtherInfo);

    // Reset Akas
    C.tbAkas.hide();
    C.gridAkas.Visible(false);

    // Other info
    if (mClientGroup.ShowOtherInfo) {
      C.tbCreditRating.show();
      C.tbCommunication.show();

      if (mRecord.ShowAkas.toUpperCase() != "FALSE") {
        C.tbAkas.show();
        C.gridAkas.Visible(true);

        // Refresh Grid
        gridAkas_Refresh();
      }

      chkCommunicationGeneral_Change();
      chkCommunicationMarketing_Change();
    }
    else {
      C.tbCreditRating.hide();
      C.tbCommunication.hide();
    }

    // Passcode
    if (mRecord.ShowPasscode &amp;&amp; mClientGroup.ShowOtherInfo) {
      C.tbPassCode.show();
    }
    else {
      C.tbPassCode.hide();
    }

    // Contact Methods
    ContactMethodControls_Refresh();

    // Contact Addresses
    if (mClientGroup.SupportsPostalAddress &amp;&amp; mClientGroup.SupportsPhysicalAddress) {
      C.lblAddressPostal.VisibleRow(true);
      C.adAddressPostal.Visible(true);
      C.chkPostalAndPhysicalAddressSame.VisibleRow(true);
      chkPostalAndPhysicalAddressSame_Change();

      C.lblAddressPhysical.VisibleRow(true);
      C.adAddressPhysical.Visible(true);
    }
    else if (mClientGroup.SupportsPostalAddress) {
      C.lblAddressPostal.VisibleRow(true);
      C.adAddressPostal.Visible(true);
      C.chkPostalAndPhysicalAddressSame.VisibleRow(false);

      C.lblAddressPhysical.VisibleRow(false);
      C.adAddressPhysical.Visible(false);
    }
    else if (mClientGroup.SupportsPhysicalAddress) {
      C.lblAddressPostal.VisibleRow(false);
      C.adAddressPostal.Visible(false);
      C.chkPostalAndPhysicalAddressSame.VisibleRow(false);

      C.lblAddressPhysical.VisibleRow(true);
      C.adAddressPhysical.Visible(true);
    }
    else {
      C.lblAddressPostal.VisibleRow(false);
      C.adAddressPostal.Visible(false);
      C.chkPostalAndPhysicalAddressSame.VisibleRow(false);

      C.lblAddressPhysical.VisibleRow(false);
      C.adAddressPhysical.Visible(false);
    }

    // Web Access
    if (mClientGroup.ShowWebAccessPage &amp;&amp; mClientGroup.HasUserDataWeb) {
      C.phUserDefinedWeb.Initialise(mClientGroup.UserDefinedWebParameters, { alwaysCreateControls: true });
    }
    else {
      C.phUserDefinedWeb.Initialise({});
    }

    // User Defined
    if (mClientGroup.ShowUserDefinedPage &amp;&amp; mClientGroup.HasUserData) {
      C.phUserDefined.Initialise(mClientGroup.UserDefinedParameters, { alwaysCreateControls: true });
    }
    else {
      C.phUserDefined.Initialise({});
    }
  }

  // Update Buttons
  tabWizard_UpdateButtons();
}

// ==============
// cboTaxCategory
// ==============
function cboTaxCategory_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Get Tax Category
  var taxCategory = mTaxCategories.GetItem(C.cboTaxCategory.Text());

  if (taxCategory) {
    // Exempt
    C.ExemptionCertificate.VisibleRow(taxCategory.Exempt);
    C.ExemptionIssueDate.VisibleRow(taxCategory.Exempt);
    C.ExemptionExpiryDate.VisibleRow(taxCategory.Exempt);

    // Tax Country
    C.cboTaxCountry.VisibleRow(!taxCategory.Resident);    
    
    // Tax Foreign Reference
    C.txtTaxForeignReference.VisibleRow(!taxCategory.Resident);
  }
  else {
    // Exempt
    C.ExemptionCertificate.VisibleRow(false);
    C.ExemptionIssueDate.VisibleRow(false);
    C.ExemptionExpiryDate.VisibleRow(false);

    // Tax Country
    C.cboTaxCountry.VisibleRow(!C.chkTaxResident.Value());  
    
    // Tax Foreign Reference
    C.txtTaxForeignReference.VisibleRow(!C.chkTaxResident.Value());     
  }
}

// =============
// blClientTypes
// =============
function blClientTypes_Change(sender, e) {
  if (C.blClientTypes.SelectedItemIndex() != -1) {
    // Select Contact Method
    mClientType = mClientTypes[C.blClientTypes.SelectedItemIndex()];
    mRecord.ClientTypeId = mClientType.ClientTypeId;

    // Update Controls
    if (mClientType) {
      C.cboIndustryCode.VisibleRow(mClientType.UseIndustryCode);
    }

    // Move to next page
    if (e) {
      mRequiresRefresh = true;
      tabWizard_Move(1);
    }
  }
  else {
    mClientType = null;
  }
}

// =================
// chkAllowWebAccess
// =================
function chkAllowWebAccess_Change(sender, e) {
  // Make controls visible
  if (C.chkAllowWebAccess.Value()) {
    C.tbWebAccessDetails.show();
    C.phUserDefinedWeb.Visible(true);
  }
  else {
    C.tbWebAccessDetails.hide();
    C.phUserDefinedWeb.Visible(false);
  }
}

// ==============================
// chkCommunicationGeneral_Change
// ==============================
function chkCommunicationGeneral_Change(sender, e) {
  var visibleRows = C.chkCommunicationGeneral.Value();
  
  if (mRecord &amp;&amp; !mRecord.AddonsClientAdvanced) visibleRows = false;
  
  C.chkCommunicationGeneralEmail.VisibleRow(visibleRows);
  C.chkCommunicationGeneralLetter.VisibleRow(visibleRows);
  C.chkCommunicationGeneralPhone.VisibleRow(visibleRows);
  C.chkCommunicationGeneralSms.VisibleRow(visibleRows);  
}

// ===============================
// chkCommunicationMarketing_Change
// ===============================
function chkCommunicationMarketing_Change(sender, e) {
  var visibleRows = C.chkCommunicationMarketing.Value();
  
  if (mRecord &amp;&amp; !mRecord.AddonsClientAdvanced) visibleRows = false;

  C.chkCommunicationMarketingEmail.VisibleRow(visibleRows);
  C.chkCommunicationMarketingLetter.VisibleRow(visibleRows);
  C.chkCommunicationMarketingPhone.VisibleRow(visibleRows);
  C.chkCommunicationMarketingSms.VisibleRow(visibleRows);
}

// ===============================
// chkPostalAndPhysicalAddressSame
// ===============================
function chkPostalAndPhysicalAddressSame_Change(sender, e) {
  if (C.chkPostalAndPhysicalAddressSame.VisibleRow()) {
    if (C.chkPostalAndPhysicalAddressSame.Value()) {
      C.lblAddressPhysical.VisibleRow(false);
      C.adAddressPhysical.Visible(false);
    }
    else {
      C.lblAddressPhysical.VisibleRow(true);
      C.adAddressPhysical.Visible(true);
    }

    // Resize Tab
    tabWizard_Resize();
  }
}

// ==============
// chkTaxResident
// ==============
function chkTaxResident_Change(sender, e) {
  // Reset Tax Category if user invoked
  if (e) C.cboTaxCategory.Text("");

  // Update Controls
  if (mClientType) {
    if (C.chkTaxResident.Value()) {
      C.cboTaxCategory.RefreshFromStandardRange("TaxCategories", mClientType.TaxCategoryResidentFilter);
    }
    else {
      C.cboTaxCategory.RefreshFromStandardRange("TaxCategories", mClientType.TaxCategoryNonResidentFilter);
    }
  }

  // Update Controls
  cboTaxCategory_Change();

  // Resize Controls
  tabWizard_Resize();
}

// ==============
// txtWebPassword
// ==============
function txtWebPassword_ButtonClick(source, e) {
  switch(e.id) {
    case "GeneratePassword":
      widget.GetString("GeneratePassword", {},
        function(data) { C.txtWebPassword.Text(data); },
        function(errorMessage) { widget.UI.MsgBoxAlert(errorMessage); }
      );
      break;
  }
}

// ===============
// Contact Methods
// ===============
function ContactMethodControls_Create() {
  C.tbContactMethods.empty();

  if (mContactMethods &amp;&amp; mContactMethods.length != 0) {
    for(var i = 0; i &lt; mContactMethods.length; i++) {
      var item = mContactMethods[i];
    
      // Exclude 'Other' Contact Types here
      if (!item.IsOther) {
        var control = $("&lt;input /&gt;");
        var item = mContactMethods[i];
        var id = "txtContactMethod_" + item.Pk;
        var td = $("&lt;td&gt;&lt;/td&gt;");
        var tr = $("&lt;tr&gt;&lt;/tr&gt;");
  
        // Control Attributes
        control.attr("id", id);
        td.append(control);
  
        // Row
        tr.append("&lt;th&gt;&lt;label for='" + id + "'&gt;" + widget.UI.HtmlEncode(item.Description + ":") + "&lt;/label&gt;&lt;/th&gt;");
        tr.append(td);
        C.tbContactMethods.append(tr);
        item.row = tr;
  
        // Create Widget Control
        var dataType = "";
        var maxLength = 50;
        if (item.ContactType == "Phone") {
          dataType = "phone";
          maxLength = 20;
        }
        else if (item.ContactType == "Email") {
          dataType = "email";
        }
  
        item.control = widget.UI.TextBox(id, {
          dataType: dataType,
          dataTypeReformat: item.AutoFormat,
          maxLength: maxLength
        });
  
        // Hide by default
        item.control.VisibleRow(false);
      }      
    }

    C.lblContactDetails.VisibleRow(false);
  }
  else {
    C.lblContactDetails.VisibleRow(false);
    C.tbContactMethods.hide();
  }
}

function ContactMethodControls_Refresh() {
  var matchesFound = false;
  var contactMethodCache = null;
  
  // Cache grid Contact Methods so the values can be reinstated if they also apply for the new Client Group
  if (mRecord_ContactMethods &amp;&amp; mRecord_ContactMethods.length &gt; 0) {
    contactMethodCache = mRecord_ContactMethods;
  }
  
  // Reset Full Contact Methods
  mRecord_ContactMethods = [];

  if (mClientGroup) {
    var contactMethodPks = mClientGroup.ContactMethods;

    // Ensure applicable controls are visible
    if (mContactMethods &amp;&amp; mContactMethods.length != 0) {
      for (var i = 0; i &lt; mContactMethods.length; i++) {
        var item = mContactMethods[i];        
        var found = false;        
        var k = 0;

        // Reset ordering
        if (!item.IsOther) item.row.attr("data-order", "-1");

        // Show applicable controls
        for (var j = 0; j &lt; contactMethodPks.length; j++) {
          var pk = contactMethodPks[j];
          k++;

          if (item.Pk == pk) {
            found = true;
            matchesFound = true;

            // Ordering
            if (!item.IsOther) item.row.attr("data-order", k);
            
            // Allowing full Grid?
            if (mClientGroup.ShowFullContactsGrid &amp;&amp; item.IsOther) {
              var o = item.ClientContactMethod;
              o.dataOrder = k;
              mRecord_ContactMethods.push(o);
            }
            break;
          }
        }

        // Visibility
        if (!item.IsOther) item.control.VisibleRow(found);      
      }
    }
  }

  // Show or Hide sections
  if (matchesFound) {
    // Sort
    widget.UI.OrderElements(C.tbContactMethods, "tr", "data-order", false);

    if (mRecord_ContactMethods.length &gt; 0) {
      mRecord_ContactMethods.sort(ClientContactMethodsSort);
      
      // Reinstate existing values
      if (contactMethodCache) {
        var contactsToAdd = [];
      
        for (var i = 0; i &lt; contactMethodCache.length; i++) {
          var cacheItem = contactMethodCache[i];
          var found = false;
          
          // If this cache item has a value, attempt to reinstate
          if (ContactMethodControls_Refresh_HasValue(cacheItem)) {
            for (var j = 0; j &lt; mRecord_ContactMethods.length; j++) {
              var item = mRecord_ContactMethods[j];
              
              if (cacheItem.ContactMethodPk == mRecord_ContactMethods[j].ContactMethodPk) {
                // If there are multiple Contact Methods of the same type, do not overwrite if there is already a value (additional items will be added at the end)
                if (!ContactMethodControls_Refresh_HasValue(mRecord_ContactMethods[j])) {
                  found = true;
                  mRecord_ContactMethods[j] = cacheItem;
                  break;
                }                
              }
            }
            if (!found) contactsToAdd.push(cacheItem);
          }          
        }
        
        // Add non-matched items at the end
        if (contactsToAdd.length &gt; 0) {
          for (var i = 0; i &lt; contactsToAdd.length; i++) {
            mRecord_ContactMethods.push(contactsToAdd[i]);
          }
        }
      }
    }

    // Make Visible
    C.lblContactDetails.VisibleRow(true);
    C.tbContactMethods.show();
  }
  else {
    C.lblContactDetails.VisibleRow(false);
    C.tbContactMethods.hide();
  }
}

function ContactMethodControls_Refresh_HasValue(contactMethod) {
  if (contactMethod) {
    if (contactMethod.Value &amp;&amp; contactMethod.Value.length &gt; 0) return true;
    if (contactMethod.LinkedClientId &amp;&amp; contactMethod.LinkedClientId.length &gt; 0) return true;
    if (contactMethod.LinkedClientName &amp;&amp; contactMethod.LinkedClientName.length &gt; 0) return true;
  }
  
  return false;
}

// ===========================
// Sort Client Contact Methods
// ===========================
function ClientContactMethodsSort(a, b) {
  if (a.dataOrder &lt; b.dataOrder) {
    return -1;
  }
  else if (a.dataOrder &gt; b.dataOrder) {
    return 1;
  }
  else {
    return 0;
  }
}

// =================
// Finish Parameters
// =================
function CreateFinishParameters() {
  // Create Parameters
  var params = {
    ClientGroup: C.cboClientGroup.Text(),
    ClientType: mClientType ? mClientType.ClientTypeId : "",

    Branch: C.cboBranch.Text(),
    Manager: C.cboManager.Text(),

    OrganisationName: C.txtOrganisationName.Text(),
    ClientCode: C.txtClientCode.Text(),
    ExternalId: C.txtExternalId.Text(),
    CrossReference: C.txtCrossReference.Text(),
    
    LegalName: C.txtLegalName.Text(),

    BusinessNumber: C.txtBusinessNumber.Text(),
    TaxNumber: C.txtTaxNumber.Text(),
    GstNumber: C.txtGstNumber.Text(),
    OrganisationNumber: C.txtOrganisationNumber.Text(),
    CommencementDate: C.dateCommencementDate.Value(),

    Title: C.cboTitle.Text(),
    FirstName: C.txtFirstName.Text(),
    MiddleNames: C.txtMiddleNames.Text(),
    LastName: C.txtLastName.Text(),
    PreferredName: C.txtPreferredName.Text(),
    DateOfBirth: C.dateDateOfBirth.Value(),
    Gender: C.cboGender.Text(),
    MaritalStatus: C.cboMaritalStatus.Text(),
    JobTitle: C.cboJobTitle.Text(),
    Occupation: C.cboOccupation.Text(),

    PostalAddressJson: C.adAddressPostal.ToAddressDetailsJson(),
    PostalAndPhysicalAddressSame: C.chkPostalAndPhysicalAddressSame.Value(),

    AllowWebAccess: C.chkAllowWebAccess.Value(),
    WebUserId: C.txtWebUserId.Text(),
    WebPassword: C.txtWebPassword.Text(),
    ForcePasswordChange: C.chkForceChangePassword.Value(),
  };

  if (!C.chkPostalAndPhysicalAddressSame.Value()) {
    params.PhysicalAddressJson = C.adAddressPhysical.ToAddressDetailsJson();
  }

  // Contact Methods
  params.ContactMethods = CreateFinishParameters_ContactMethods(true);

  // Industry Code
  if (mClientType &amp;&amp; mClientType.UseIndustryCode) {
    params.IndustryCode = C.cboIndustryCode.Text();
  }

  // Other Information
  if (mClientGroup &amp;&amp; mClientGroup.ShowOtherInfo) {
    params.CreditRating = C.cboCreditRating.Text();
    params.Status = C.cboStatus.Text();
    params.DateReview = C.dateReview.Value();

    if (mRecord) {
      if (mRecord.ShowGst) params.GstExempt = C.chkGstExempt.Value();
      if (mRecord.ShowPasscode) params.PassCode = C.txtPassCode.Text();
    }

    params.CommunicationGeneral = C.chkCommunicationGeneral.Value();
    if (C.chkCommunicationGeneral.Value()) {
      params.CommunicationGeneralLetter = C.chkCommunicationGeneralLetter.Value();
      params.CommunicationGeneralEmail = C.chkCommunicationGeneralEmail.Value();
      params.CommunicationGeneralSms = C.chkCommunicationGeneralSms.Value();
      params.CommunicationGeneralPhone = C.chkCommunicationGeneralPhone.Value();
    }

    params.CommunicationMarketing = C.chkCommunicationMarketing.Value();
    if (C.chkCommunicationMarketing.Value()) {
      params.CommunicationMarketingLetter = C.chkCommunicationMarketingLetter.Value();
      params.CommunicationMarketingEmail = C.chkCommunicationMarketingEmail.Value();
      params.CommunicationMarketingSms = C.chkCommunicationMarketingSms.Value();
      params.CommunicationMarketingPhone = C.chkCommunicationMarketingPhone.Value();
    }

    if (mRecord.AddonsClientAdvanced) {
      params.CommunicationOther1 = C.chkCommunicationOther1.Value();
      params.CommunicationOther2 = C.chkCommunicationOther2.Value();
      params.CommunicationOther3 = C.chkCommunicationOther3.Value();
      params.CommunicationOther4 = C.chkCommunicationOther4.Value();
    }

    // Akas
    params.Akas = JSON.parse(JSON.stringify(mRecord_Akas));
  }

  // Identification
  if (mClientGroup &amp;&amp; mClientGroup.ShowIdentificationPage) {
    params.Identification = CreateFinishParameters_Identification();
  }

  // Employments
  if (mClientGroup &amp;&amp; mClientGroup.ShowEmploymentsPage) {
    params.Employments = JSON.parse(JSON.stringify(mRecord_Employments));
  }

  // Statistics
  if (mRecord_ClientStatisticsSetJson) {
    params.ClientStatisticsSetJson = mRecord_ClientStatisticsSetJson;
  }

  // Banking Details
  params.BankingDetails = CreateFinishParameters_BankingDetails();

  // Tax Information
  if (mClientGroup &amp;&amp; mClientGroup.ShowTaxPage) {
    params.Resident = C.chkTaxResident.Value();
    params.TaxCategoryId = C.cboTaxCategory.Text();
    params.ExemptionCertificate = C.ExemptionCertificate.Text();
    params.ExemptionIssueDate = C.ExemptionIssueDate.Value();
    params.ExemptionExpiryDate = C.ExemptionExpiryDate.Value();
    params.TaxCountry = C.cboTaxCountry.Text();
    params.TaxForeignReference = C.txtTaxForeignReference.Text();    
  }

  // Web Access
  if (mClientGroup &amp;&amp; mClientGroup.ShowWebAccessPage) {
    params.UserDataWebJson = JSON.stringify(C.phUserDefinedWeb.GetParameterValuesWithTypes());
  }

  // User Defined
  if (mClientGroup &amp;&amp; mClientGroup.ShowUserDefinedPage) {
    params.UserDataJson = JSON.stringify(C.phUserDefined.GetParameterValuesWithTypes());
  }

  return params;
}

function CreateFinishParameters_BankingDetails() {
  var params = {
    BankingDetailsJson : C.cbdBankingDetails.ToBankingDetailsJson(),
    CreditLimit : C.numCreditLimit.Value(),
    DateStart : C.dateStart.Value(),
    DebitLimit : C.numDebitLimit.Value(),
    FriendlyName : C.txtFriendlyName.Text(),
    Notes : C.txtNotes.Text(),
    ShowExternally : C.chkShowExternally.Value(),
  }

  return params;
}

function CreateFinishParameters_ContactMethods(includeGrid) {
  ContactMethods = [];

  // Flat list
  if (mContactMethods &amp;&amp; mContactMethods.length != 0) {
    for (var i = 0; i &lt; mContactMethods.length; i++) {
      var item = mContactMethods[i];

      if (!item.IsOther &amp;&amp; item.control.VisibleRow() &amp;&amp; item.control.Text()) {
        var o = {
          description: item.Description,
          pk: item.Pk,
          sortOrder: item.row.attr("data-order"),
          value: item.control.Text(),          
        }
        ContactMethods.push(o);
      }
    }
    
    // Sort by Client Group
    ContactMethods.sort(CreateFinishParameters_ContactMethods_SortFlatList);
  }
  
  // Grid  
  if (includeGrid &amp;&amp; mClientGroup &amp;&amp; mClientGroup.ShowFullContactsGrid &amp;&amp; mRecord_ContactMethods.length &gt; 0) {
    for (var i = 0; i &lt; mRecord_ContactMethods.length; i++) {
      var item = mRecord_ContactMethods[i];
      ContactMethods.push({ ClientContactMethod: item });
    }
  }

  return ContactMethods;
}

function CreateFinishParameters_ContactMethods_SortFlatList(a, b) {
  if (a.sortOrder &lt; b.sortOrder) {
    return -1;
  }
  else if (a.sortOrder &gt; b.sortOrder) {
    return 1;
  }
  else {
    return 0;
  }
}

function CreateFinishParameters_Identification() {
  var params = {
    DateOfBirth : C.dateDateOfBirth.Value(),
  };

  // Return if not showing Identification
  if (!mClientGroup.ShowIdentificationPage) return params;

  // Country-specific Identification
  switch (mRecord.DefaultCountryCode) {
    case "AU":
      // Drivers Licence
      if (mRecord.ShowIdentification_DL &amp;&amp; !mRecord.ShowIdentification_DL_Warning) {
        params.DL_State = C.cboAU_DL_State.Text();
        params.DL_FamilyName = C.txtAU_DL_FamilyName.Text();
        params.DL_OtherNames = C.txtAU_DL_OtherNames.Text();
        params.DL_Address = C.txtAU_DL_Address.Text();
        params.DL_DateOfBirth = C.dateAU_DL_DateOfBirth.Value();
        params.DL_DateExpiry = C.dateAU_DL_DateExpiry.Value();
        params.DL_LicenceNumber = C.txtAU_DL_LicenceNumber.Text();
        params.DL_CardNumber = C.txtAU_DL_CardNumber.Text();
      }

      // Passport
      if (mRecord.ShowIdentification_Passport &amp;&amp; !mRecord.ShowIdentification_Passport_Warning) {
        params.Passport_PassportNumber = C.txtAU_Passport_DocumentNumber.Text();
        params.Passport_Surname = C.txtAU_Passport_FamilyName.Text();
        params.Passport_GivenNames = C.txtAU_Passport_GivenNames.Text();
        params.Passport_DateOfBirth = C.dateAU_Passport_DateOfBirth.Value();
        params.Passport_DateIssue = C.dateAU_Passport_DateIssue.Value();
        params.Passport_DateExpiry = C.dateAU_Passport_DateExpiry.Value();
      }

      // Medicare
      if (mRecord.ShowIdentification_Medicare &amp;&amp; !mRecord.ShowIdentification_Medicare_Warning) {
        params.Medicare_Colour = C.cboAU_Medicare_Colour.Text();
        params.Medicare_CardNumber = C.txtAU_Medicare_CardNumber.Text();
        params.Medicare_IndividualReference = C.txtAU_Medicare_IndividualReference.Text();
        params.Medicare_CardName = C.txtAU_Medicare_CardName.Text();
        params.Medicare_DateExpiry = C.dateAU_Medicare_DateExpiry.Value();
      }
      break;

    case "NZ":
      // Drivers Licence
      if (mRecord.ShowIdentification_DL &amp;&amp; !mRecord.ShowIdentification_DL_Warning) {
        params.DL_FamilyName = C.txtNZ_DL_FamilyName.Text();
        params.DL_OtherNames = C.txtNZ_DL_OtherNames.Text();
        params.DL_DateOfBirth = C.dateNZ_DL_DateOfBirth.Value();
        params.DL_DateIssue = C.dateNZ_DL_DateIssue.Value();
        params.DL_DateExpiry = C.dateNZ_DL_DateExpiry.Value();
        params.DL_LicenceNumber = C.txtNZ_DL_LicenceNumber.Text();
        params.DL_VersionNumber = C.txtNZ_DL_VersionNumber.Text();
      }

      // Passport
      if (mRecord.ShowIdentification_Passport &amp;&amp; !mRecord.ShowIdentification_Passport_Warning) {
        params.Passport_PassportNumber = C.txtNZ_Passport_PassportNumber.Text();
        params.Passport_Surname = C.txtNZ_Passport_Surname.Text();
        params.Passport_GivenNames = C.txtNZ_Passport_GivenNames.Text();
        params.Passport_DateOfBirth = C.dateNZ_Passport_DateOfBirth.Value();
        params.Passport_DateIssue = C.dateNZ_Passport_DateIssue.Value();
        params.Passport_DateExpiry = C.dateNZ_Passport_DateExpiry.Value();
      }
      break;

    case "US":
      // Drivers Licence
      if (mRecord.ShowIdentification_DL &amp;&amp; !mRecord.ShowIdentification_DL_Warning) {
        params.DL_State = C.cboUS_DL_State.Text();
        params.DL_FamilyName = C.txtUS_DL_FamilyName.Text();
        params.DL_OtherNames = C.txtUS_DL_OtherNames.Text();
        params.DL_Address = C.txtUS_DL_Address.Text();
        params.DL_DateOfBirth = C.dateUS_DL_DateOfBirth.Value();
        params.DL_DateExpiry = C.dateUS_DL_DateExpiry.Value();
        params.DL_LicenceNumber = C.txtUS_DL_LicenceNumber.Text();
        params.DL_Gender = C.cboUS_DL_Gender.Text();
      }

      // Passport
      if (mRecord.ShowIdentification_Passport &amp;&amp; !mRecord.ShowIdentification_Passport_Warning) {
        params.Passport_PassportNumber = C.txtUS_Passport_PassportNumber.Text();
        params.Passport_Surname = C.txtUS_Passport_Surname.Text();
        params.Passport_GivenNames = C.txtUS_Passport_GivenNames.Text();
        params.Passport_DateOfBirth = C.dateUS_Passport_DateOfBirth.Value();
        params.Passport_DateIssue = C.dateUS_Passport_DateIssue.Value();
        params.Passport_DateExpiry = C.dateUS_Passport_DateExpiry.Value();
      }
      break;
  }

  return params;
}

// =================
// Advanced handling
// =================
function AdvancedInitialise() {
  // Tweaks
  // Reset heading classes
  $("#trBranchManager").removeClass("advanced");

  // Branch and Client Manager
  if (mRecord.ShowBranch.toUpperCase() == "ADVANCED" &amp;&amp; (mRecord.ShowManager.toUpperCase() == "ADVANCED" || mRecord.ShowManager.toUpperCase() == "FALSE")) {
    $("#trBranchManager").addClass("advanced");
  }
  else if (mRecord.ShowManager.toUpperCase() == "ADVANCED" &amp;&amp; (mRecord.ShowBranch.toUpperCase() == "ADVANCED" || mRecord.ShowBranch.toUpperCase() == "FALSE")) {
    $("#trBranchManager").addClass("advanced");
  }

  // General
  AdvancedInitialiseSection("ClientCode", mRecord.ShowClientCode);
  AdvancedInitialiseSection("ExternalId", mRecord.ShowExternalId);
  AdvancedInitialiseSection("CrossReference", mRecord.ShowCrossReference);
  AdvancedInitialiseSection("ClientAkas", mRecord.ShowAkas);
  AdvancedInitialiseSection("ClientGroup", mRecord.ShowClientGroup);
  AdvancedInitialiseSection("Branch", mRecord.ShowBranch);
  AdvancedInitialiseSection("Manager", mRecord.ShowManager);
  AdvancedInitialiseSection("BankingDetails", mRecord.ShowOtherBankingDetails);
}

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

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

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

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

function AdvancedToggle() {
  // Toggle Advanced
  mAdvancedVisible = !mAdvancedVisible;

  // Update Controls
  if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }

  // Other
  switch (tabWizard.SelectedTabId()) {
    case "General":
      AdvancedToggle_General();
      break;
  }

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

function AdvancedToggle_General() {
  // Branch and Manager
  if (C.cboBranch.VisibleRow() &amp;&amp; C.cboManager.VisibleRow()) {
    C.lblBranchManager.Text("Select the Branch and Client Manager");
  }
  else if(C.cboBranch.VisibleRow()) {
    C.lblBranchManager.Text("Select the Branch");
  }
  else {
    C.lblBranchManager.Text("Select the Client Manager");
  }
  C.lblBranchManager.VisibleRow(C.cboBranch.VisibleRow() || C.cboManager.VisibleRow());
}

// =============
// cmdStatistics
// =============
function cmdStatistics_Click() {
  // NOTE: For new records, pass across the ClientGroupId and ClientTypeId so the wizard knows what to show
  var json = "{ ClientGroupId: '" + mClientGroup.ClientGroupId + "', ClientTypeId: '" + mClientType.ClientTypeId + "' }";
  if (mRecord_ClientStatisticsSetJson) json = mRecord_ClientStatisticsSetJson;

  var params = {
    EditJson: true,
    ClientStatisticsSetJson: json,
  };

  widget.UI.Forms.ShowHtmlWidgetModal(mRecord.ClientStatisticsWidgetId, { startupParametersJson: JSON.stringify(params) }, StatisticsUpdated_Notify);
}

function StatisticsUpdated_Notify(actionId, data) {
  switch(actionId) {
    case "RecordUpdated":
      mRecord_ClientStatisticsSetJson = data;

      // Preview
      wbClientStatistics_Preview();
      break;
  }
}

// ==================
// cmdStatisticsClear
// ==================
function cmdStatisticsClear_Click() {
  // Clear
  mRecord_ClientStatisticsSetJson = null;

  // Preview
  wbClientStatistics_Preview();
}

// ====================================
// Drivers Licence details have changed
// ====================================
function DriversLicence_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Hide Warnings
  C.div_AU_DL_Warnings.hide();
  C.div_NZ_DL_Warnings.hide();
  C.div_US_DL_Warnings.hide();

  // Parameters
  var params = {
    identificationJson: CreateFinishParameters_Identification(),
    validateDriversLicence: true,
    validateMedicare: false,
    validatePassport: false
  }

  // Validate
  widget.GetString("ValidateIdentification", params, DriversLicence_Change_Done);
}

function DriversLicence_Change_Done(data) {
  if (data) {
    switch (mRecord.DefaultCountryCode) {
      case "AU":
        C.div_AU_DL_Warnings.html(widget.UI.HtmlEncode(data));
        C.div_AU_DL_Warnings.show();
        break;

      case "NZ":
        C.div_NZ_DL_Warnings.html(widget.UI.HtmlEncode(data));
        C.div_NZ_DL_Warnings.show();
        break;

      case "US":
        C.div_US_DL_Warnings.html(widget.UI.HtmlEncode(data));
        C.div_US_DL_Warnings.show();
        break;
    }
  }
}

// =============================
// Medicare details have changed
// =============================
function Medicare_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Controls
  if (C.cboAU_Medicare_Colour.Text().toUpperCase() == "GREEN") {
    C.dateAU_Medicare_DateExpiry.AllowDay(false);
  }
  else {
    C.dateAU_Medicare_DateExpiry.AllowDay(true);
  }

  // Hide Warnings
  C.div_AU_Medicare_Warnings.hide();

  // Parameters
  var params = {
    identificationJson: CreateFinishParameters_Identification(),
    validateDriversLicence: false,
    validateMedicare: true,
    validatePassport: false
  }

  // Validate
  widget.GetString("ValidateIdentification", params, Medicare_Change_Done);
}

function Medicare_Change_Done(data) {
  if (data) {
    switch (mRecord.DefaultCountryCode) {
      case "AU":
        C.div_AU_Medicare_Warnings.html(widget.UI.HtmlEncode(data));
        C.div_AU_Medicare_Warnings.show();
        break;
    }
  }
}

// =============================
// Passport details have changed
// =============================
function Passport_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Hide Warnings
  C.div_AU_Passport_Warnings.hide();
  C.div_NZ_Passport_Warnings.hide();
  C.div_US_Passport_Warnings.hide();

  // Parameters
  var params = {
    identificationJson: CreateFinishParameters_Identification(),
    validateDriversLicence: false,
    validateMedicare: false,
    validatePassport: true
  }

  // Validate
  widget.GetString("ValidateIdentification", params, Passport_Change_Done);
}

function Passport_Change_Done(data) {
  if (data) {
    switch (mRecord.DefaultCountryCode) {
      case "AU":
        C.div_AU_Passport_Warnings.html(widget.UI.HtmlEncode(data));
        C.div_AU_Passport_Warnings.show();
        break;

      case "NZ":
        C.div_NZ_Passport_Warnings.html(widget.UI.HtmlEncode(data));
        C.div_NZ_Passport_Warnings.show();
        break;

      case "US":
        C.div_US_Passport_Warnings.html(widget.UI.HtmlEncode(data));
        C.div_US_Passport_Warnings.show();
        break;
    }
  }
}

// ========
// gridAkas
// ========
function gridAkas_Refresh() {
  // Add Columns
  C.gridAkas.ClearColumns();
  C.gridAkas.AddColumnString("Name", { caption: "Name", allowEdit: true, maxLength: 125 });
  C.gridAkas.AddColumnString("Notes", { caption: "Notes", allowEdit: true, maxLength: 255 });

  // Actions
  var actions = [];
  if (mRecord.AkaCanAdd) {
    actions.push({ actionId: "ItemAddName", tooltipText: "Add the Client's current Name", icon: "Client_AkaAddName" });
    actions.push({ actionId: "ItemInsert", tooltipText: "Insert a row before the current row", icon: "Grid_Row_Insert" });
  }
  if (mRecord.AkaCanDelete) {
    actions.push({ actionId: "SelectDelete", tooltipText: "Delete selected row(s)", icon: "Grid_Row_Delete" });
  }
  if (mRecord.AkaCanAdd || mRecord.AkaCanDelete) {
    actions.push({});
  }
  actions.push({ actionId: "SelectAll", tooltipText: "Select all rows", icon: "Select_All" });
  actions.push({ actionId: "SelectNone", tooltipText: "Select no rows", icon: "Select_None" });
  actions.push({ actionId: "SelectUp", tooltipText: "Select all rows above and including the current row", icon: "Select_Up" });
  actions.push({ actionId: "SelectDown", tooltipText: "Select all rows below and including the current row", icon: "Select_Down" });
  actions.push({});
  actions.push({ actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" });
  actions.push({ actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });
  C.gridAkas.Actions().Define(actions);

  // Refresh
  C.gridAkas.VirtualDataRefresh(mRecord_Akas);
}

function gridAkas_InitialiseRow(e) {
  var item = mRecord_Akas[e.row.listIndex];

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

function gridAkas_BeforeCellUpdate(e) {
  var item = mRecord_Akas[e.row.listIndex];

  switch(e.columnKey) {
    case "Name":
      item.Name = e.newValue;
      break;

    case "Notes":
      item.Notes = e.newValue;
      break;
 }

  // Refresh row to update styles
  e.refreshRow = true;
}

function gridAkas_AfterRowActivate(e) {
  // Refresh Buttons
  gridAkas_RefreshButtons();
}

function gridAkas_RefreshButtons() {
  if (C.gridAkas.ActiveDataRowListIndex() == -1) {
    C.gridAkas.Actions().SetEnabled("SelectDelete", false);
    C.gridAkas.Actions().SetEnabled("RowMoveUp", false);
    C.gridAkas.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    C.gridAkas.Actions().SetEnabled("SelectDelete", true);
    C.gridAkas.Actions().SetEnabled("RowMoveUp", C.gridAkas.ActiveDataRowListIndex() &gt; 0);
    C.gridAkas.Actions().SetEnabled("RowMoveDown", C.gridAkas.ActiveDataRowListIndex() &lt; mRecord_Akas.length - 1);
  }

  C.gridAkas.RefreshButtons();
  C.gridAkas.Focus();
}

function gridAkas_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "ITEMADDNAME":
      if (!C.txtOrganisationName.Text()) {
        widget.UI.MsgBoxAlert("No Name has been entered.");
      }
      else if(gridAkas_NameExists()) {
        widget.UI.MsgBoxAlert("Name already exists as an AKA.");
      }
      else {
        var item = {
          Name: C.txtOrganisationName.Text(),
          Notes: "",
        }
        mRecord_Akas.push(item);

        // Refresh
        C.gridAkas.VirtualDataRefresh(mRecord_Akas);
      }
      break;

    case "ITEMINSERT":
      // Create item
      var item = {
        Name: "",
        Notes: "",
      };
      mRecord_Akas.splice(C.gridAkas.ActiveDataRowListIndex(), 0, item);

      // Refresh
      C.gridAkas.VirtualDataRefresh(mRecord_Akas);
      break;

    case "SELECTDELETE":
      C.gridAkas.RemoveSelectedRowsAndCollectionItems();
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord_Akas.length; i++) {
        indexes.push(i);
      }
      break;

    case "SELECTNONE":
      var indexes = [];
      break;

    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridAkas.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord_Akas.length; i++) {
        if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
          indexes.push(i);
        }
        else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
          indexes.push(i);
        }
      }
      break;

    case "ROWMOVEDOWN":
      C.gridAkas.RowMoveDown();
      break;

    case "ROWMOVEUP":
      C.gridAkas.RowMoveUp();
      break;

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

  // Set Indexes
  if(indexes) {
    C.gridAkas.SetSelectedRowIndexes(indexes, true);
  }

  C.gridAkas.RefreshButtons();
}

function gridAkas_NameExists() {
  for (var i = 0; i &lt; mRecord_Akas.length; i++) {
    var item = mRecord_Akas[i];

    if (C.txtOrganisationName.Text() == item.Name) return true;
  }

  return false;
}

function gridAkas_RowAdd(e) {
  // Create item
  var item = {
    Name: "",
    Notes: "",
  };

  // Add
  mRecord_Akas.push(item);
}

// ===========
// gridMatches
// ===========
function gridMatches_Refresh() {
  // Anything to show?
  if (!mRecord_Matches || mRecord_Matches.length == 0) {
    C.lblMatches.VisibleRow(false);
    C.gridMatches.Visible(false);
    return;
  }
  else {
    C.lblMatches.VisibleRow(true);
    C.gridMatches.Visible(true);
  }

  // Show Columns?
  var showBusinessNumber = false;
  var showDateOfBirth = false;
  var showGender = false;
  var showLegalName = false;
  var showLocation = false;  
  var showOrganisationNumber = false;   
  var showTaxNumber = false;

  for (var i = 0; i &lt; mRecord_Matches.length; i++) {
    var item = mRecord_Matches[i];

    if (item.BusinessNumber) showBusinessNumber = true;
    if (item.DateOfBirthJson) showDateOfBirth = true;
    if (item.Gender) showGender = true;
    if (item.LegalName) showLegalName = true;
    if (item.Location) showLocation = true;
    if (item.OrganisationNumber) showOrganisationNumber = true;
    if (item.TaxNumber) showTaxNumber = true;
  }
  
  // Sole Trader
  if (mClientType) {
    if (mClientType.IsSoleTrader) {
      showLegalName = false
      showOrganisationNumber = false;
    } 
    else {
      showGender = false;
      showDateOfBirth = false;
    }
  }

  // Add Columns
  C.gridMatches.ClearColumns();
  C.gridMatches.AddColumnDrilldown("Drilldown", { icon: "Clipboard_Paste" });
  C.gridMatches.AddColumnCode("ClientId", { caption: "Client" });
  C.gridMatches.AddColumnString("Name", { caption: "Name" });
  C.gridMatches.AddColumnString("LegalName", { caption: "Legal Name", visible: showLegalName });  
  C.gridMatches.AddColumnCode("Gender", { caption: "Gender", visible: showGender });  
  C.gridMatches.AddColumnDate("DateOfBirthJson", { caption: "DOB", visible: showDateOfBirth });
  C.gridMatches.AddColumnString("Location", { caption: "Location", width: "6em", visible: showLocation });  
  C.gridMatches.AddColumnString("TaxNumber", { caption: mRecord.Terminology_TaxNumberOrganisation, visible: showTaxNumber });
  C.gridMatches.AddColumnString("BusinessNumber", { caption: mRecord.Terminology_BusinessNumber, visible: showBusinessNumber });
  C.gridMatches.AddColumnString("OrganisationNumber", { caption: mRecord.Terminology_CompanyNumber, visible: showOrganisationNumber });

  // Refresh Grid
  C.gridMatches.VirtualDataRefresh(mRecord_Matches);
}

function gridMatches_InitialiseRow(e) {
  var item = mRecord_Matches[e.row.listIndex];

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

  // Matching colours
  // NOTE: A item will only have a match colour if it matches
  
  // Business Number
  if (item.BusinessNumberMatchColour &amp;&amp; e.row.cells.BusinessNumber) {
    e.row.cells.BusinessNumber.backgroundColour = item.BusinessNumberMatchColour
  }
  
  // Date of Birth
  if (item.DateOfBirthMatchColour &amp;&amp; e.row.cells.DateOfBirthJson) {
    e.row.cells.DateOfBirthJson.backgroundColour = item.DateOfBirthMatchColour;
  }
  
  // Gender
  if (item.GenderMatchColour &amp;&amp; e.row.cells.Gender) {
    e.row.cells.Gender.backgroundColour = item.GenderMatchColour;
  }
  
  // Legal Name
  if (item.LegalNameMatchColour &amp;&amp; e.row.cells.LegalName) {
    e.row.cells.LegalName.backgroundColour = item.LegalNameMatchColour;
  }
  
  // Location
  if (item.LocationMatchColour &amp;&amp; e.row.cells.Location) {
    e.row.cells.Location.backgroundColour = item.LocationMatchColour;
  }
  
  // Name
  if (item.NameMatchColour &amp;&amp; e.row.cells.Name) {
    e.row.cells.Name.backgroundColour = item.NameMatchColour;
  }
  
  // Organisation Number
  if (item.OrganisationNumberMatchColour &amp;&amp; e.row.cells.OrganisationNumber) {
    e.row.cells.OrganisationNumber.backgroundColour = item.OrganisationNumberMatchColour;
  }
  
  // Tax Number
  if (item.TaxNumberMatchColour &amp;&amp; e.row.cells.TaxNumber) {
    e.row.cells.TaxNumber.backgroundColour = item.TaxNumberMatchColour;
  }

  // Hyperlink ClientId
  e.row.cells.ClientId.hyperlink = "app://FormShow?form=Client&amp;id=" + encodeURI(item.ClientId);
}

// ==================
// gridContactMethods
// ==================
function gridContactMethods_Refresh() {
  // Show columns
  var showNotes = false;
  var showHistoric = false;
  for (var i = 0; i &lt; mRecord_ContactMethods.length; i++) {
    var item = mRecord_ContactMethods[i];
    
    if (item.Notes) showNotes = true;
    if (item.ShowAsHistoric) showHistoric = true;
  }

  // Add Columns
  C.gridContactMethods.ClearColumns();
  C.gridContactMethods.AddColumnDrilldown();
  C.gridContactMethods.AddColumnIcon("Icon", {});
  C.gridContactMethods.AddColumnIcon("Historic", { visible: showHistoric });
  C.gridContactMethods.AddColumnCode("ContactMethodId", { caption: "Method" });
  C.gridContactMethods.AddColumnString("Description", { caption: "Contact Method", width: "14em" });
  C.gridContactMethods.AddColumnHtml("Value", { caption: "Details" });
  C.gridContactMethods.AddColumnString("Notes", { caption: "Notes", visible: showNotes });

  // Actions
  var actions = [];
  actions.push({ actionId: "Add", tooltipText: "Add a Contact Method", icon: "Grid_Row_Add" });
  actions.push({ actionId: "SelectDelete", tooltipText: "Delete selected row(s)", icon: "Grid_Row_Delete" });
  actions.push({});
  actions.push({ actionId: "SelectAll", tooltipText: "Select all rows", icon: "Select_All" });
  actions.push({ actionId: "SelectNone", tooltipText: "Select no rows", icon: "Select_None" });
  actions.push({ actionId: "SelectUp", tooltipText: "Select all rows above and including the current row", icon: "Select_Up" });
  actions.push({ actionId: "SelectDown", tooltipText: "Select all rows below and including the current row", icon: "Select_Down" });
  actions.push({});
  actions.push({ actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" });
  actions.push({ actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });
  C.gridContactMethods.Actions().Define(actions);

  // Refresh
  C.gridContactMethods.VirtualDataRefresh(mRecord_ContactMethods);
}

function gridContactMethods_InitialiseRow(e) {
  var item = mRecord_ContactMethods[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);
  
  // Value Type
  if (item.ValueType) {
    if (item.ValueType.length &gt; 10) e.row.cells.Description.small = true;
    e.row.cells.Description.value = e.row.cells.Description.value + " (" + item.ValueType + ")";
  }
  
  // Handle different value types
  if (item.Extension) {
    // Has Extension (Phone)
    e.row.cells.Value.value = e.row.cells.Value.value + " Ext " + widget.UI.HtmlEncode(item.Extension)
  }    
  else if (item.IsWebAddress &amp;&amp; item.Value) {
    // Is a Web Page
    e.row.cells.Value.value = "&lt;a href=\"javascript:widget.ExecuteApplicationShortcutUrl('External?file=" + item.Value + "')\"&gt;" + widget.UI.HtmlEncode(item.Value) + "&lt;/a&gt;";
  }
  else if (item.LinkedClientId) {
    // Has a Linked Client
    e.row.cells.Value.value = "&lt;div class='linked-client'&gt;&lt;img src='" + widget.GetIconUrl("Client") + "' /&gt;&lt;span class='inline-linked-client'&gt;&lt;a href='app://FormShow?form=Clients&amp;id=" + item.LinkedClientId + "'&gt;" + item.LinkedClientId + " (" + item.LinkedClientName + ")&lt;/a&gt;&lt;/span&gt;&lt;/div&gt;";
  }
  
  // Historic
  if (item.ShowAsHistoric) {
    e.row.inactive = true;
    e.row.cells.Historic.value = "History";
    e.row.cells.Historic.tooltipText = "Historic";
  }
  else {
    e.row.cells.Value.bold = true;
  }
  
  // Hyperlinks
  e.row.cells.ContactMethodId.hyperlink = "app://FormShow?form=ContactMethods&amp;id=" + encodeURI(item.ContactMethodId);
}

function gridContactMethods_RowDrilldown(e) {
  EditContactMethod(e.row.listIndex);
}

function gridContactMethods_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "ADD":
      EditContactMethod(-1);
      break;  
      
    case "SELECTDELETE":
      C.gridContactMethods.RemoveSelectedRowsAndCollectionItems();
      break;
      
    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord_ContactMethods.length; i++) {
        indexes.push(i);
      }
      break;
      
    case "SELECTNONE":
      var indexes = [];
      break;

    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridContactMethods.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord_ContactMethods.length; i++) {
        if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
          indexes.push(i);
        }
        else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
          indexes.push(i);
        }
      }
      break;  
      
    case "ROWMOVEDOWN":
      C.gridContactMethods.RowMoveDown();
      break;

    case "ROWMOVEUP":
      C.gridContactMethods.RowMoveUp();
      break;
  }
  
  // Set Indexes
  if(indexes) {
    C.gridContactMethods.SetSelectedRowIndexes(indexes, true);
  }

  gridContactMethods_RefreshButtons();
}

function gridContactMethods_AfterRowActivate(e) {
  // Refresh Buttons
  gridContactMethods_RefreshButtons();
}

function gridContactMethods_SelectedRowsChanged(e) {
  // Refresh Buttons
  gridContactMethods_RefreshButtons();
}

function gridContactMethods_RefreshButtons() {
  var rows = C.gridContactMethods.GetSelectedRowIndexes(true, true);

  if (rows.length == 0) {
    C.gridContactMethods.Actions().SetEnabled("SelectDelete", false);
    C.gridContactMethods.Actions().SetEnabled("SelectUp", false);
    C.gridContactMethods.Actions().SetEnabled("SelectDown", false);
    C.gridContactMethods.Actions().SetEnabled("RowMoveUp", false);
    C.gridContactMethods.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    C.gridContactMethods.Actions().SetEnabled("SelectDelete", true);
    C.gridContactMethods.Actions().SetEnabled("SelectUp", C.gridContactMethods.ActiveDataRowListIndex() != -1);
    C.gridContactMethods.Actions().SetEnabled("SelectDown", C.gridContactMethods.ActiveDataRowListIndex() != -1);
    C.gridContactMethods.Actions().SetEnabled("RowMoveUp", C.gridContactMethods.ActiveDataRowListIndex() != -1);
    C.gridContactMethods.Actions().SetEnabled("RowMoveDown", C.gridContactMethods.ActiveDataRowListIndex() != -1);
  }

  C.gridContactMethods.RefreshButtons();
}

// =========================
// Identification Paste Data
// =========================
function Identification_CanPasteName() {
  return (C.txtFirstName.Text() || C.txtMiddleNames.Text() || C.txtLastName.Text());
}

function Identification_PasteData(updateDetail) {
  // Format Names
  var nameFirstMiddle = C.txtFirstName.Text();
  if (C.txtMiddleNames.Text()) nameFirstMiddle = nameFirstMiddle + " " + C.txtMiddleNames.Text();

  var nameFull = nameFirstMiddle;
  if (C.txtLastName.Text()) nameFull = nameFull + " " + C.txtLastName.Text();

  // Update Controls
  var updateControls = true;
  switch (updateDetail) {
    case "AU_DL_PasteName":    
      C.txtAU_DL_OtherNames.Text(nameFirstMiddle);
      C.txtAU_DL_FamilyName.Text(C.txtLastName.Text());              
      break;
      
    case "AU_DL_PasteDOB":
      C.dateAU_DL_DateOfBirth.Value(C.dateDateOfBirth.Value());
      break;  
      
    case "AU_Passport_PasteName":
      C.txtAU_Passport_GivenNames.Text(nameFirstMiddle);
      C.txtAU_Passport_FamilyName.Text(C.txtLastName.Text());
      break;
      
    case "AU_Passport_PasteDOB":
      C.dateAU_Passport_DateOfBirth.Value(C.dateDateOfBirth.Value());
      break;
      
    case "AU_Medicare_PasteName":
      C.txtAU_Medicare_CardName.Text(nameFull);
      break;
      
    case "NZ_DL_PasteName":
      C.txtNZ_DL_OtherNames.Text(nameFirstMiddle);
      C.txtNZ_DL_FamilyName.Text(C.txtLastName.Text());
      break;
      
    case "NZ_DL_PasteDOB":
      C.dateNZ_DL_DateOfBirth.Value(C.dateDateOfBirth.Value());
      break;
      
    case "NZ_Passport_PasteName":
      C.txtNZ_Passport_GivenNames.Text(nameFirstMiddle);
      C.txtNZ_Passport_Surname.Text(C.txtLastName.Text());
      break;
      
    case "NZ_Passport_PasteDOB":
      C.dateNZ_Passport_DateOfBirth.Value(C.dateDateOfBirth.Value());
      break;
      
    case "US_DL_PasteName":
      C.txtUS_DL_OtherNames.Text(nameFirstMiddle);
      C.txtUS_DL_FamilyName.Text(C.txtLastName.Text());
      break;
      
    case "US_DL_PasteDOB":
      C.dateUS_DL_DateOfBirth.Value(C.dateDateOfBirth.Value());
      break;
      
    case "US_Passport_PasteName":
      C.txtUS_Passport_GivenNames.Text(nameFirstMiddle);
      C.txtUS_Passport_Surname.Text(C.txtLastName.Text());
      break;
      
    case "US_Passport_PasteDOB":
      C.dateUS_Passport_DateOfBirth.Value(C.dateDateOfBirth.Value());
      break;
      
    default:
      updateControls = false;
      break;
  }
  
  // Update Controls
  if (updateControls &amp;&amp; updateDetail) {
    if (updateDetail.indexOf("_DL_") != -1) {
      DriversLicence_Change();
    }
    else if (updateDetail.indexOf("_Passport_") != -1) {
      Passport_Change();
    }
    else if (updateDetail.indexOf("_Medicare_") != -1) {
      Medicare_Change();
    }
  }
}

// ===================
// Edit Contact Method
// ===================
function EditContactMethod(index) {
  mEditClientContactMethodIndex = index;
  var json = index == -1 ? "" : JSON.stringify(mRecord_ContactMethods[index]);
  
  // Parameters
  var params = {};
  if (mRecord.WidgetClientContactMethod_StartupParametersJson) params = JSON.parse(mRecord.WidgetClientContactMethod_StartupParametersJson);
  params.EditJson = true;
  params.ClientContactMethodJson = json;

  // Show Widget
  widget.UI.Forms.ShowHtmlWidgetModal(mRecord.WidgetClientContactMethod, { startupParametersJson: JSON.stringify(params) }, NewClientContactMethod_Notify);
}

function NewClientContactMethod_Notify(actionId, data) {
  // Parse
  data = JSON.parse(data);

  // Handle
  switch(actionId) {
    case "RecordUpdated":
      // Update underlying data
      var item;
      if (mEditClientContactMethodIndex == -1) {
        // New
        mRecord_ContactMethods.push(data);
      }
      else {
        // Existing
        mRecord_ContactMethods[mEditClientContactMethodIndex] = data;
      }
      
      // Refresh Grid
      gridContactMethods_Refresh();
      break;
  }
}

// ===============
// Edit Employment
// ===============
function EditEmployment(index) {
  mEditClientEmploymentIndex = index;
  var json = index == -1 ? "" : JSON.stringify(mRecord_Employments[index]);
  
  // Parameters
  var params = {};
  if (mRecord.WidgetClientEmployment_StartupParametersJson) params = JSON.parse(mRecord.WidgetClientEmployment_StartupParametersJson);
  params.EditJson = true;
  params.EditJsonIsIndividual = false;
  params.ClientEmploymentJson = json;

  // Show Widget
  widget.UI.Forms.ShowHtmlWidgetModal(mRecord.WidgetClientEmployment, { startupParametersJson: JSON.stringify(params) }, NewEmployment_Notify);
}

function NewEmployment_Notify(actionId, data) {
  // Parse
  data = JSON.parse(data);

  // Handle
  switch(actionId) {
    case "RecordUpdated":
      // Update underlying data
      var item;
      if (mEditClientEmploymentIndex == -1) {
        // New
        mRecord_Employments.push(data);
      }
      else {
        // Existing
        mRecord_Employments[mEditClientEmploymentIndex] = data;
      }
      
      // Refresh Grid
      gridEmployments_Refresh();
      
      // Set selected row
      if (mEditClientEmploymentIndex == -1) {
        C.gridEmployments.ActiveDataRowListIndex(mRecord_Employments.length - 1);
      }
      else {
        C.gridEmployments.ActiveDataRowListIndex(mEditClientEmploymentIndex);
      }
      break;
  }
}

// ===============
// gridEmployments
// ===============
function gridEmployments_Refresh() {
  // Show columns  
  var showHistoric = false;
  var showRoleType = false;
  var showOccupation = false;    
  var showJobTitle = false;
  var showBasis = false;
  var showType = false;
  var showDuration = false;
  var showNotes = false;  
  for (var i = 0; i &lt; mRecord_Employments.length; i++) {
    var item = mRecord_Employments[i];
    
    if (item.ShowAsHistoric) showHistoric = true;
    if (item.RoleType) showRoleType = true;
    if (item.Occupation) showOccupation = true;
    if (item.JobTitle) showJobTitle = true;
    if (item.EmploymentBasis) showBasis = true;
    if (item.EmploymentType) showType = true;
    if (item.TimeSpan) showDuration = true;
    if (item.Notes) showNotes = true;        
  }

  // Add Columns
  C.gridEmployments.ClearColumns();
  C.gridEmployments.AddColumnDrilldown();
  C.gridEmployments.AddColumnIcon("Historic", { visible: showHistoric });
  C.gridEmployments.AddColumnString("RoleType", { caption: "Role Type", visible: showRoleType });
  C.gridEmployments.AddColumnHtml("Name", { caption: "Related Party" });
  C.gridEmployments.AddColumnString("Occupation", { caption: "Occupation", visible: showOccupation });
  C.gridEmployments.AddColumnString("JobTitle", { caption: "Job Title", visible: showJobTitle });
  C.gridEmployments.AddColumnString("EmploymentBasis", { caption: "Basis", visible: showBasis });
  C.gridEmployments.AddColumnString("EmploymentType", { caption: "Type", visible: showType });
  C.gridEmployments.AddColumnString("TimeSpan", { caption: "Duration", visible: showDuration });
  C.gridEmployments.AddColumnString("Notes", { caption: "Notes", visible: showNotes });

  // Actions
  var actions = [];
  actions.push({ actionId: "Add", tooltipText: "Add an Employment", icon: "Grid_Row_Add" });
  actions.push({ actionId: "SelectDelete", tooltipText: "Delete selected row(s)", icon: "Grid_Row_Delete" });
  actions.push({});
  actions.push({ actionId: "SelectAll", tooltipText: "Select all rows", icon: "Select_All" });
  actions.push({ actionId: "SelectNone", tooltipText: "Select no rows", icon: "Select_None" });
  actions.push({ actionId: "SelectUp", tooltipText: "Select all rows above and including the current row", icon: "Select_Up" });
  actions.push({ actionId: "SelectDown", tooltipText: "Select all rows below and including the current row", icon: "Select_Down" });
  actions.push({});
  actions.push({ actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" });
  actions.push({ actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });
  C.gridEmployments.Actions().Define(actions);

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mRecord_Employments.GetCacheKey = function (index) {
    var item = mRecord_Employments[index];
    return JSON.stringify(item);
  };
  mRecord_Employments.GetPreviewFetchParameters = function (index) {
    var item = mRecord_Employments[index];
    var o = {};
    o.ClientEmploymentJson = JSON.stringify(item);
    return o;
  };

  // Refresh
  C.gridEmployments.VirtualDataRefresh(mRecord_Employments);
  
  // Select first row
  C.gridEmployments.ActivateFirstDataRow();
}

function gridEmployments_InitialiseRow(e) {
  var item = mRecord_Employments[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);
  
  // Styling 
  e.row.cells.Notes.small = true;
  
  // Handle different value types
  if (item.LinkedClientId) {
    // Has a Linked Client
    e.row.cells.Name.value = "&lt;div class='linked-client'&gt;&lt;img src='" + widget.GetIconUrl("Client") + "' /&gt;&lt;span class='inline-linked-client'&gt;&lt;a href='app://FormShow?form=Clients&amp;id=" + item.LinkedClientId + "'&gt;" + item.LinkedClientId + " (" + item.Name + ")&lt;/a&gt;&lt;/span&gt;&lt;/div&gt;";
  }
  
  // Historic
  if (item.ShowAsHistoric) {
    e.row.inactive = true;
    e.row.cells.Historic.value = "History";
    e.row.cells.Historic.tooltipText = "Historic";
  }
}

function gridEmployments_RowDrilldown(e) {
  EditEmployment(e.row.listIndex);
}

function gridEmployments_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "ADD":
      EditEmployment(-1);
      break;  
      
    case "SELECTDELETE":
      C.gridEmployments.RemoveSelectedRowsAndCollectionItems();
      break;
      
    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord_Employments.length; i++) {
        indexes.push(i);
      }
      break;
      
    case "SELECTNONE":
      var indexes = [];
      break;

    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridEmployments.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord_Employments.length; i++) {
        if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
          indexes.push(i);
        }
        else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
          indexes.push(i);
        }
      }
      break;  
      
    case "ROWMOVEDOWN":
      C.gridEmployments.RowMoveDown();
      break;

    case "ROWMOVEUP":
      C.gridEmployments.RowMoveUp();
      break;
  }
  
  // Set Indexes
  if(indexes) {
    C.gridEmployments.SetSelectedRowIndexes(indexes, true);
  }

  gridEmployments_RefreshButtons();
}

function gridEmployments_AfterRowActivate(e) {
  // Refresh Summary
  wbEmployments_Preview();

  // Refresh Buttons
  gridEmployments_RefreshButtons();
}

function gridEmployments_SelectedRowsChanged(e) {
  // Refresh Buttons
  gridEmployments_RefreshButtons();
}

function gridEmployments_RefreshButtons() {
  var rows = C.gridEmployments.GetSelectedRowIndexes(true, true);

  if (rows.length == 0) {
    C.gridEmployments.Actions().SetEnabled("SelectDelete", false);
    C.gridEmployments.Actions().SetEnabled("SelectUp", false);
    C.gridEmployments.Actions().SetEnabled("SelectDown", false);
    C.gridEmployments.Actions().SetEnabled("RowMoveUp", false);
    C.gridEmployments.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    C.gridEmployments.Actions().SetEnabled("SelectDelete", true);
    C.gridEmployments.Actions().SetEnabled("SelectUp", C.gridEmployments.ActiveDataRowListIndex() != -1);
    C.gridEmployments.Actions().SetEnabled("SelectDown", C.gridEmployments.ActiveDataRowListIndex() != -1);
    C.gridEmployments.Actions().SetEnabled("RowMoveUp", C.gridEmployments.ActiveDataRowListIndex() != -1);
    C.gridEmployments.Actions().SetEnabled("RowMoveDown", C.gridEmployments.ActiveDataRowListIndex() != -1);
  }

  C.gridEmployments.RefreshButtons();
}

// =============
// wbEmployments
// =============
function wbEmployments_Preview() {
  C.wbEmployments.PreviewFromGridCollection(C.gridEmployments, mRecord_Employments, "GetEmploymentItemPreview");
}

// ==================
// wbClientStatistics
// ==================
function wbClientStatistics_Preview() {
  // Preview
  if (mRecord_ClientStatisticsSetJson) {
    // Fetch
    widget.GetString("GetClientStatisticsSetSummary", { clientStatisticsSetJson: mRecord_ClientStatisticsSetJson },
      function (data) {
        C.wbClientStatistics.SetContent(data, false);
      },

      function (error) {
        widget.UI.MsgBoxAlert(error);
      });
  }
  else {
    C.wbClientStatistics.SetContent("&lt;html&gt;&lt;body style=\"font-size:13px; font-family:'Open Sans', Sans-serif, 'Helvetica Neue', Helvetica, Verdana, Arial\"&gt;&lt;i&gt;No Statistics have been entered for this Client. Use the button above to enter them.&lt;/i&gt;&lt;/body&gt;&lt;/html&gt;", true, {});
  }

  // Show/ Hide Clear Button
  if (mRecord_ClientStatisticsSetJson) {
    C.cmdStatisticsClear.show();
  }
  else {
    C.cmdStatisticsClear.hide();
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>NVcy1jEy4kimvPyBGbqXZg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1600</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 />
    <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="ShowClientCode" type="List">
            <BlankTip />
            <Caption>Show Client Code</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowExternalId" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowCrossReference" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowClientGroup" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowBranch" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowManager" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowOtherBankingDetails" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAkas" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowFullContactsGrid" 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="UseBuiltInClientContactMethodHTMLWidget" type="Boolean">
            <BlankTip />
            <Caption>Use Built-In Client Contact Method HTML Widget?</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="UseBuiltInClientEmploymentHTMLWidget" type="Boolean">
            <BlankTip />
            <Caption>Use Built-In Client Employment HTML Widget?</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="ShowNewRecordOnFinish" 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="CanEdit" type="Boolean">
            <BlankTip />
            <Caption>Can edit value if default provided?</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="IconListStyle" 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>Grid</Value>
            <Visible>true</Visible>
            <List>Grid,Vertical</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="PriorityClientTypes" type="Text">
            <BlankTip />
            <Caption>Priority Client Types</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>A comma-separated list of Contact Method Ids to highlight and show first.</TooltipText>
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Basic Client details.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>If left blank, defaults will be taken from the User Preferences -&gt; Clients -&gt; General page.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ClientGroupId" 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.ClientGroups</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Default Branch and Client Manager.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>If left blank, defaults will be taken from the User Preferences -&gt; Clients -&gt; General page.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="BranchId" 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.Branches</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ManagerUserId" 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.UsersCurrentActive</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Default Client details.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DefaultName" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>