<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-20T03:41:15.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-07-19T22:22:34.6800000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-20T03:40:52.2600000</UpdatedUtcDate>
    <ScriptId>CLIEMPLOYMENT</ScriptId>
    <Description>Client Employment Widget</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ClientEmployment
Option Explicit On
Option Strict On

' #################################################################
' Client Employment wizard HTML Widget
'
' Version: 1.11 (20/08/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.06  02/06/2021  ISS                Updated
'    1.07  04/03/2022  ISS      J028286   Fixed Share Employee grid for Organisations
'    1.08  28/07/2023  ISS      J031540   User Creation section is only displayed if a User can be created (User Permissions)
'    1.09  31/01/2024  ISS      J032709   Added Individual Date of Birth
'    1.10  17/07/2024  ISS      J032268   Added support for 'EditJson' as full Client Employments can now be added from the New Client wizards
'    1.11  20/08/2024  ISS      J034114   Added ability for a new Client to be added directly from this wizard
' #################################################################

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

' Standard Parameters
Private mClientId As String
Private mClientEmploymentPk As Integer
Private mReadOnly As Boolean
Private mReplaceRecordPk As Integer
Private mEditJson As Boolean
Private mEditJsonIsIndividual As Boolean
Private mClientEmploymentJson As String

' Other
Private mClient As finClient

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 Standard Parameters
  With mCombinedParameters
    mClientEmploymentJson = .GetString("ClientEmploymentJson")
    mClientEmploymentPk = .GetInteger("ClientEmploymentPk")
    mClientId = .GetString("ClientId")
    mEditJson = .GetBoolean("EditJson")
    mEditJsonIsIndividual = .GetBoolean("EditJsonIsIndividual")
    mReadOnly = .GetBoolean("ReadOnly")
    mReplaceRecordPk = .GetInteger("ReplaceRecordPk")
  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 "Delete"
      ' Delete Employment
      Main = Delete(returnValue)

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

    Case "FormatPhoneNumber"
      ' Format Phone Number
      Main = FormatPhoneNumber(returnValue)

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

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

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

End Function

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

  Dim ClientEmployment As finClientEmployment
  Dim Success As Boolean
  Dim User As finUser

  ' Assume Success
  Success = True

  ' Get Employment
  If Success Then
    Success = GetEmployment(mClientEmploymentPk, ClientEmployment)
  End If

  ' Validate
  If Success Then
  End If

  ' Delete and Save
  If Success Then
    If finBL.Database.TransactionBegin() Then
      ' Delete User
      If Len(ClientEmployment.ExternalUserId) &lt;&gt; 0 Then
        User = finBL.CreateUser()
        If User.Load(ClientEmployment.ExternalUserId) Then
          Success = User.Delete()
        Else
          Success = False
        End If
      End If

      ' Delete Employment
      If Success Then mClient.Employments.Remove(ClientEmployment)

      ' Save Client
      If Success Then Success = mClient.Save()

      ' Commit/ Rollback Transaction
      If Success Then
        finBL.Database.TransactionCommit()
      Else
        finBL.Database.TransactionRollback()
      End If
    Else
      Success = False
    End If
  End If

  Return Success

End Function

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

  Dim ClientEmployment As finClientEmployment
  Dim ClientEmploymentReplace As finClientEmployment
  Dim Index As Integer
  Dim InTransaction As Boolean
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean
  
  ' Assume Success
  Success = True

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

  ' Get Employment
  If Success Then
    Success = GetEmployment(mClientEmploymentPk, ClientEmployment)
  End If

  ' Get record being replaced
  If Success AndAlso mReplaceRecordPk &lt;&gt; 0 Then
    Success = GetEmployment(mReplaceRecordPk, ClientEmploymentReplace)
  End If

  ' Start Transaction
  If Success AndAlso (Not mEditJson) Then
    If finBL.Database.TransactionBegin() Then
      InTransaction = True
    Else 
      Success = False
    End If
  End If
  
  ' Update and Save
  If Success Then
    ' Update Client Employment
    With ClientEmployment
      ' General
      .IsIndividual = (Record.EmploymentClientType = "Individual")
      .IsOrganisation = (Record.EmploymentClientType = "Organisation")
      .RoleType = Record.RoleType
      .ActiveSalesRep = Record.ActiveSalesRep
      .AvailableToSubExternalParties = Record.AvailableToSubExternalParties
      .LinkedClientId = Record.LinkedClientId
      .IndividualTitle = Record.Title
      .IndividualFirstName = Record.FirstName
      .IndividualMiddleNames = Record.MiddleNames
      .IndividualLastName = Record.LastName
      .IndividualDateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateOfBirth)
      .IndividualGenderText = Record.Gender
      .OrganisationName = Record.Name
      .PhoneNumber = Record.PhoneNumber
      .Extension = Record.Extension
      .Email = Record.Email

      .Occupation = Record.Occupation
      .JobTitle = Record.JobTitle
      .EmploymentType = Record.EmploymentType
      .EmploymentBasis = Record.EmploymentBasis

      .Notes = Record.Notes

      If Record.DateStart Is Nothing Then
        .DateStart = Nothing
      Else
        .DateStart = CDate(Record.DateStart)
      End If
      If Record.DateStop Is Nothing Then
        .DateStop = Nothing
      Else
        .DateStop = CDate(Record.DateStop)
      End If
      .Historic = Record.Historic

      ' External Party Employee
      .ClientEmploymentId = Record.Code
      .ExternalPartyManager = Record.ExternalPartyManager
      .ExternalPartyViewSubAccounts = Record.ExternalPartyViewSubAccounts
      .ExternalPartySubAccountsFilter = Record.ExternalPartySubAccountsFilter
      .ExternalPartyShareAccounts = Record.ExternalPartyShareAccounts
      .ExternalPartyShareEmployeePks = GetExternalPartyShareEmployeePks(Record.ExternalPartyShareEmployees)
    End With

    ' Move?
    If Not mEditJson Then
      Select Case Record.MoveAction
        Case "MoveTop"
          Index = mClient.Employments.IndexOf(ClientEmployment)
          mClient.Employments.Move(Index, 0)
      End Select
    End If      

    ' Other Validation
    If Len(Record.LinkedClientId) &lt;&gt; 0 AndAlso ClientEmployment.LinkedClientPk = 0 Then
      Success = False
      finBL.Error.ErrorBeginFormat("Invalid Client '{0}'.", Record.LinkedClientId)
    End If

    ' Replace Record?
    If Not mEditJson Then
      If Success AndAlso ClientEmploymentReplace IsNot Nothing Then
        ' Expire
        If ClientEmployment.DateStart = Nothing Then
          ClientEmploymentReplace.DateStop = DateAdd(DateInterval.Day, -1, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
        Else
          ClientEmploymentReplace.DateStop = DateAdd(DateInterval.Day, -1, ClientEmployment.DateStart)
        End If

        ' Ensure new record is directly before old one
        mClient.Employments.Remove(ClientEmployment)
        mClient.Employments.Insert(mClient.Employments.IndexOf(ClientEmploymentReplace), ClientEmployment)
      End If
    End If      

    ' Save
    If Success Then
      If mEditJson Then
        returnValue = ClientEmployment.ToHtmlWidgetJsonString()
      Else 
        Success = mClient.Save()
      End If        
    End If

    ' Add User?
    If Success AndAlso Record.CreateUser AndAlso Not mEditJson Then
      Success = ClientEmployment.AddUser(Record.DuplicateUserId, True, True, "")
    End If
  End If

  ' Transaction Handling
  If InTransaction Then
    If Success Then
      finBL.Database.TransactionCommit()
    Else 
      finBL.Database.TransactionRollback()
    End If
  End If
  
  Return Success

End Function

''' &lt;summary&gt;
'''  Format a Phone Number.
''' &lt;/summary&gt;
Private Function FormatPhoneNumber(ByRef returnValue As String) As Boolean

  Dim Comment As String
  Dim Data As Object
  Dim PhoneNumber As String
  Dim PhoneNumberFormatted As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters (don't use combined parameters in case there is a clash)
  With mParameters
    PhoneNumber = .GetString("PhoneNumber")
  End With

  ' Format
  If Success Then
    PhoneNumberFormatted = finBL.CurrentCountry.FormatPhoneNumber(PhoneNumber, Comment)
    If PhoneNumberFormatted = Comment Then Comment = ""
  End If

  ' Format Return Value
  If Success AndAlso PhoneNumberFormatted &lt;&gt; PhoneNumber Then
    Data = New With {
      .PhoneNumber = PhoneNumberFormatted,
      .Notes = Comment
    }
  End If

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

  ' NOTE: Always return True since this is a helper method that gives the User the option to accept the formatted details
  Return True

End Function

''' &lt;summary&gt;
'''  Load Client.
''' &lt;/summary&gt;
Private Function GetClient() As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Create Empty Client if new Client Wizard
  If mEditJson Then
    mClient = finBL.CreateClient()
  End If
  
  ' Shortcut
  If mClient IsNot Nothing Then
    Return Success
  End If

  ' Validate
  If Len(mClientId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Client Id not specified.")
  ElseIf finBL.CurrentUserInformation.IsClientFilteredOut(mClientId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Client.")
  End If

  ' Create and Load Client
  If Success Then
    ' Create Client
    mClient = finBL.CreateClient()

    ' Load Client
    If mClient.Load(mClientId) Then
      ' Validate
      If mClient.IsNew Then
        Success = False
        finBL.Error.ErrorBeginFormat("Client '{0}' not found.", mClientId)
      End If
    Else
      Success = False
    End If
  End If

  ' Load Employments
  If Success Then
    Success = mClient.EmploymentsLoad()
  End If

  ' Clear Client if failed
  If Not Success Then
    mClient = Nothing
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Load Client Employment.
''' &lt;/summary&gt;
Private Function GetEmployment(recordPk As Integer,
                               ByRef clientEmployment As finClientEmployment) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Intialise ByRef
  clientEmployment = Nothing

  ' Validate
  If (Not mEditJson) AndAlso (recordPk = 0 OrElse recordPk &lt; -1) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Employment Pk {0}.", recordPk)
  End If

  ' Load Client
  If Success Then
    Success = GetClient()
  End If

  ' Get Employment
  If Success Then
    If mEditJson Then
      ' New Client Wizard
      clientEmployment = mClient.Employments.CreateClientEmployment()
      
      If Len(mClientEmploymentJson) &lt;&gt; 0 Then
        Success = clientEmployment.FromHtmlWidgetJsonString(mClientEmploymentJson)
      End If  
    ElseIf recordPk = -1 Then
      ' New
      clientEmployment = mClient.Employments.CreateClientEmployment()
      mClient.Employments.Add(clientEmployment)
    Else
      ' Existing
      If mClient.Employments.ExistsPk(recordPk) Then
        clientEmployment = mClient.Employments.ItemByPk(recordPk)
      Else
        Success = False
        finBL.Error.ErrorBeginFormat("Employment {0} not found.", recordPk)
      End If
    End If
  End If

  Return Success

End Function

Private Function GetExternalPartyShareEmployeeList(clientEmployments As finClientEmployments,
                                                   externalPartyShareEmployeePks As String) As List(Of ExternalPartyShareEmployee)

  Dim ClientEmployment As finClientEmployment
  Dim ExternalPartyShareEmployeePkList As ISList
  Dim ExternalPartyShareEmployees As List(Of ExternalPartyShareEmployee)

  ' Initialise
  ExternalPartyShareEmployees = New List(Of ExternalPartyShareEmployee)
  ExternalPartyShareEmployeePkList = New ISList()

  ' Load External Party Share Employees Pks
  ExternalPartyShareEmployeePkList.FromCsvString(externalPartyShareEmployeePks)

  ' Get External PArty Share Employees
  For Each ClientEmployment In clientEmployments
    With ClientEmployment
      If .IsExternalPartyEmployee AndAlso Not .IsNew Then
        ExternalPartyShareEmployees.Add(New ExternalPartyShareEmployee(.ClientEmploymentId, .IndividualName, .Pk, ExternalPartyShareEmployeePkList.Exists(CStr(.Pk))))
      End If
    End With
  Next

  Return ExternalPartyShareEmployees

End Function

Private Function GetExternalPartyShareEmployeePks(externalPartyShareEmployeeList As List(Of ExternalPartyShareEmployee)) As String

  Dim ExternalPartyShareEmployee As ExternalPartyShareEmployee
  Dim ExternalPartyShareEmployeePkList As ISList

  ' Initialise
  ExternalPartyShareEmployeePkList = New ISList()

  For Each ExternalPartyShareEmployee In externalPartyShareEmployeeList
    If ExternalPartyShareEmployee.Share Then
      ExternalPartyShareEmployeePkList.Add(CStr(ExternalPartyShareEmployee.Pk))
    End If
  Next

  Return ExternalPartyShareEmployeePkList.ToCsvString()

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 ClientEmployment As finClientEmployment
  Dim ClientEmploymentReplace As finClientEmployment
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim strTemp As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If mReplaceRecordPk &lt;&gt; 0 Then
    If mClientEmploymentPk &lt;&gt; -1 Then
      Success = False
      finBL.Error.ErrorBegin("When replacing a Client Employment, ClientEmploymentPk must be -1.")
    ElseIf mReplaceRecordPk &lt; 0 Then
      Success = False
      finBL.Error.ErrorBeginFormat("Invalid Replace Record Pk {0}.", mReplaceRecordPk)
    End If
  End If

  ' Get Employment
  If success Then
    Success = GetEmployment(mClientEmploymentPk, ClientEmployment)
  End If

  ' Get record being replaced
  If Success AndAlso mReplaceRecordPk &lt;&gt; 0 Then
    Success = GetEmployment(mReplaceRecordPk, ClientEmploymentReplace)
  End If

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

      ' Record
      .IsNew = ClientEmployment.IsNew
      .Timestamp = ClientEmployment.Timestamp

      ' Client
      .ClientId = mClient.ClientId
      .ClientName = mClient.Name
      .ClientIsOrganisation = mClient.IsOrganisation
      .ClientIsExternalParty = (mClient.SpecialType = isefinClientSpecialType.ExternalParty)

      ' Employment Client Type
      If mEditJson Then
        If Len(mClientEmploymentJson) = 0 Then
          If mEditJsonIsIndividual Then
            .EmploymentClientType = "Organisation"
          Else 
            .EmploymentClientType = "Individual"
          End If
        Else 
          If ClientEmployment.IsIndividual Then
            .EmploymentClientType = "Individual"
          Else
            .EmploymentClientType = "Organisation"
          End If
        End If
      ElseIf ClientEmployment.IsNew Then
        If mClient.IsOrganisation Then
          .EmploymentClientType = "Individual"
        Else
          .EmploymentClientType = "Organisation"
        End If
      Else
        If ClientEmployment.IsIndividual Then
          .EmploymentClientType = "Individual"
        Else
          .EmploymentClientType = "Organisation"
        End If
      End If      
      
      ' General
      .RoleType = ClientEmployment.RoleType
      .ActiveSalesRep = ClientEmployment.ActiveSalesRep
      .AvailableToSubExternalParties = ClientEmployment.AvailableToSubExternalParties
      .LinkedClientId = ClientEmployment.LinkedClientId
      .Title = ClientEmployment.IndividualTitle
      .FirstName = ClientEmployment.IndividualFirstName
      .MiddleNames = ClientEmployment.IndividualMiddleNames
      .LastName = ClientEmployment.IndividualLastName
      .DateOfBirth = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(ClientEmployment.IndividualDateOfBirth)
      .Gender = ClientEmployment.IndividualGenderText
      .Name = ClientEmployment.OrganisationName
      .PhoneNumber = ClientEmployment.PhoneNumber
      .Extension = ClientEmployment.Extension
      .Email = ClientEmployment.Email

      .Occupation = clientEmployment.Occupation
      .JobTitle = clientEmployment.JobTitle
      .EmploymentType = clientEmployment.EmploymentType
      .EmploymentBasis = clientEmployment.EmploymentBasis

      .Notes = ClientEmployment.Notes

      .DateStart = finBL.Runtime.DateUtilities.CastToNullableUtcDate(ClientEmployment.DateStart)
      .DateStop = finBL.Runtime.DateUtilities.CastToNullableUtcDate(ClientEmployment.DateStop)
      .Historic = ClientEmployment.Historic

      ' External Party Employee
      .Code = clientEmployment.ClientEmploymentId
      .ExternalUserId = clientEmployment.ExternalUserId
      .ExternalPartyManager = ClientEmployment.ExternalPartyManager
      .ExternalPartyViewSubAccounts = ClientEmployment.ExternalPartyViewSubAccounts
      .ExternalPartySubAccountsFilter = ClientEmployment.ExternalPartySubAccountsFilter
      .ExternalPartyShareAccounts = ClientEmployment.ExternalPartyShareAccounts
      .ExternalPartyShareEmployees = GetExternalPartyShareEmployeeList(mClient.Employments, ClientEmployment.ExternalPartyShareEmployeePks)

      ' Replacing Record details
      If ClientEmploymentReplace IsNot Nothing Then
        If mClient.IsOrganisation Then
          .ReplaceRecordDetails = ClientEmploymentReplace.IndividualName
        Else
          .ReplaceRecordDetails = ClientEmploymentReplace.OrganisationName
        End If

        .DateStart = finBL.Runtime.DateUtilities.CastToNullableUtcDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())

        strTemp = "Changed from:" &amp; vbNewLine &amp; .ReplaceRecordDetails
        If Len(.Notes) &lt;&gt; 0 Then strTemp &amp;= vbNewLine &amp; vbNewLine &amp; .Notes
        .Notes = strTemp
      End If

      ' Lists
      .GendersList = finBL.Enums.isefinGender_GetList().ToCsvString()

      ' Configuration Options
      .AddOnExternalUsers = finBL.Settings.AddOns.ExternalUsers
      .AlwaysShowAdvanced = mCombinedParameters.GetBoolean("AlwaysShowAdvanced", False)
      .CanCreateUser = (finBL.CurrentUser.IsAdministrator OrElse finBL.CurrentUser.IsUserAdministrator OrElse (.ClientIsExternalParty AndAlso finBL.CurrentUser.Permissions.Allow("ExternalParty.AddUser")))
      .EditJson = mEditJson
      .WidgetNewIndividualClient = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientNew_Individual, mCombinedParameters.GetBoolean("UseBuiltInNewIndividualClientHTMLWidget"), strTemp)
      .WidgetNewIndividualClient_StartupParametersJson = strTemp
      .WidgetNewOrganisationClient = finBL.CloudConnectFunctions.GetClientHtmlWidgetId(isefinCloudConnectClientScriptType.HtmlWidgetClientNew_Organisation, mCombinedParameters.GetBoolean("UseBuiltInNewOrganisationClientHTMLWidget"), strTemp)
      .WidgetNewOrganisationClient_StartupParametersJson = strTemp
      
      If mEditJson Then
        ' From New Client wizard
        .CanDelete = False
      ElseIf .ReadOnly OrElse .IsNew Then
        .CanDelete = False
      Else
        .CanDelete = finBL.CurrentUser.Permissions.Allow("Client.Employments.Delete")
      End If
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
    End With
  End If

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

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

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

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

  Return Success

End Function

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

  Dim ClientEmployment As finClientEmployment
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

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

  ' Get Employment
  If Success Then
    Success = GetEmployment(mClientEmploymentPk, ClientEmployment)
  End If

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

  Return Success

End Function


Public Class ExternalPartyShareEmployee

  Public ClientEmploymentId As String
  Public Name As String
  Public Pk As Integer
  Public Share As Boolean

  Public Sub New(clientEmploymentId As String,
                 name As String,
                 pk As Integer,
                 share As Boolean)

    Me.ClientEmploymentId = clientEmploymentId
    Me.Name = name
    Me.Pk = pk
    Me.Share = share

  End Sub

End Class


''' &lt;summary&gt;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
''' &lt;remarks&gt;
'''  This object is also used to save the Employment.
''' &lt;/remarks&gt;
Public Class FormInitialisationInfo

  ' Record
  Public IsNew As Boolean
  Public Timestamp As Integer

  ' Client Properties
  Public ClientId As String
  Public ClientName As String
  Public ClientIsOrganisation As Boolean
  Public ClientIsExternalParty As Boolean

  ' General
  Public EmploymentClientType As String
  Public RoleType As String
  Public ActiveSalesRep As Boolean
  Public AvailableToSubExternalParties As Boolean
  Public LinkedClientId As String
  Public Name As String
  Public Title As String
  Public FirstName As String
  Public MiddleNames As String
  Public LastName As String
  Public DateOfBirth As Date?
  Public Gender As String

  Public PhoneNumber As String
  Public Extension As String
  Public Email As String

  Public Occupation As String
  Public JobTitle As String
  Public EmploymentType As String
  Public EmploymentBasis As String

  Public Notes As String

  Public DateStart As Date?
  Public DateStop As Date?
  Public Historic As Boolean

  ' External Party Employee
  Public Code As String
  Public ExternalUserId As String
  Public ExternalPartyManager As Boolean
  Public ExternalPartyViewSubAccounts As Boolean
  Public ExternalPartySubAccountsFilter As String
  Public ExternalPartyShareAccounts As Boolean
  Public ExternalPartyShareEmployees As List(Of ExternalPartyShareEmployee)

  ' Replace Record details
  Public ReplaceRecordDetails As String

  ' Permissions
  Public CanCreateUser As Boolean
  Public CanDelete As Boolean  

  ' Lists
  Public GendersList As String

  ' Configuration
  Public AddOnExternalUsers As Boolean
  Public AlwaysShowAdvanced As Boolean
  Public EditJson As Boolean  
  Public PromptOnSave As Boolean
  Public [ReadOnly] As Boolean
  Public WidgetNewIndividualClient As String
  Public WidgetNewIndividualClient_StartupParametersJson As String
  Public WidgetNewOrganisationClient As String
  Public WidgetNewOrganisationClient_StartupParametersJson As String

  ' Other
  Public CreateUser As Boolean
  Public DuplicateUserId As String
  Public MoveAction As String

End Class


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

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

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

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

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System-supplied HTML Widget to add, edit or delete a Client Employment.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General"&gt;Employment Details&lt;/li&gt;
        &lt;li tabId="ExternalPartyEmployee" tooltipText="Enter External Party Employee-specific details."&gt;External Party Employee&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- General --&gt;
    &lt;div id="pageGeneral" class="flex-panels"&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="lblNameOrClient"&gt;Name or Client&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="rblEmploymentClientType" style="padding-bottom:8px"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboLinkedClient"&gt;Client:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboLinkedClient"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trNewClient"&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td&gt;&lt;button id="cmdAddClient" class="is-button small"&gt;Add New Client&lt;/button&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trNameIndividual"&gt;
          &lt;th&gt;&lt;label for="txtFirstName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;table id="tblPersonName" class="is-form" style="width:auto"&gt;
              &lt;tbody&gt;
                &lt;tr&gt;
                  &lt;td style="padding-right:2px"&gt;&lt;input id="cboTitle"/&gt;&lt;/td&gt;
                  &lt;td style="padding-right:2px"&gt;&lt;input id="txtFirstName"/&gt;&lt;/td&gt;
                  &lt;td style="padding-right:2px"&gt;&lt;input id="txtMiddleNames"/&gt;&lt;/td&gt;
                  &lt;td style="padding-right:2px"&gt;&lt;input id="txtLastName"/&gt;&lt;/td&gt;
                &lt;/tr&gt;
              &lt;/tbody&gt;
            &lt;/table&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 id="trPhoneNumber"&gt;
           &lt;th&gt;&lt;label for="txtPhoneNumber"&gt;Phone:&lt;/label&gt;&lt;/th&gt;
           &lt;td&gt;
            &lt;table id="tblPhoneNumber" class="is-form" style="width:auto"&gt;
              &lt;tbody&gt;
                &lt;tr&gt;
                  &lt;td style="padding-right:2px"&gt;&lt;input id="txtPhoneNumber"/&gt;&lt;/td&gt;
                  &lt;td style="padding-right:2px"&gt;&lt;input id="txtExtension"/&gt;&lt;/td&gt;
                &lt;/tr&gt;
              &lt;/tbody&gt;
            &lt;/table&gt;
           &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtEmail"&gt;Email:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtEmail"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblEmploymentDetails"&gt;Employment details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRoleType"&gt;Role Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRoleType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkActiveSalesRep" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkAvailableToSubExternalParties" type="checkbox" /&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;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="cboEmploymentType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboEmploymentType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboEmploymentBasis"&gt;Basis:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboEmploymentBasis"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr class="advanced" id="trEmploymentPeriod"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPeriod"&gt;Employment Period&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr class="advanced" id="trDateStart"&gt;
          &lt;th&gt;&lt;label for="dateStart"&gt;From:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateStart"/&gt; &lt;small&gt;to&lt;/small&gt; &lt;input id="dateStop"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr class="advanced" id="trHistoric"&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkHistoric" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;th colspan="2"&gt;&lt;label id="lblNotes"&gt;Notes&lt;/label&gt;&lt;/th&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="txtNotes" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- ExternalPartyEmployee --&gt;
    &lt;div id="pageExternalPartyEmployee" class="flex-panels"&gt;
      &lt;div class="panel-fixed"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:5em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tbody&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblEmployeeCode"&gt;Enter the Employee's code or leave blank to automatically assign a code&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtCode"&gt;Code:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtCode"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;

          &lt;tbody id="tbCreateUser"&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblCreateUser"&gt;Optionally, create a User record so that this Employee can sign-in to finPOWER Connect&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkCreateUser" type="checkbox" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th class="indent1"&gt;&lt;label for="cboDuplicateUser"&gt;Duplicate:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboDuplicateUser"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr id="trCreateUserInformation"&gt;
              &lt;th colspan="2"&gt;&lt;div id="divCreateUserInformation" class="is-info-text info small"&gt;The new User record will be inactive until you edit it to activate and set a sign-in password for the new User.&lt;/div&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;

          &lt;tbody&gt;          
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblExternalPartyAccounts"&gt;External User access&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkExternalPartyManager" type="checkbox" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkExternalPartyCanViewSubAccounts" type="checkbox" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtExternalPartySubAccountsFilter"&gt;Filter:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtExternalPartySubAccountsFilter"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkExternalPartyShareAccounts" type="checkbox" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div class="panel-flex gap-top" style="min-height:200px"&gt;
        &lt;div id="gridExternalPartyShareEmployees" class="is-dock-fill border"&gt;&lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdActions"/&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;Save&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;


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

var mOriginalJson;

// Controls
var C = {
  //   General
  lblNameOrClient: null,
  rblEmploymentClientType: null,
  cboLinkedClient: null,
  trNewClient: null,
  txtName: null,
  trNameIndividual: null,
  cboTitle: null,
  txtFirstName: null,
  txtMiddleNames: null,
  txtLastName: null,
  dateDateOfBirth: null,
  cboGender: null,
  trPhoneNumber: null,
  txtPhoneNumber: null,
  txtExtension: null,
  txtExtension: null,
  txtEmail: null,

  lblEmploymentDetails: null,
  cboRoleType: null,
  chkActiveSalesRep: null,
  chkAvailableToSubExternalParties: null,
  cboOccupation: null,
  cboJobTitle: null,
  cboEmploymentType: null,
  cboEmploymentBasis: null,

  lblNotes: null,
  txtNotes: null,

  trEmploymentPeriod: null,
  lblPeriod: null,
  trDateStart: null,
  dateStart: null,
  dateStop: null,
  trHistoric: null,
  chkHistoric: null,

  pulPromptUpdateList_Value: null,

  //   External Party Employee
  lblEmployeeCode: null,
  txtCode: null,

  tbCreateUser: null,
  lblCreateUser: null,
  chkCreateUser: null,
  cboDuplicateUser: null,
  trCreateUserInformation: null,
  divCreateUserInformation: null,

  lblExternalPartyAccounts: null,
  chkExternalPartyManager: null,
  chkExternalPartyCanViewSubAccounts: null,
  txtExternalPartySubAccountsFilter: null,
  chkExternalPartyShareAccounts: null,
  gridExternalPartyShareEmployees: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdAdvanced;
var cmdAddClient;

// Other
var mAdvancedVisible = false;
var mContactMethod;
var mHasAdvancedOptions = false;
var mRequiresRefresh = false;
var mValueData;

// ==========
// Initialise
// ==========
$(function () {

  // --------
  // Controls
  // --------
  //   General
  C.trNameIndividual = $("#trNameIndividual");
  C.lblNameOrClient = widget.UI.Label("lblNameOrClient", {});
  C.rblEmploymentClientType = widget.UI.RadioButtonList("rblEmploymentClientType", {
    allowBlank: false,

    onChange: rblEmploymentClientType_Change,
  });
  C.cboLinkedClient = widget.UI.DBCombo("cboLinkedClient", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
    onChange: cboLinkedClient_Change
  });
  C.trNewClient = $("#trNewClient");
  C.txtName = widget.UI.TextBox("txtName", {
    allowBlank: false,
    maxLength: 100,
  });
  C.cboTitle = widget.UI.InformationListComboBox("cboTitle", {
    maxLength: 20,
    width: "8em",
  });
  C.txtFirstName = widget.UI.TextBox("txtFirstName", {
    allowBlank: false,
    maxLength: 40,
    width: "12em",
    blankTip: "First",
  });
  C.txtMiddleNames = widget.UI.TextBox("txtMiddleNames", {
    maxLength: 60,
    width: "12em",
    blankTip: "Middle",
  });
  C.txtLastName = widget.UI.TextBox("txtLastName", {
    allowBlank: false,
    maxLength: 40,
    width: "12em",
    blankTip: "Last",
  });
  C.dateDateOfBirth = widget.UI.DateBox("dateDateOfBirth", {
    historic: true,
    minValue: new Date(1900, 0, 1),
    maxValue: new Date(),
    showAge: true,
  });  
  C.cboGender = widget.UI.ComboBox("cboGender", {
    limitToList: true,
    maxLength: 15,
  });
  C.trPhoneNumber = $("#trPhoneNumber");
  C.txtPhoneNumber = widget.UI.TextBox("txtPhoneNumber", {
    maxLength: 20,
    width: "12em",

    onChange: txtPhoneNumber_Change,
  });
  C.txtExtension = widget.UI.TextBox("txtExtension", {
    maxLength: 20,
    width: "4em",
    blankTip: "Ext",
  });
  C.txtEmail = widget.UI.TextBox("txtEmail", {
    maxLength: 255,
  });

  C.lblEmploymentDetails = widget.UI.Label("lblEmploymentDetails", {});
  C.cboRoleType = widget.UI.InformationListComboBox("cboRoleType", {
    maxLength: 50,
  });
  C.chkActiveSalesRep = widget.UI.CheckBox("chkActiveSalesRep", {
    caption: "Active Sales Representative?",
  });
  C.chkAvailableToSubExternalParties = widget.UI.CheckBox("chkAvailableToSubExternalParties", {
    caption: "Available to Sub External Parties?",
  });
  C.cboOccupation = widget.UI.InformationListComboBox("cboOccupation", {
    maxLength: 50,
  });
  C.cboJobTitle = widget.UI.InformationListComboBox("cboJobTitle", {
    maxLength: 50,
  });
  C.cboEmploymentType = widget.UI.InformationListComboBox("cboEmploymentType", {
    maxLength: 50,
  });
  C.cboEmploymentBasis = widget.UI.InformationListComboBox("cboEmploymentBasis", {
    maxLength: 50,
  });

  C.pulPromptUpdateList_Value = widget.UI.PromptUpdateList({
    onAccept: pulPromptUpdateList_Value_Accept
  });

  C.lblNotes = widget.UI.Label("lblNotes", {});
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    maxLength: 255,
    multiLine: true,
    rows: 5,
    spellCheck: true,
  });

  C.trEmploymentPeriod = $("#trEmploymentPeriod");
  C.lblPeriod = widget.UI.Label("lblPeriod", {});
  C.trDateStart = $("#trDateStart");
  C.dateStart = widget.UI.DateBox("dateStart", {});
  C.dateStop = widget.UI.DateBox("dateStop", {});
  C.trHistoric= $("#trHistoric");
  C.chkHistoric = widget.UI.CheckBox("chkHistoric", {
    caption: "Historic (dates not available or are estimates)?",
  });

  //   External Party Employee
  C.lblEmployeeCode = widget.UI.Label("lblEmployeeCode", {});
  C.txtCode = widget.UI.TextBox("txtCode", {
    maxLength: 20,
  });

  C.tbCreateUser = $("#tbCreateUser");
  C.lblCreateUser = widget.UI.Label("lblCreateUser", {
    tooltipText: "When you opt to create a User, the User record can be based upon (i.e., be a duplicate of) an existing User.\n\nThis will copy all of the existing User's settings to the new User.",
  });
  C.chkCreateUser = widget.UI.CheckBox("chkCreateUser", {
    caption: "Create finPOWER Connect User?",
    onChange: pageExternalPartyEmployee_Refresh
  });
  C.cboDuplicateUser = widget.UI.DBCombo("cboDuplicateUser", {
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.trCreateUserInformation = $("#trCreateUserInformation");
  C.divCreateUserInformation = $("#divCreateUserInformation");

  C.lblExternalPartyAccounts = widget.UI.Label("lblExternalPartyAccounts", {});
  C.chkExternalPartyManager = widget.UI.CheckBox("chkExternalPartyManager", {
    caption: "Manager (can view all other Employees' Accounts)?",
  });
  C.chkExternalPartyCanViewSubAccounts = widget.UI.CheckBox("chkExternalPartyCanViewSubAccounts", {
    caption: "Accounts for sub External Parties?",
  });
  C.txtExternalPartySubAccountsFilter = widget.UI.TextBox("txtExternalPartySubAccountsFilter", {
    maxLength: 255,
  });
  C.chkExternalPartyShareAccounts = widget.UI.CheckBox("chkExternalPartyShareAccounts", {
    caption: "Share with other External Party Employees?",
    onChange: chkExternalPartyShareAccounts_Change,
  });

    // Grids
  C.gridExternalPartyShareEmployees = widget.UI.Grid("gridExternalPartyShareEmployees", {
    rowNumbering: false,
    stickyHeader: true,
    onInitialiseRow: gridExternalPartyShareEmployees_InitialiseRow,
    onBeforeCellUpdate: gridExternalPartyShareEmployees_BeforeCellUpdate,
  });

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

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

  // Handle resize
  $(window).resize(Form_Resize);

  // 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(tabWizard_Cancel);
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(function () {
    // Toggle Advanced
    mAdvancedVisible = !mAdvancedVisible;
    pageGeneral_Refresh();
  });
  
  cmdAddClient = $("#cmdAddClient");
  cmdAddClient.click(function() { Form_ExecuteAction("AddClient"); });

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Set Tab
  tabWizard.SelectedTabId("General");

  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    Record_Load_Done,

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

function Record_Load_Done(data) {
  // Initialise
  mRecord = JSON.parse(data);

  // Load Fields
  Fields_Load();

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

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

  // Save Fields (so data is in correct format for mOriginalJson)
  Fields_Save();

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboLinkedClient.Text(mRecord.LinkedClientId);
    C.txtName.Text(mRecord.Name);
    C.cboTitle.Text(mRecord.Title);
    C.txtFirstName.Text(mRecord.FirstName);
    C.txtMiddleNames.Text(mRecord.MiddleNames);
    C.txtLastName.Text(mRecord.LastName);
    C.dateDateOfBirth.Value(mRecord.DateOfBirth);
    C.cboGender.Text(mRecord.Gender);
    C.txtPhoneNumber.Text(mRecord.PhoneNumber);
    C.txtExtension.Text(mRecord.Extension);
    C.txtEmail.Text(mRecord.Email);

    C.cboRoleType.Text(mRecord.RoleType);
    C.chkActiveSalesRep.Value(mRecord.ActiveSalesRep);
    C.chkAvailableToSubExternalParties.Value(mRecord.AvailableToSubExternalParties);
    C.cboOccupation.Text(mRecord.Occupation);
    C.cboJobTitle.Text(mRecord.JobTitle);
    C.cboEmploymentType.Text(mRecord.EmploymentType);
    C.cboEmploymentBasis.Text(mRecord.EmploymentBasis);

    C.txtNotes.Text(mRecord.Notes);

    C.dateStart.Value(mRecord.DateStart);
    C.dateStop.Value(mRecord.DateStop);
    C.chkHistoric.Value(mRecord.Historic);

    // External Party Employee
    C.txtCode.Text(mRecord.Code);
    C.chkExternalPartyManager.Value(mRecord.ExternalPartyManager);
    C.chkExternalPartyCanViewSubAccounts.Value(mRecord.ExternalPartyViewSubAccounts);
    C.txtExternalPartySubAccountsFilter.Text(mRecord.ExternalPartySubAccountsFilter);
    C.chkExternalPartyShareAccounts.Value(mRecord.ExternalPartyShareAccounts);

    gridExternalPartyShareEmployees_Refresh();
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord.EmploymentClientType = C.rblEmploymentClientType.Value();
  mRecord.LinkedClientId = C.cboLinkedClient.Text();
  mRecord.Name = C.txtName.Text();
  mRecord.Title = C.cboTitle.Text();
  mRecord.FirstName = C.txtFirstName.Text();
  mRecord.MiddleNames = C.txtMiddleNames.Text();
  mRecord.LastName = C.txtLastName.Text();
  mRecord.DateOfBirth = C.dateDateOfBirth.Value();
  mRecord.Gender = C.cboGender.Text();
  mRecord.PhoneNumber = C.txtPhoneNumber.Text();
  mRecord.Extension = C.txtExtension.Text();
  mRecord.Email = C.txtEmail.Text();

  mRecord.RoleType = C.cboRoleType.Text();
  mRecord.ActiveSalesRep = C.chkActiveSalesRep.Value();
  mRecord.AvailableToSubExternalParties = C.chkAvailableToSubExternalParties.Value();
  mRecord.Occupation = C.cboOccupation.Text();
  mRecord.JobTitle = C.cboJobTitle.Text();
  mRecord.EmploymentType = C.cboEmploymentType.Text();
  mRecord.EmploymentBasis = C.cboEmploymentBasis.Text();

  mRecord.Notes = C.txtNotes.Text();

  mRecord.DateStart = C.dateStart.Value();
  mRecord.DateStop = C.dateStop.Value();
  mRecord.Historic = C.chkHistoric.Value();

  // External Party Employee
  mRecord.Code = C.txtCode.Text();  
  mRecord.CreateUser = (mRecord.CanCreateUser &amp;&amp; C.chkCreateUser.Value());
  mRecord.DuplicateUserId = C.cboDuplicateUser.Text();
  mRecord.ExternalPartyManager = C.chkExternalPartyManager.Value();
  mRecord.ExternalPartyViewSubAccounts = C.chkExternalPartyCanViewSubAccounts.Value();
  mRecord.ExternalPartySubAccountsFilter = C.txtExternalPartySubAccountsFilter.Text();
  mRecord.ExternalPartyShareAccounts = C.chkExternalPartyShareAccounts.Value();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  var heading = "";
  if (mRecord &amp;&amp; mRecord.ClientIsOrganisation) {
    heading = "Personnel";
  }
  else {
    heading = "Employment";
  }
  if (mRecord &amp;&amp; mRecord.ReplaceRecordDetails) {
    heading = "Replace " + heading;
  }
  else if (mRecord &amp;&amp; mRecord.IsNew) {
    heading = "New " + heading;
  }
  widget.SetHeading(heading);

  // Information Lists
  C.cboTitle.SetComboFromInformationList("Titles");
  C.cboRoleType.SetComboFromInformationList("RoleTypes");
  C.cboOccupation.SetComboFromInformationList("Occupations");
  C.cboJobTitle.SetComboFromInformationList("JobTitles");
  C.cboEmploymentType.SetComboFromInformationList("EmploymentTypes");
  C.cboEmploymentBasis.SetComboFromInformationList("EmploymentBasis");

  // Lists
  if (mRecord) {
    C.cboGender.ListFromCsvString(mRecord.GendersList);
    C.cboDuplicateUser.RefreshFromStandardRange("Users");
  }

  // Check for Advanced options
  mHasAdvancedOptions = true;
  if (mRecord) {
    mHasAdvancedOptions = !mRecord.AlwaysShowAdvanced;
  }

  // Controls
  if (mRecord) {
    // Read only
    if (mRecord.ReadOnly) {
      C.trNewClient.hide();
    }
  
    // Advanced
    if (!mHasAdvancedOptions) {
      C.trEmploymentPeriod.removeClass("advanced");
      C.trDateStart.removeClass("advanced");
      C.trHistoric.removeClass("advanced");
    }

    // Individual / Organisation Radio Button List
    if (mRecord.ClientIsOrganisation) {
      C.rblEmploymentClientType.ListFromArray([{ caption: "Individual", value: "Individual" }, { caption: "Organisation", value: "Organisation" }]);
    }
    else {
      C.rblEmploymentClientType.ListFromArray([{ caption: "Organisation", value: "Organisation" }, { caption: "Individual", value: "Individual" }]);
    }
    C.rblEmploymentClientType.Value(mRecord.EmploymentClientType);

    // Can Create User?
    if (!mRecord.CanCreateUser) {
      C.tbCreateUser.hide();
    }

    cboLinkedClient_Change();
    chkExternalPartyShareAccounts_Change();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

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

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

// ========
// Is Dirty
// ========
function Form_IsDirty() {
  if (mRecord) {
    // Save Fields
    Fields_Save();

    // Is Dirty?
    return mOriginalJson != JSON.stringify(mRecord);
  }
  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 and Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();    
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();
    cmdBack.prop("disabled", tabIndex &lt;= 0);
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);    
  }
  
  // Finish Button
  if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

  // Exceptions  
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // External Party Page is only available if entering an individual for an External Party
      if (mRecord &amp;&amp; mRecord.ClientIsExternalParty &amp;&amp; C.rblEmploymentClientType.Value() == "Individual") {
        cmdFinish.prop("disabled", true);
        cmdNext.prop("disabled", false);
      }
      else {
        cmdFinish.prop("disabled", false);
        cmdNext.prop("disabled", true);
      }
      break;
  }
  
  // Read Only
  if (mRecord &amp;&amp; mRecord.ReadOnly) {
    cmdCancel.hide();
    cmdFinish.text("Close");
  }
  else {
    cmdFinish.text("Save");
  }    

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // General
      C.txtName.WidthResizeFromParent();
      C.txtEmail.WidthResizeFromParent();
      C.txtNotes.WidthResizeFromParent();
      C.cboRoleType.WidthResizeFromParent();
      C.cboOccupation.WidthResizeFromParent();
      C.cboJobTitle.WidthResizeFromParent();
      C.cboEmploymentType.WidthResizeFromParent();
      C.cboEmploymentBasis.WidthResizeFromParent();
      break;

    case "ExternalPartyEmployee":
      // External Party Employee
      C.txtCode.WidthResizeFromParent();
      C.txtExternalPartySubAccountsFilter.WidthResizeFromParent();
      break;
  }
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

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

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

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

      case "ExternalPartyEmployee":
        // External Party Employee
        pageExternalPartyEmployee_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "General":
      if (mRecord.EditJson) {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter Employment details.");
      }
      else {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter Employment details for Client '" + mRecord.ClientId + "', " + mRecord.ClientName + ".");
      }      
      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;
  }
}

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

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

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

  // Server-side validation
  if (Ok) {
    var params;
    switch (tabWizard.SelectedTabId()) {
      case "General":
        Fields_Save();
        params = JSON.parse(JSON.stringify(mRecord));
        params.GendersList = null;
        break;

      case "New":
        // Fetch default parameters for Contact Method change
        if (mRequiresRefresh) {
          params = { contactMethodId: mRecord.ContactMethodId };
        }
        break;
    }

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

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

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


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

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

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

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

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

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

    case "MOVETOP":
      Form_ExecuteAction_MoveTop();
      break;

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

// =================
// Add Client Action
// =================
function Form_ExecuteAction_AddClient() {
  var params = {};
  var htmlWidgetId = "";

  // Select HTML Widget
  if (C.rblEmploymentClientType.Value() == "Individual") {
    htmlWidgetId = mRecord.WidgetNewIndividualClient;
    if (mRecord.WidgetNewIndividualClient_StartupParametersJson) params = JSON.parse(mRecord.WidgetNewIndividualClient_StartupParametersJson);
  }
  else {
    htmlWidgetId = mRecord.WidgetNewOrganisationClient;
    if (mRecord.WidgetNewOrganisationClient_StartupParametersJson) params = JSON.parse(mRecord.WidgetNewOrganisationClient_StartupParametersJson);
  }
  
  // Open New Client wizard
  if (htmlWidgetId) {
    params.ShowNewRecordOnFinish = false;
    widget.UI.Forms.ShowHtmlWidgetModal(htmlWidgetId, { startupParametersJson: JSON.stringify(params) }, Form_ExecuteAction_AddClient_Notify);
  }
}

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

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mRecord.EditJson) {
      // No prompt
      Form_ExecuteAction_FinishPost();
    }
    else if (mRecord.PromptOnSave) {
      // Confirm
      if (mRecord.IsNew) {
        var heading = "Add Client Employment";
        var message = "Are you sure you want to add the Employment details to this Client?";
      }
      else {
        var heading = "Update Client Employment";
        var message = "Are you sure you want to update the Employment details for this Client?";
      }

      widget.UI.MsgBoxConfirm(message,
                              { heading: heading },
                              Form_ExecuteAction_FinishPost);
    }
    else {
      // Save without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishPost(moveAction) {
  // Disable Form
  if (mRecord.EditJson) {
    widget.UI.Block("Updating, please wait...");
  } 
  else {
    widget.UI.Block("Saving, please wait...");
  }  

  // Create Parameters
  // NOTE: We will simply update mRecord, clone this and send back (less some information)
  Fields_Save();
  var params = JSON.parse(JSON.stringify(mRecord));
  params.GendersList = null;

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

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      // Finalise
      Form_ExecuteAction_FinishPost_Finalise(data);
    },

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

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

function Form_ExecuteAction_FinishPost_Finalise(data) {
  if (mRecord.EditJson) {
    // Notify parent (e.g., New Client wizard) that a new Contact Method has been created or an item edited
    // NOTE: This is essential if this wizard needs to be run from a New Client wizard
    widget.ParentNotify("RecordUpdated", data);

    // Close
    widget.Close();
    return;
  }

  // Close Form
  widget.Close();

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

// =============
// Delete Action
// =============
function Form_ExecuteAction_Delete() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    var msg = "Are you sure you want to delete this record?";
    if (mRecord.ExternalUserId) msg += "\n\nWARNING: This will also delete the finPOWER Connect User '" + mRecord.ExternalUserId + "'.";
    widget.UI.MsgBoxConfirmDelete(msg, {}, Form_ExecuteAction_DeletePost);
  });
}

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

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

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

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

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

// ==================
// Move to Top Action
// ==================
function Form_ExecuteAction_MoveTop() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    if (mRecord.PromptOnSave) {
      widget.UI.MsgBoxConfirm("Move the record to the top of the list?\n\nNote, this will also update your changes.",
                              { heading: "Update and Promote Employment" },
                              function () {
                                // Save and Move
                                Form_ExecuteAction_FinishPost("MoveTop");
                              });
    }
    else {
      // Save and Move without prompting
      Form_ExecuteAction_FinishPost("MoveTop");
    }
  });
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  if (!mRecord) return;

  // Controls
  if (!mRecord.ClientIsExternalParty) {
    C.chkActiveSalesRep.VisibleRow(false);
    C.chkAvailableToSubExternalParties.VisibleRow(false);
  }

  if (mRecord.ClientIsOrganisation) {
    C.lblNameOrClient.Text("Enter Personnel, Officer or Related Party details");
  }
  else {
    C.lblNameOrClient.Text("Enter Employer or Other Role details");
  }

  if (C.cboLinkedClient.Text()) {
    C.txtName.VisibleRow(false);
    C.trNameIndividual.hide();
    C.dateDateOfBirth.VisibleRow(false);
    C.cboGender.VisibleRow(false);
    C.trPhoneNumber.hide();
    C.txtEmail.VisibleRow(false);
  }
  else {
    if (C.rblEmploymentClientType.Value() == "Individual") {
      C.txtName.VisibleRow(false);
      C.trNameIndividual.show();
      C.dateDateOfBirth.VisibleRow(true);
      C.cboGender.VisibleRow(true);
      C.cboGender.VisibleRow(true);
    }
    else {
      C.txtName.VisibleRow(true);
      C.trNameIndividual.hide();
      C.dateDateOfBirth.VisibleRow(false);
      C.cboGender.VisibleRow(false);
      C.cboGender.VisibleRow(false);
    }
    C.trPhoneNumber.show();
    C.txtEmail.VisibleRow(true);
  }

  // Linked Client
  var standardRange = "ClientsOrganisations";
  if (C.rblEmploymentClientType.Value() == "Individual") {
    standardRange = "ClientsIndividuals";
  }
  C.cboLinkedClient.RefreshFromStandardRange(standardRange, "", false, mRecord.LinkedClientId);

  // Advanced Button visible?
  if (mRecord &amp;&amp; mRecord.AlwaysShowAdvanced) {
    // Hide button
    cmdAdvanced.hide();

    // Remove advanced section styling for everything
    $("tr").removeClass("advanced");
  }
  else if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }
  
  // Update Buttons
  tabWizard_UpdateButtons();
}

// =========================
// pageExternalPartyEmployee
// =========================
function pageExternalPartyEmployee_Refresh() {
  if (!mRecord) return;

  // Controls
  if (mRecord.ExternalUserId || !mRecord.AddOnExternalUsers || mRecord.EditJson) {
    C.lblCreateUser.VisibleRow(false);
    C.chkCreateUser.VisibleRow(false);
    C.cboDuplicateUser.VisibleRow(false);
    C.trCreateUserInformation.hide();
  }
  else {
    C.cboDuplicateUser.VisibleRow(C.chkCreateUser.Value());
    if (C.chkCreateUser.Value()) {
      C.trCreateUserInformation.show();
    }
    else {
      C.trCreateUserInformation.hide();
    }
  }

}

// ========
// txtValue
// ========
function txtValue_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Format?
  if (C.txtValue.Text()) {
    switch(mContactMethod.ContactType) {
      case "Phone":
        widget.GetString("FormatPhoneNumber", { phoneNumber: C.txtValue.Text()}, txtValue_PromptUpdate);
        break;
    }
  }
  else {
    C.pulPromptUpdateList_Value.Hide();
  }
}

function txtValue_PromptUpdate(data) {
  if (data) {
    // Parse
    mValueData = JSON.parse(data);

    // Build update list
    var list = [];
    if (mValueData.PhoneNumber) list.push({ id: "Phone", caption: "Phone No.", value: mValueData.PhoneNumber});
    if (mValueData.Notes) list.push({ id: "Notes", caption: "Notes", value: mValueData.Notes, selected: false});

    // Show
    C.pulPromptUpdateList_Value.Show(C.txtValue, list);
  }
  else {
    C.pulPromptUpdateList_Value.Hide();
  }
}

// ===============
// cboLinkedClient
// ===============
function cboLinkedClient_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Layout
  pageGeneral_Refresh();
}

// =========================
// pulPromptUpdateList_Value
// =========================
function pulPromptUpdateList_Value_Accept(sender, e) {
  // Update
  for(var i = 0; i &lt; e.ids.length; i++) {
    switch(e.ids[i]) {
      case "Phone":
        C.txtValue.Text(mValueData.PhoneNumber);
        break;

      case "Notes":
        // Append to existing notes
        var s = C.txtNotes.Text();
        if (s) s += "\n\n";
        s += mValueData.Notes;
        C.txtNotes.Text(s);
        break;
    }
  }
}

// ==============
// txtPhoneNumber
// ==============
function txtPhoneNumber_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Format?
  if (C.txtPhoneNumber.Text()) {
    widget.GetString("FormatPhoneNumber", { phoneNumber: C.txtPhoneNumber.Text()}, txtPhoneNumber_PromptUpdate);
  }
  else {
    C.pulPromptUpdateList_Value.Hide();
  }
}

function txtPhoneNumber_PromptUpdate(data) {
  if (data) {
    // Parse
    mValueData = JSON.parse(data);

    // Build update list
    var list = [];
    if (mValueData.PhoneNumber) list.push({ id: "Phone", caption: "Phone No.", value: mValueData.PhoneNumber});
    if (mValueData.Notes) list.push({ id: "Notes", caption: "Notes", value: mValueData.Notes, selected: false});

    // Show
    C.pulPromptUpdateList_Value.Show(C.txtPhoneNumber, list);
  }
  else {
    C.pulPromptUpdateList_Value.Hide();
  }
}

// =========================
// pulPromptUpdateList_Value
// =========================
function pulPromptUpdateList_Value_Accept(sender, e) {
  // Update
  for(var i = 0; i &lt; e.ids.length; i++) {
    switch(e.ids[i]) {
      case "Phone":
        C.txtPhoneNumber.Text(mValueData.PhoneNumber);
        break;

      case "Notes":
        // Append to existing notes
        var s = C.txtNotes.Text();
        if (s) s += "\n\n";
        s += mValueData.Notes;
        C.txtNotes.Text(s);
        break;
    }
  }
}

// =============================
// chkExternalPartyShareAccounts
// =============================
function chkExternalPartyShareAccounts_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  C.gridExternalPartyShareEmployees.Visible(C.chkExternalPartyShareAccounts.Value());
}

// =======================
// rblEmploymentClientType
// =======================
function rblEmploymentClientType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Clear linked Client
  C.cboLinkedClient.Text("");

  // Refresh General Page
  pageGeneral_Refresh();
}

// ===============================
// gridExternalPartyShareEmployees
// ===============================
function gridExternalPartyShareEmployees_Refresh() {
  // Add Columns
  C.gridExternalPartyShareEmployees.ClearColumns();
  C.gridExternalPartyShareEmployees.AddColumnBoolean("Share", { caption: "Share", width: "3em", allowEdit: true});
  C.gridExternalPartyShareEmployees.AddColumnString("ClientEmploymentId", { caption: "Code", width: "10em" });
  C.gridExternalPartyShareEmployees.AddColumnString("Name", { caption: "Name"});

  // Refresh
  C.gridExternalPartyShareEmployees.VirtualDataRefresh(mRecord.ExternalPartyShareEmployees);
}

function gridExternalPartyShareEmployees_InitialiseRow(e) {
  var item = mRecord.ExternalPartyShareEmployees[e.row.listIndex];

  // Update cells
  e.row.cells.Share.value = item.Share;
  e.row.cells.ClientEmploymentId.value = item.ClientEmploymentId;
  e.row.cells.Name.value = item.Name;
}

function gridExternalPartyShareEmployees_BeforeCellUpdate(e) {
  var item = mRecord.ExternalPartyShareEmployees[e.row.listIndex];

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

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

// ====================
// 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;
   }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>DBSLoN90aEuEZ9JRHWFvYQ</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Client Employment</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>800</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AlwaysShowAdvanced" type="Boolean">
            <BlankTip />
            <Caption>Always show "Advanced" details?</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="ReadOnly" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ClientId" 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.Clients</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ClientEmploymentPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="ReplaceRecordPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="EditJson" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="EditJsonIsIndividual" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ClientEmploymentJson" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="UseBuiltInNewIndividualClientHTMLWidget" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="UseBuiltInNewOrganisationClientHTMLWidget" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>