<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-01-09T20:22:55.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2023-11-26T22:09:30.4500000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-01-09T20:22:19.7070000</UpdatedUtcDate>
    <ScriptId>CGE</ScriptId>
    <Description>Client Group Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ClientGroupEdit
Option Explicit On
Option Strict On

' #################################################################
' Client Group Edit form HTML Widget
'
' Version: 1.00 (10/01/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  10/01/2024  ISS      J032486   Created
' #################################################################

' Constants
Private Const FORM_KEY As String = "ClientGroups"

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

' Standard Parameters
Private mClientGroupId As String
Private mDuplicateRecordId As String
Private mPage As String
Private mReadOnly As Boolean

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 mStartupParameters
    mClientGroupId = .GetString("ClientGroupId") ' Always use Startup Parameters since the Client Group Id may be updated
  End With
  With mCombinedParameters
    mDuplicateRecordId = .GetString("DuplicateRecordId")
    mPage = .GetString("Page")
    mReadOnly = .GetBoolean("ReadOnly")
  End With
  
  ' Validate
  Main = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)

  ' Handle Events
  If Main Then
    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 "GetInitialisationInfo"
        ' Get Initialisation Information required for this wizard
        Main = GetInitialisationInfo(returnValue)

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

End Function

''' &lt;summary&gt;
'''  Load Client Group.
''' &lt;/summary&gt;
Private Function GetClientGroup(ByRef clientGroup As finClientGroup) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Client Group
  If Success Then
    ' Create Client Group
    clientGroup = finBL.CreateClientGroup()

    ' Load Client Group
    If Len(mDuplicateRecordId) &lt;&gt; 0 Then
      ' New record (by duplicating existing)
      Success = clientGroup.Load(mDuplicateRecordId)
      If Success Then clientGroup.Duplicate()
    ElseIf Len(mClientGroupId) = 0 Then
      ' New record
    Else
      Success = clientGroup.Load(mClientGroupId)
    End If
  End If

  Return Success

End Function

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

  Dim ClientGroup As finClientGroup
  Dim ClientGroupContactMethod As finClientGroupContactMethod
  Dim ClientGroupDocument As finClientGroupDocument
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim StatisticClassList As ISList
  Dim StatisticTypeRO As finStatisticTypeRO
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  StatisticClassList = finBL.Runtime.CreateList()
  
  ' Validate
  
  ' Get Client Group
  If Success Then
    Success = GetClientGroup(ClientGroup)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Form
      .PageId = mPage
      If finBL.Database.IsReadOnly OrElse mReadOnly OrElse Not finBL.CurrentUser.Permissions.Allow("Admin.ClientGroups") Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .Pk = ClientGroup.Pk
      .Timestamp = ClientGroup.Timestamp

      ' Page Permissions (defined here since they are used below)
      .AllowPageGeneral = True
      .AllowPageNewClientWizard = True
      .AllowPageStatisticsIndividual = finBL.Settings.AddOns.ClientStatistics
      .AllowPageStatisticsOrganisation = finBL.Settings.AddOns.ClientStatistics
      .AllowPageIdentification = finBL.Settings.AddOns.ClientAdvanced
      .AllowPageDocuments = True
      .AllowPageParameterSets = True
      .AllowPageUserDefined = finBL.Settings.HasClientGroupUser

      ' General
      .ClientGroupId = ClientGroup.ClientGroupId ' Always need to return Client Group Id
      If .AllowPageGeneral Then
        .Active = ClientGroup.Active
        .Description = ClientGroup.Description
        
        .NextClientId = ClientGroup.NextClientId 
        .CommunicationGeneral = ClientGroup.CommunicationGeneral
        .CommunicationMarketing = ClientGroup.CommunicationMarketing
      End If
      
      ' New Client Wizard
      If .AllowPageNewClientWizard Then
        .HideInNewClientWizard = ClientGroup.HideInNewClientWizard
        
        .NewWizardShowAddresses = ClientGroup.NewWizardShowAddresses
        .NewWizardShowContactMethods = ClientGroup.NewWizardShowContactMethods
        .NewWizardShowFullContacts = ClientGroup.NewWizardShowFullContacts
        .NewWizardShowImage = ClientGroup.NewWizardShowImage
        .NewWizardShowIdentification = ClientGroup.NewWizardShowIdentification
        .NewWizardShowIdentificationDecision = ClientGroup.NewWizardShowIdentificationDecision
        .NewWizardShowEmployment = ClientGroup.NewWizardShowEmployment
        .NewWizardShowStatistics = ClientGroup.NewWizardShowStatistics
        .NewWizardShowBankingDetails = ClientGroup.NewWizardShowBankingDetails
        .NewWizardShowOtherInformation = ClientGroup.NewWizardShowOtherInformation
        .NewWizardShowTaxInformation = ClientGroup.NewWizardShowTaxInformation
        .NewWizardShowWebAccess = ClientGroup.NewWizardShowWebAccess
        .NewWizardShowUserDefined = ClientGroup.NewWizardShowUserDefined
        
        .NewWizardIndividualTaxNumberMandatory = ClientGroup.NewWizardIndividualTaxNumberMandatory
        .NewWizardIndividualDateOfBirthMandatory = ClientGroup.NewWizardIndividualDateOfBirthMandatory
        .NewWizardIndividualGenderMandatory = ClientGroup.NewWizardIndividualGenderMandatory
        
        .NewWizardOrganisationBusinessNumberMandatory = ClientGroup.NewWizardOrganisationBusinessNumberMandatory
        .NewWizardOrganisationTaxNumberMandatory = ClientGroup.NewWizardOrganisationTaxNumberMandatory
        .NewWizardOrganisationCompanyNumberMandatory = ClientGroup.NewWizardOrganisationCompanyNumberMandatory
        
        .NewWizardValidatorScriptId = ClientGroup.NewWizardValidatorScriptId
        
        .PostalContactMethodId = ClientGroup.PostalContactMethodId
        .PhysicalContactMethodId = ClientGroup.PhysicalContactMethodId
        
        For Each ClientGroupContactMethod In ClientGroup.ContactMethods
          .ContactMethods.Add(New ContactMethod(ClientGroupContactMethod))
        Next 
      End If
      
      ' Statistics Individual
      If .AllowPageStatisticsIndividual Then
        .IndividualUseStatistics = ClientGroup.IndividualUseStatisticsText
        
        .IndividualStatisticsFixed = ClientGroup.IndividualStatisticsFixed
        .IndividualAvailableAssetsPercent = ClientGroup.IndividualAvailableAssetsPercent
        .IndividualAvailableIncomePercent = ClientGroup.IndividualAvailableIncomePercent
        .IndividualStatisticsExpiryCycle = finBL.Utilities.DateCycleGetDescription(false, ClientGroup.IndividualStatisticsExpiryCycle)
        .IndividualStatisticsSummaryScriptId = ClientGroup.IndividualStatisticsSummaryScriptId
        .IndividualStatistics = ClientGroup.IndividualStatistics.ToHtmlWidgetJsonObject()
      End If
      
      ' Statistics Organisation
      If .AllowPageStatisticsOrganisation Then
        .OrganisationUseStatistics = ClientGroup.OrganisationUseStatisticsText
        
        .OrganisationStatisticsFixed = ClientGroup.OrganisationStatisticsFixed
        .OrganisationAvailableAssetsPercent = ClientGroup.OrganisationAvailableAssetsPercent
        .OrganisationAvailableIncomePercent = ClientGroup.OrganisationAvailableIncomePercent
        .OrganisationStatisticsExpiryCycle = finBL.Utilities.DateCycleGetDescription(false, ClientGroup.OrganisationStatisticsExpiryCycle)
        .OrganisationStatisticsSummaryScriptId = ClientGroup.OrganisationStatisticsSummaryScriptId
        .OrganisationStatistics = ClientGroup.OrganisationStatistics.ToHtmlWidgetJsonObject()
      End If
      
      ' Identification
      If .AllowPageIdentification Then
        .UseIdentification = ClientGroup.UseIdentification
        
        .IdentificationDecisionCardId = ClientGroup.IdentificationDecisionCardId
        .IdentificationDecisionExpiryCycle = finBL.Utilities.DateCycleGetDescription(false, ClientGroup.IdentificationDecisionExpiryCycle)
      End If
      
      ' Documents
      If .AllowPageDocuments Then
        For Each ClientGroupDocument In ClientGroup.Documents
          .Documents.Add(New Document(ClientGroupDocument))
        Next 
        .Documents.Sort(AddressOf ClientGroupDocuments_SortComparer)
      End If
      
      ' Parameter Sets
      If .AllowPageParameterSets Then
        .UserDefinedParameterSetId = ClientGroup.UserDefinedParameterSetId
        
        .UserDefinedWebParameterSetId = ClientGroup.UserDefinedWebParameterSetId
      End If
      
      ' User Defined
      If .AllowPageUserDefined Then
        .UserDefinedParameters = finBL.CreateWsParameters(finBL.ParameterSets.CreateParameters(finBL.Settings.ClientGroupUserDefinedParameterSetId, False))
        .UserDataJson = ClientGroup.UserData.ToSimpleJsonString()
      End If
      
      ' Permissions
      .AddonsClientAdvanced = finBL.Settings.AddOns.ClientAdvanced
      .AddonsClientStatistics = finBL.Settings.AddOns.ClientStatistics
      .AddonsWebAutomation = finBL.Settings.AddOns.WebAutomation

      ' Lists
      .ClientGroupUseStatisticsList = finBL.Enums.isefinClientGroupUseStatistics_ToCodeDescriptionList().ToJsonObject()
      .ContactAddressesSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.ContactMethods.GetDataViewFilter_ClientGroups_ContactAddresses())
      .DecisionCardSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.DecisionCards.GetDataViewFilter_ClientGroups_Identification())
      .ExpiryCycleList = "1 Week,1 Month,3 Months,6 Months,1 Year,2 Years,3 Years,4 Years,5 Years,10 Years"
      .FrequencyPerAnnumList = finBL.Enums.isefinFrequencyPerAnnum_GetList(False).ToCsvString()
      .StatisticsSummarySqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.Scripts.GetDataViewFilter_ClientGroups_StatisticsSummary())
      .WizardValidatorSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.Scripts.GetDataViewFilter_ClientGroups_WizardValidator())      
      
      For Each StatisticTypeRO In finBL.StatisticTypes
        If StatisticTypeRO.Active Then
          .StatisticTypes.Add(New StatisticType(StatisticTypeRO))
          StatisticClassList.Add(StatisticTypeRO.StatisticClassText, True)
        End If
      Next 
      StatisticClassList.Sort()
      .StatisticClassList = StatisticClassList.ToCsvString()
      
      ' Terminology
      If Len(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BusinessNumber)) &lt;&gt; 0 Then
        .Terminology_BusinessNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.BusinessNumber, False)
      End If
      If Len(finBL.CurrentCountry.Terminology(isefinCountryTerminology.CompanyNumber)) &lt;&gt; 0 Then
        .Terminology_CompanyNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.CompanyNumber, False)
      End If
      If Len(finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberIndividual)) &lt;&gt; 0 Then
        .Terminology_TaxNumberIndividual = finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberIndividual, False)
      End If
      If Len(finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberOrganisation)) &lt;&gt; 0 Then
        .Terminology_TaxNumberOrganisation = finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberOrganisation, False)
      End If
      
      ' Permissions
      .ShowUserDefinedWeb = (finBL.Settings.AddOns.WebAutomation AndAlso finBL.Settings.WebAutomationUseClientWebAccess)
      
      ' Configuration      
      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .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;
'''  Client Group Documents Sort Comparer.
''' &lt;/summary&gt;
Private Function ClientGroupDocuments_SortComparer(x As Document,
                                                   y As Document) As Integer

  If x.Category &gt; y.Category Then
    Return 1
  ElseIf x.Category &lt; y.Category Then
    Return -1
  Else
    If x.DocumentId &gt; y.DocumentId Then
      Return 1
    ElseIf x.DocumentId &lt; y.DocumentId Then
      Return -1
    Else 
      Return 0
    End If
  End If

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Save Client Group.
''' &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 ClientGroup As finClientGroup
  Dim ClientGroupContactMethod As finClientGroupContactMethod
  Dim ClientGroupDocument As finClientGroupDocument
  Dim ContactMethod As ContactMethod
  Dim Document As Document
  Dim i As Integer
  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 Client Group
  If Success Then
    Success = GetClientGroup(ClientGroup)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; ClientGroup.Timestamp Then
      Success = False
      finBL.Error.ErrorBegin("This record has been updated by another User.")
    End If
  End If

  ' Update and Save
  ' NOTE: Recheck Permissions in addition to the 'AllowPage' properties before updating to prevent spoofing
  If Success Then
    ' Begin Transaction
    If finBL.Database.TransactionBegin() Then
      ' Update Client Group
      With ClientGroup
        If Success AndAlso Record.AllowPageGeneral Then
          .ClientGroupId = Record.ClientGroupId
          .Active = Record.Active
          .Description = Record.Description  
          .NextClientId = Record.NextClientId
          .CommunicationGeneral = Record.CommunicationGeneral
          .CommunicationMarketing = Record.CommunicationMarketing
        End If
        
        ' New Client Wizard
        If Success AndAlso Record.AllowPageNewClientWizard Then
          .HideInNewClientWizard = Record.HideInNewClientWizard
          
          .NewWizardShowAddresses = Record.NewWizardShowAddresses
          .NewWizardShowContactMethods = Record.NewWizardShowContactMethods
          .NewWizardShowFullContacts = Record.NewWizardShowFullContacts
          .NewWizardShowImage = Record.NewWizardShowImage
          .NewWizardShowIdentification = Record.NewWizardShowIdentification
          .NewWizardShowIdentificationDecision = Record.NewWizardShowIdentificationDecision
          .NewWizardShowEmployment = Record.NewWizardShowEmployment
          .NewWizardShowStatistics = Record.NewWizardShowStatistics
          .NewWizardShowBankingDetails = Record.NewWizardShowBankingDetails
          .NewWizardShowOtherInformation = Record.NewWizardShowOtherInformation
          .NewWizardShowTaxInformation = Record.NewWizardShowTaxInformation
          .NewWizardShowWebAccess = Record.NewWizardShowWebAccess
          .NewWizardShowUserDefined = Record.NewWizardShowUserDefined
          
          .NewWizardIndividualTaxNumberMandatory = Record.NewWizardIndividualTaxNumberMandatory
          .NewWizardIndividualDateOfBirthMandatory = Record.NewWizardIndividualDateOfBirthMandatory
          .NewWizardIndividualGenderMandatory = Record.NewWizardIndividualGenderMandatory
          
          .NewWizardOrganisationBusinessNumberMandatory = Record.NewWizardOrganisationBusinessNumberMandatory
          .NewWizardOrganisationTaxNumberMandatory = Record.NewWizardOrganisationTaxNumberMandatory
          .NewWizardOrganisationCompanyNumberMandatory = Record.NewWizardOrganisationCompanyNumberMandatory
          
          .NewWizardValidatorScriptId = Record.NewWizardValidatorScriptId
          
          .PostalContactMethodId = Record.PostalContactMethodId
          .PhysicalContactMethodId = Record.PhysicalContactMethodId
          
          ' Contact Methods
          For Each ClientGroupContactMethod In .ContactMethods
            For Each ContactMethod In Record.ContactMethods
              If ClientGroupContactMethod.ContactMethodPk = ContactMethod.ContactMethodPk Then
                ClientGroupContactMethod.Individual = ContactMethod.Individual
                ClientGroupContactMethod.Organisation = ContactMethod.Organisation
                Exit For
              End If
            Next 
          Next 
        
          ' Order Contact Methods
          For Each ContactMethod In Record.ContactMethods
            i = .ContactMethods.IndexOfContactMethodPk(ContactMethod.ContactMethodPk)
            
            If i &lt;&gt; Record.ContactMethods.IndexOf(ContactMethod) Then
              If Not .ContactMethods.Move(i, Record.ContactMethods.IndexOf(ContactMethod)) Then
                Success = False
                Exit For
              End If
            End If
          Next 
        End If
        
        ' Statistics Individual
        If Success AndAlso Record.AllowPageStatisticsIndividual Then
          .IndividualUseStatisticsText = Record.IndividualUseStatistics
          
          .IndividualStatisticsFixed = Record.IndividualStatisticsFixed
          .IndividualAvailableAssetsPercent = Record.IndividualAvailableAssetsPercent
          .IndividualAvailableIncomePercent = Record.IndividualAvailableIncomePercent
          .IndividualStatisticsExpiryCycle = Record.IndividualStatisticsExpiryCycle
          .IndividualStatisticsSummaryScriptId = Record.IndividualStatisticsSummaryScriptId
          
          ' Statistics
          Success = .IndividualStatistics.FromHtmlWidgetJsonObject(Record.IndividualStatistics)
        End If
        
        ' Statistics Organisation
        If Success AndAlso Record.AllowPageStatisticsOrganisation Then
          .OrganisationUseStatisticsText = Record.OrganisationUseStatistics
          
          .OrganisationStatisticsFixed = Record.OrganisationStatisticsFixed
          .OrganisationAvailableAssetsPercent = Record.OrganisationAvailableAssetsPercent
          .OrganisationAvailableIncomePercent = Record.OrganisationAvailableIncomePercent
          .OrganisationStatisticsExpiryCycle = Record.OrganisationStatisticsExpiryCycle
          .OrganisationStatisticsSummaryScriptId = Record.OrganisationStatisticsSummaryScriptId
          
          ' Statistics
          Success = .OrganisationStatistics.FromHtmlWidgetJsonObject(Record.OrganisationStatistics)
        End If
        
        ' Identification
        If Success AndAlso Record.AllowPageIdentification Then
          .UseIdentification = Record.UseIdentification
          
          .IdentificationDecisionCardId = Record.IdentificationDecisionCardId
          .IdentificationDecisionExpiryCycle = Record.IdentificationDecisionExpiryCycle
        End If
        
        ' Documents
        If Success AndAlso Record.AllowPageDocuments Then
          For Each ClientGroupDocument In .Documents
            For Each Document In Record.Documents
              If ClientGroupDocument.DocumentPk = Document.DocumentPk Then
                ClientGroupDocument.Available = Document.Available
                Exit For
              End If
            Next
          Next 
        End If
        
        ' Parameter Sets
        If Success AndAlso Record.AllowPageParameterSets Then
          .UserDefinedParameterSetId = Record.UserDefinedParameterSetId
          
          .UserDefinedWebParameterSetId = Record.UserDefinedWebParameterSetId
        End If
        
        ' User Defined
        If Success AndAlso Record.AllowPageUserDefined Then
          .UserData.FromHtmlWidgetParametersJsonString(Record.UserDataJson)
        End If
      End With

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

      ' 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;
'''  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 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
  End Select

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

  Return Success

End Function


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

  ' Form
  Public PageId As String
  Public [ReadOnly] As Boolean

  ' Record
  Public Pk As Integer
  Public Timestamp As Integer

  ' General
  Public ClientGroupId As String
  Public Active As Boolean
  Public Description As String
  
  Public NextClientId As String
  Public CommunicationGeneral As Boolean
  Public CommunicationMarketing As Boolean
  
  ' New Client wizard
  Public HideInNewClientWizard As Boolean
  
  Public NewWizardShowAddresses As Boolean
  Public NewWizardShowContactMethods As Boolean
  Public NewWizardShowFullContacts As Boolean
  Public NewWizardShowImage As Boolean
  Public NewWizardShowIdentification As Boolean
  Public NewWizardShowIdentificationDecision As Boolean
  Public NewWizardShowEmployment As Boolean
  Public NewWizardShowStatistics As Boolean
  Public NewWizardShowBankingDetails As Boolean
  Public NewWizardShowOtherInformation As Boolean
  Public NewWizardShowTaxInformation As Boolean
  Public NewWizardShowWebAccess As Boolean
  Public NewWizardShowUserDefined As Boolean
  
  Public NewWizardIndividualTaxNumberMandatory As Boolean
  Public NewWizardIndividualDateOfBirthMandatory As Boolean
  Public NewWizardIndividualGenderMandatory As Boolean
  
  Public NewWizardOrganisationBusinessNumberMandatory As Boolean
  Public NewWizardOrganisationTaxNumberMandatory As Boolean
  Public NewWizardOrganisationCompanyNumberMandatory As Boolean
  
  Public NewWizardValidatorScriptId As String
  
  Public PostalContactMethodId As String
  Public PhysicalContactMethodId As String
  
  Public ContactMethods As New List(Of ContactMethod)
  
  ' Statistics Individual
  Public IndividualUseStatistics As String
  
  Public IndividualStatisticsFixed As Boolean
  Public IndividualAvailableAssetsPercent As Double
  Public IndividualAvailableIncomePercent As Double
  Public IndividualStatisticsExpiryCycle As String
  Public IndividualStatisticsSummaryScriptId As String
  
  Public IndividualStatistics As List(Of finClientGroupStatistic.jsonHtmlWidgetClientGroupStatistic)
  
  ' Statistics Organisation
  Public OrganisationUseStatistics As String
  
  Public OrganisationStatisticsFixed As Boolean
  Public OrganisationAvailableAssetsPercent As Double
  Public OrganisationAvailableIncomePercent As Double
  Public OrganisationStatisticsExpiryCycle As String
  Public OrganisationStatisticsSummaryScriptId As String
  
  Public OrganisationStatistics As List(Of finClientGroupStatistic.jsonHtmlWidgetClientGroupStatistic)
  
  ' Identification
  Public UseIdentification As Boolean

  Public IdentificationDecisionCardId As String
  Public IdentificationDecisionExpiryCycle As String
  
  ' Documents
  Public Documents As New List(Of Document)
  
  ' Parameter Sets
  Public UserDefinedParameterSetId As String
  
  Public UserDefinedWebParameterSetId As String
  
  ' User Defined
  Public UserDefinedParameters As ISWsParameters
  Public UserDataJson As String
  
  ' Permissions
  Public AddonsClientAdvanced As Boolean
  Public AddonsClientStatistics As Boolean
  Public AddonsWebAutomation As Boolean
  Public AllowPageGeneral As Boolean
  Public AllowPageNewClientWizard As Boolean
  Public AllowPageStatisticsIndividual As Boolean
  Public AllowPageStatisticsOrganisation As Boolean
  Public AllowPageIdentification As Boolean
  Public AllowPageDocuments As Boolean
  Public AllowPageParameterSets As Boolean
  Public AllowPageUserDefined As Boolean
  Public ShowUserDefinedWeb As Boolean

  ' Lists    
  Public ClientGroupUseStatisticsList As Object
  Public ContactAddressesSqlWhere As String
  Public DecisionCardSqlWhere As String
  Public ExpiryCycleList As String
  Public FrequencyPerAnnumList As String
  Public StatisticClassList As String
  Public StatisticsSummarySqlWhere As String
  Public StatisticTypes As New List(Of StatisticType)
  Public WizardValidatorSqlWhere As String

  ' Terminology
  Public Terminology_BusinessNumber As String
  Public Terminology_CompanyNumber As String
  Public Terminology_TaxNumberIndividual As String  
  Public Terminology_TaxNumberOrganisation As String
  
  ' Configuration
  Public HideOtherPages As Boolean
  Public PromptOnSave As Boolean

End Class



''' &lt;summary&gt;
'''  Client Group Contact Method.
''' &lt;/summary&gt;
Public Class ContactMethod

  Public Active As Boolean
  Public ContactMethodId As String
  Public ContactMethodPk As Integer
  Public Description As String
  Public Icon As String
  Public Individual As Boolean
  Public Organisation As Boolean 
  
  Public Sub New()
  End Sub
  
  Public Sub New(clientGroupContactMethod As finClientGroupContactMethod)
    
    With clientGroupContactMethod
      Me.Active = .Active
      Me.ContactMethodId = .ContactMethodId
      Me.ContactMethodPk = .ContactMethodPk
      Me.Description = .Description
      Me.Icon = .Icon
      Me.Individual = .Individual
      Me.Organisation = .Organisation
    End With
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Client Group Document
''' &lt;/summary&gt;
Public Class Document
  
  Public Active As Boolean
  Public Available As Boolean
  Public Category As String
  Public Description As String
  Public DocumentId As String
  Public DocumentPk As Integer
  
  Public Sub New()
  End Sub
  
  Public Sub New(clientGroupDocument As finClientGroupDocument)
    
    With clientGroupDocument
      Me.Active = .Active
      Me.Available = .Available
      Me.Category = .Category
      Me.Description = .Description
      Me.DocumentId = .DocumentId
      Me.DocumentPk = .DocumentPk
    End With
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Statistic Type.
''' &lt;/summary&gt;
Public Class StatisticType

  Public CanUpdateFrequencyPerAnnum As Boolean
  Public Description As String
  Public StatisticClass As String
  Public StatisticTypeId As String
  
  Public Sub New(statisticTypeRO As finStatisticTypeRO)
    
    With statisticTypeRO
      Me.Description = .Description
      Me.StatisticClass = .StatisticClassText
      Me.StatisticTypeId = .StatisticTypeId
      
      Select Case .StatisticClass
        Case isefinStatisticClass.Asset, isefinStatisticClass.Liability: Me.CanUpdateFrequencyPerAnnum = False          
        Case Else: Me.CanUpdateFrequencyPerAnnum = True
      End Select
    End With
    
  End Sub
  
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 edit a Client Group.</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;!-- Tabs --&gt;
    &lt;div id="tabDetails" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General"&gt;General&lt;/li&gt;
        &lt;li tabId="NewClientWizard"&gt;New Client Wizard&lt;/li&gt;
        &lt;li tabId="StatisticsIndividual"&gt;Statistics Individual&lt;/li&gt;
        &lt;li tabId="StatisticsOrganisation"&gt;Statistics Organisation&lt;/li&gt;
        &lt;li tabId="Identification"&gt;Identification&lt;/li&gt;
        &lt;li tabId="Documents"&gt;Documents&lt;/li&gt;
        &lt;li tabId="ParameterSets"&gt;Parameter Sets&lt;/li&gt;
        &lt;li tabId="UserDefined"&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;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:6em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCodeAndName"&gt;Code and Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtClientGroupId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtClientGroupId"/&gt; &lt;input id="chkActive" type="checkbox"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtDescription"&gt;Description:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDescription"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblNewClientDefaults"&gt;Defaults for new Clients&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtNextClientId"&gt;Next code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtNextClientId"/&gt;&lt;/td&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"&gt;&lt;input id="chkCommunicationMarketing" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    &lt;!-- New Client Wizard --&gt;
    &lt;div id="pageNewClientWizard"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&gt;
          &lt;table class="is-form"&gt;
            &lt;colgroup&gt;
              &lt;col style="width:6em" /&gt;
              &lt;col /&gt;
            &lt;/colgroup&gt;
    
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblNewClientWizardSupport"&gt;New Client Wizard support&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;    
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkHideInNewClientWizard" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;    
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblIncludeInNewWizard"&gt;Pages to include in the New Client wizard&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowAddreses" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowContactMethods" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowFullContacts" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowImage" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowIdentification" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkNewWizardShowIdentificationDecision" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowEmployment" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowStatistics" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowBankingDetails" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowOtherInformation" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowTax" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowWebAccess" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardShowUserDefined" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblNewWizardOptionsIndividual"&gt;New Client wizard options for Individuals&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardIndividualTaxNumberMandatory" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardIndividualDateOfBirthMandatory" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardIndividualGenderMandatory" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblNewWizardOptionsOrganisation"&gt;New Client wizard options for Organisations&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardOrganisationBusinessNumberMandatory" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardOrganisationTaxNumberMandatory" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt; 
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkNewWizardOrganisationCompanyNumberMandatory" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblValidatorScript"&gt;Validator Script to use in the New Client wizard&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboNewWizardValidatorScript"&gt;Script:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboNewWizardValidatorScript"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblAddresses"&gt;Contact Addresses for Postal and Physical Address pages&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboPostalContactMethod"&gt;Postal:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboPostalContactMethod"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboPhysicalContactMethod"&gt;Physical:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboPhysicalContactMethod"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblContactMethods"&gt;Contact Methods to display on the Contact Methods page&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px; min-height:400px"&gt;
          &lt;div id="gridContactMethods" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    
    
    &lt;!-- Statistics Individual --&gt;
    &lt;div id="pageStatisticsIndividual"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&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;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblIndSupport"&gt;Statistics support for Individual Clients&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboIndUseStatistics"&gt;Use Statistics:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboIndUseStatistics"/&gt;&lt;/td&gt;
            &lt;/tr&gt;   
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblIndStatisticsOptions"&gt;Statistics options&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkIndStatisticsFixed" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="numIndAvailableAssetsPercentage"&gt;Available Assets:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="numIndAvailableAssetsPercentage"/&gt;&lt;/td&gt;
            &lt;/tr&gt;   
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="numIndAvailableIncomePercentage"&gt;Available Income:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="numIndAvailableIncomePercentage"/&gt;&lt;/td&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboIndStatisticsExpiryCycle"&gt;Expiry Period:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboIndStatisticsExpiryCycle"/&gt;&lt;/td&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboIndStatisticsScript"&gt;Summary Script:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboIndStatisticsScript"/&gt;&lt;/td&gt;
            &lt;/tr&gt; 
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblIndStatisticsDefaults"&gt;Defaults for new Clients and new Statistics sets&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt; 
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px; min-height:400px"&gt;
          &lt;div id="gridIndStatistics" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
        
        
    &lt;!-- Statistics Organisation --&gt;
    &lt;div id="pageStatisticsOrganisation"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&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;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblOrgSupport"&gt;Statistics support for Organisation Clients&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboOrgUseStatistics"&gt;Use Statistics:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboOrgUseStatistics"/&gt;&lt;/td&gt;
            &lt;/tr&gt;   
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblOrgStatisticsOptions"&gt;Statistics options&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOrgStatisticsFixed" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="numOrgAvailableAssetsPercentage"&gt;Available Assets:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="numOrgAvailableAssetsPercentage"/&gt;&lt;/td&gt;
            &lt;/tr&gt;   
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="numOrgAvailableIncomePercentage"&gt;Available Income:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="numOrgAvailableIncomePercentage"/&gt;&lt;/td&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboOrgStatisticsExpiryCycle"&gt;Expiry Period:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboOrgStatisticsExpiryCycle"/&gt;&lt;/td&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboOrgStatisticsScript"&gt;Summary Script:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboOrgStatisticsScript"/&gt;&lt;/td&gt;
            &lt;/tr&gt; 
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblOrgStatisticsDefaults"&gt;Defaults for new Clients and new Statistics sets&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt; 
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px; min-height:400px"&gt;
          &lt;div id="gridOrgStatistics" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    
    
    &lt;!-- Identification --&gt;
    &lt;div id="pageIdentification"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblIdentificationSupport"&gt;Identification support&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUseIdentification" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblIdentificationDecisionCard"&gt;Decision Card for scoring Client Identification&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboIdDecisionCard"&gt;Decision Card:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboIdDecisionCard"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboIdentificationDecisionExpiryCycle"&gt;Expiry Period:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboIdentificationDecisionExpiryCycle"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    &lt;!-- Documents --&gt;
    &lt;div id="pageDocuments"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&gt;
          &lt;table class="is-form"&gt;
            &lt;colgroup&gt;
              &lt;col style="width:9em" /&gt;
              &lt;col /&gt;
            &lt;/colgroup&gt;
    
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblDocuments"&gt;Documents available to this Client Group&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;        
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px; min-height:400px"&gt;
          &lt;div id="gridDocuments" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    
    
    &lt;!-- Parameter Sets --&gt;
    &lt;div id="pageParameterSets"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblParameterSetUserDefined"&gt;Parameter Set to enter User Defined details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;    
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboParameterSetUserDefined"&gt;Parameter Set:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboParameterSetUserDefined"/&gt;&lt;/td&gt;
        &lt;/tr&gt;    
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblParameterSetUserDefinedWeb"&gt;Parameter Set to enter User Defined Web details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;    
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboParameterSetUserDefinedWeb"&gt;Parameter Set:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboParameterSetUserDefinedWeb"/&gt;&lt;/td&gt;
        &lt;/tr&gt;   
      &lt;/table&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="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Save&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;


&lt;!-- frmStatisticAdd BEGIN --&gt;
&lt;div id="frmStatisticAdd"  class="is-widget-form-body" style="display:none"&gt;
  &lt;table class="is-form"&gt;
    &lt;colgroup&gt;
      &lt;col style="width:10em" /&gt;
      &lt;col /&gt;
    &lt;/colgroup&gt;

    &lt;tr&gt;
      &lt;th colspan="2"&gt;&lt;label id="lblStatisticAdd"&gt;Enter Statistic details&lt;/label&gt;&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="cboStatisticClass"&gt;Class:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="cboStatisticClass"/&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="cboStatisticTypeId"&gt;Statistic Type Id:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="cboStatisticTypeId"/&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="txtStatisticDescription"&gt;Description:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="txtStatisticDescription"/&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="cboStatisticFrequency"&gt;Frequency:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="cboStatisticFrequency"/&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="numStatisticValue"&gt;Value:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="numStatisticValue"/&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
&lt;/div&gt;
&lt;!-- frmStatisticAdd END --&gt;

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

var mOriginalJson;

// Controls
var C = {
  //   General
  lblCodeAndName: null,
  chkActive: null,
  txtClientGroupId: null,
  txtDescription: null,
  
  lblNewClientDefaults: null,
  txtNextClientId: null,
  chkCommunicationGeneral: null,
  chkCommunicationMarketing: null,
  
  //   New Client Wizard
  lblNewClientWizardSupport: null,
  chkHideInNewClientWizard: null,
  
  lblIncludeInNewWizard: null,
  chkNewWizardShowAddreses: null,
  chkNewWizardShowContactMethods: null,
  chkNewWizardShowFullContacts: null,
  chkNewWizardShowImage: null,
  chkNewWizardShowIdentification: null,
  chkNewWizardShowIdentificationDecision: null,
  chkNewWizardShowEmployment: null,
  chkNewWizardShowStatistics: null,
  chkNewWizardShowBankingDetails: null,
  chkNewWizardShowOtherInformation: null,
  chkNewWizardShowTax: null,
  chkNewWizardShowWebAccess: null,
  chkNewWizardShowUserDefined: null,
  
  lblNewWizardOptionsIndividual: null,
  chkNewWizardIndividualTaxNumberMandatory: null,
  chkNewWizardIndividualDateOfBirthMandatory: null,
  chkNewWizardIndividualGenderMandatory: null,
  
  lblNewWizardOptionsOrganisation: null,
  chkNewWizardOrganisationBusinessNumberMandatory: null,
  chkNewWizardOrganisationTaxNumberMandatory: null,
  chkNewWizardOrganisationCompanyNumberMandatory: null,
  
  lblValidatorScript: null,
  cboNewWizardValidatorScript: null,
  
  lblAddresses: null,
  cboPostalContactMethod: null,
  cboPhysicalContactMethod: null,
  
  lblContactMethods: null,
  gridContactMethods: null,
  
  //   Statistics Individual
  lblIndSupport: null,
  cboIndUseStatistics: null,
  
  lblIndStatisticsOptions: null,
  chkIndStatisticsFixed: null,
  numIndAvailableAssetsPercentage: null,
  numIndAvailableIncomePercentage: null,
  cboIndStatisticsExpiryCycle: null,
  cboIndStatisticsScript: null,
  
  lblIndStatisticsDefaults: null,
  gridIndStatistics: null,
  
  //   Statistics Organisation
  lblOrgSupport: null,
  cboOrgUseStatistics: null,
  
  lblOrgStatisticsOptions: null,
  chkOrgStatisticsFixed: null,
  numOrgAvailableAssetsPercentage: null,
  numOrgAvailableIncomePercentage: null,
  cboOrgStatisticsExpiryCycle: null,
  cboOrgStatisticsScript: null,
  
  lblOrgStatisticsDefaults: null,
  gridOrgStatistics: null,
  
  //   Identification
  lblIdentificationSupport: null,
  chkUseIdentification: null,
  
  lblIdentificationDecisionCard: null,
  cboIdDecisionCard: null,
  cboIdentificationDecisionExpiryCycle: null,
  
  //   Documents
  lblDocuments: null,
  gridDocuments: null,
  
  //   Parameter Sets
  lblParameterSetUserDefined: null,
  cboParameterSetUserDefined: null,
  
  lblParameterSetUserDefinedWeb: null,
  cboParameterSetUserDefinedWeb: null,
  
  //   User Defined
  phUserDefined: null,
  
  //   frmStatisticAdd
  lblStatisticAdd: null,
  cboStatisticClass: null,
  cboStatisticTypeId: null,
  txtStatisticDescription: null,
  cboStatisticFrequency: null,
  numStatisticValue: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

// Other
var mForm_StatisticAdd;
var mStatisticTypeListFiltered;

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   General
  C.lblCodeAndName = widget.UI.Label("lblCodeAndName", {});
  C.txtClientGroupId = widget.UI.TextBox("txtClientGroupId", {
    allowBlank: false,
    maxLength: 5,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.chkActive = widget.UI.CheckBox("chkActive", {
    caption: "Active?",
  });
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 50,
  });
  
  C.lblNewClientDefaults = widget.UI.Label("lblNewClientDefaults", {});
  C.txtNextClientId = widget.UI.TextBox("txtNextClientId", {
    maxLength: 10,
  });
  C.chkCommunicationGeneral = widget.UI.CheckBox("chkCommunicationGeneral", {
    caption: "Send general communication?",
  });
  C.chkCommunicationMarketing = widget.UI.CheckBox("chkCommunicationMarketing", {
    caption: "Send marketing communication?",
  });

  //   New Client Wizard
  C.lblNewClientWizardSupport = widget.UI.Label("lblNewClientWizardSupport", {});
  C.chkHideInNewClientWizard = widget.UI.CheckBox("chkHideInNewClientWizard", {
    caption: "Exclude this Client Group from the New Client Wizard?",
    captionWrap: true,
  });
  
  C.lblIncludeInNewWizard = widget.UI.Label("lblIncludeInNewWizard", {});
  C.chkNewWizardShowAddreses = widget.UI.CheckBox("chkNewWizardShowAddreses", {
    caption: "Postal and Physical Addresses",
    captionWrap: true,
  });
  C.chkNewWizardShowContactMethods = widget.UI.CheckBox("chkNewWizardShowContactMethods", {
    caption: "Contact Methods",
    captionWrap: true,
  });
  C.chkNewWizardShowFullContacts = widget.UI.CheckBox("chkNewWizardShowFullContacts", {
    caption: "Full Contacts (Addresses &amp; Contact Methods)",
    captionWrap: true,
  });
  C.chkNewWizardShowImage = widget.UI.CheckBox("chkNewWizardShowImage", {
    caption: "Image",
    captionWrap: true,
  });
  C.chkNewWizardShowIdentification = widget.UI.CheckBox("chkNewWizardShowIdentification", {
    caption: "Identification",
    captionWrap: true,
    
    onChange: chkNewWizardShowIdentification_Change,
  });
  C.chkNewWizardShowIdentificationDecision = widget.UI.CheckBox("chkNewWizardShowIdentificationDecision", {
    caption: "Identification Decision",
    captionWrap: true,
  });
  C.chkNewWizardShowEmployment = widget.UI.CheckBox("chkNewWizardShowEmployment", {
    caption: "Employment/ Personnel",
    captionWrap: true,
  });
  C.chkNewWizardShowStatistics = widget.UI.CheckBox("chkNewWizardShowStatistics", {
    caption: "Statistics",
    captionWrap: true,
  });
  C.chkNewWizardShowBankingDetails = widget.UI.CheckBox("chkNewWizardShowBankingDetails", {
    caption: "Banking Details",
    captionWrap: true,
  });
  C.chkNewWizardShowOtherInformation = widget.UI.CheckBox("chkNewWizardShowOtherInformation", {
    caption: "Other Information",
    captionWrap: true,
  });
  C.chkNewWizardShowTax = widget.UI.CheckBox("chkNewWizardShowTax", {
    caption: "Tax Information",
    captionWrap: true,
  });
  C.chkNewWizardShowWebAccess = widget.UI.CheckBox("chkNewWizardShowWebAccess", {
    caption: "Web Access",
    captionWrap: true,
  });
  C.chkNewWizardShowUserDefined = widget.UI.CheckBox("chkNewWizardShowUserDefined", {
    caption: "User Defined",
    captionWrap: true,
  });
  
  C.lblNewWizardOptionsIndividual = widget.UI.Label("lblNewWizardOptionsIndividual", {});
  C.chkNewWizardIndividualTaxNumberMandatory = widget.UI.CheckBox("chkNewWizardIndividualTaxNumberMandatory", {
    caption: "Tax Number is mandatory?",
    captionWrap: true,
  });
  C.chkNewWizardIndividualDateOfBirthMandatory = widget.UI.CheckBox("chkNewWizardIndividualDateOfBirthMandatory", {
    caption: "Date of Birth is mandatory?",
    captionWrap: true,
  });
  C.chkNewWizardIndividualGenderMandatory = widget.UI.CheckBox("chkNewWizardIndividualGenderMandatory", {
    caption: "Gender is mandatory?",
    captionWrap: true,
  });
  
  C.lblNewWizardOptionsOrganisation = widget.UI.Label("lblNewWizardOptionsOrganisation", {});
  C.chkNewWizardOrganisationBusinessNumberMandatory = widget.UI.CheckBox("chkNewWizardOrganisationBusinessNumberMandatory", {
    caption: "Business Number is mandatory?",
    captionWrap: true,
  });
  C.chkNewWizardOrganisationTaxNumberMandatory = widget.UI.CheckBox("chkNewWizardOrganisationTaxNumberMandatory", {
    caption: "Tax Number is mandatory?",
    captionWrap: true,
  });
  C.chkNewWizardOrganisationCompanyNumberMandatory = widget.UI.CheckBox("chkNewWizardOrganisationCompanyNumberMandatory", {
    caption: "Company Number is mandatory?",
    captionWrap: true,
  });
  
  C.lblValidatorScript = widget.UI.Label("lblValidatorScript", {});
  C.cboNewWizardValidatorScript = widget.UI.DBCombo("cboNewWizardValidatorScript", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  
  C.lblAddresses = widget.UI.Label("lblAddresses", {});
  C.cboPostalContactMethod = widget.UI.DBCombo("cboPostalContactMethod", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.cboPhysicalContactMethod = widget.UI.DBCombo("cboPhysicalContactMethod", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  
  C.lblContactMethods = widget.UI.Label("lblContactMethods", {});

  //   Statistics Individual
  C.lblIndSupport = widget.UI.Label("lblIndSupport", {});
  C.cboIndUseStatistics = widget.UI.ComboBox("cboIndUseStatistics", {
    limitToList: true,
  });
  
  C.lblIndStatisticsOptions = widget.UI.Label("lblIndStatisticsOptions", {});
  C.chkIndStatisticsFixed = widget.UI.CheckBox("chkIndStatisticsFixed", {
    caption: "Should Statistics be Fixed?",
  });
  C.numIndAvailableAssetsPercentage = widget.UI.NumberBox("numIndAvailableAssetsPercentage", {
    allowBlank: false,
    minValue: 0,
    maxValue: 100,
    percentage: true,
  });
  C.numIndAvailableIncomePercentage = widget.UI.NumberBox("numIndAvailableIncomePercentage", {
    allowBlank: false,
    minValue: 0,
    maxValue: 100,
    percentage: true,
  });
  C.cboIndStatisticsExpiryCycle = widget.UI.DateCycleComboBox("cboIndStatisticsExpiryCycle", {});
  C.cboIndStatisticsScript = widget.UI.DBCombo("cboIndStatisticsScript", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  
  C.lblIndStatisticsDefaults = widget.UI.Label("lblIndStatisticsDefaults", {});
  
  //   Statistics Organisation
  C.lblOrgSupport = widget.UI.Label("lblOrgSupport", {});
  C.cboOrgUseStatistics = widget.UI.ComboBox("cboOrgUseStatistics", {
    limitToList: true,
  });
  
  C.lblOrgStatisticsOptions = widget.UI.Label("lblOrgStatisticsOptions", {});
  C.chkOrgStatisticsFixed = widget.UI.CheckBox("chkOrgStatisticsFixed", {
    caption: "Should Statistics be Fixed?",
  });
  C.numOrgAvailableAssetsPercentage = widget.UI.NumberBox("numOrgAvailableAssetsPercentage", {
    allowBlank: false,
    minValue: 0,
    maxValue: 100,
    percentage: true,
  });
  C.numOrgAvailableIncomePercentage = widget.UI.NumberBox("numOrgAvailableIncomePercentage", {
    allowBlank: false,
    minValue: 0,
    maxValue: 100,
    percentage: true,
  });
  C.cboOrgStatisticsExpiryCycle = widget.UI.DateCycleComboBox("cboOrgStatisticsExpiryCycle", {});
  C.cboOrgStatisticsScript = widget.UI.DBCombo("cboOrgStatisticsScript", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  
  C.lblOrgStatisticsDefaults = widget.UI.Label("lblOrgStatisticsDefaults", {});

  //   Identification
  C.lblIdentificationSupport = widget.UI.Label("lblIdentificationSupport", {});
  C.chkUseIdentification = widget.UI.CheckBox("chkUseIdentification", {
    caption: "Use Identification?",
  });
  
  C.lblIdentificationDecisionCard = widget.UI.Label("lblIdentificationDecisionCard", {});
  C.cboIdDecisionCard = widget.UI.DBCombo("cboIdDecisionCard", {
    limitToList: true,
    
    onChange: cboIdDecisionCard_Change,
  });
  C.cboIdentificationDecisionExpiryCycle = widget.UI.DateCycleComboBox("cboIdentificationDecisionExpiryCycle", {});

  //   Documents
  C.lblDocuments = widget.UI.Label("lblDocuments", {});

  //   Parameter Sets
  C.lblParameterSetUserDefined = widget.UI.Label("lblParameterSetUserDefined", {});
  C.cboParameterSetUserDefined = widget.UI.DBCombo("cboParameterSetUserDefined", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  
  C.lblParameterSetUserDefinedWeb = widget.UI.Label("lblParameterSetUserDefinedWeb", {});
  C.cboParameterSetUserDefinedWeb = widget.UI.DBCombo("cboParameterSetUserDefinedWeb", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

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

  //   frmStatisticAdd
  C.lblStatisticAdd = widget.UI.Label("lblStatisticAdd", {});
  C.cboStatisticClass = widget.UI.ComboBox("cboStatisticClass", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    
    onChange: cboStatisticClass_Change,
  });
  C.cboStatisticTypeId = widget.UI.DBCombo("cboStatisticTypeId", {
    allowBlank: false,
    limitToList: true,
    
    onChange: cboStatisticTypeId_Change,
  });
  C.txtStatisticDescription = widget.UI.TextBox("txtStatisticDescription", {
    maxLength: 50,
  });
  C.cboStatisticFrequency = widget.UI.ComboBox("cboStatisticFrequency", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.numStatisticValue = widget.UI.NumberBox("numStatisticValue", {
    blankIfZero: true,
  });

  // Grids
  C.gridContactMethods = widget.UI.Grid("gridContactMethods", {
    allowMultiRowSelect: true,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,

    onAction: gridContactMethods_Action,
    onAfterRowActivate: gridContactMethods_AfterRowActivate,
    onBeforeCellUpdate: gridContactMethods_BeforeCellUpdate,
    onInitialiseRow: gridContactMethods_InitialiseRow,    
    onSelectedRowsChanged: gridContactMethods_SelectedRowsChanged,
  });  
  
  C.gridIndStatistics = widget.UI.Grid("gridIndStatistics", {
    groupByColumns: "StatisticClass",
    allowMultiRowSelect: true,    
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,

    onAction: gridIndStatistics_Action,
    onAfterRowActivate: gridIndStatistics_AfterRowActivate,
    onBeforeCellUpdate: gridIndStatistics_BeforeCellUpdate,
    onInitialiseRow: gridIndStatistics_InitialiseRow,    
    onSelectedRowsChanged: gridIndStatistics_SelectedRowsChanged,
  });
  
  C.gridOrgStatistics = widget.UI.Grid("gridOrgStatistics", {
    groupByColumns: "StatisticClass",
    allowMultiRowSelect: true,    
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,

    onAction: gridOrgStatistics_Action,
    onAfterRowActivate: gridOrgStatistics_AfterRowActivate,
    onBeforeCellUpdate: gridOrgStatistics_BeforeCellUpdate,
    onInitialiseRow: gridOrgStatistics_InitialiseRow,    
    onSelectedRowsChanged: gridOrgStatistics_SelectedRowsChanged,
  });

  C.gridDocuments = widget.UI.Grid("gridDocuments", {
    groupByColumns: "Category",
    allowMultiRowSelect: true,    
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,

    onAction: gridDocuments_Action,
    onAfterRowActivate: gridDocuments_AfterRowActivate,
    onBeforeCellUpdate: gridDocuments_BeforeCellUpdate,
    onInitialiseRow: gridDocuments_InitialiseRow,    
    onSelectedRowsChanged: gridDocuments_SelectedRowsChanged,
  });

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

  // Create Tabs
  tabDetails = new widget.UI.Tabs("tabDetails", {
    style: "normal",
    onSelectedTabChanged: tabDetails_Refresh,
  });

  // 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");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabDetails_Cancel);
  cmdFinish.click(Form_ExecuteAction_Finish);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {  
  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mStatisticTypeListFiltered = 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);

  // Give Collections ability To lookup by code
  widget.ArrayAllowLookupById(mRecord.StatisticTypes, "StatisticTypeId");

  // Set Tab
  if (mRecord &amp;&amp; mRecord.PageId) {
    tabDetails.SelectedTabId(mRecord.PageId);

    // Hide other Pages
    if (mRecord.HideOtherPages) {
      tabDetails.ShowSingleTab(mRecord.PageId);
    }
  }
  else {
    tabDetails.SelectedTabId("General");
  }

  // Page Permissions
  if (!mRecord.AllowPageGeneral) tabDetails.TabVisible("General", false);
  if (!mRecord.AllowPageNewClientWizard) tabDetails.TabVisible("NewClientWizard", false);
  if (!mRecord.AllowPageStatisticsIndividual) tabDetails.TabVisible("StatisticsIndividual", false);
  if (!mRecord.AllowPageStatisticsOrganisation) tabDetails.TabVisible("StatisticsOrganisation", false);
  if (!mRecord.AllowPageIdentification) tabDetails.TabVisible("Identification", false);
  if (!mRecord.AllowPageDocuments) tabDetails.TabVisible("Documents", false);
  if (!mRecord.AllowPageParameterSets) tabDetails.TabVisible("ParameterSets", false);
  if (!mRecord.AllowPageUserDefined) tabDetails.TabVisible("UserDefined", false);

  // Load Fields
  Fields_Load();

  // Save Fields (so UserData 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
    if (mRecord.AllowPageGeneral) {
      C.txtClientGroupId.Text(mRecord.ClientGroupId);
      C.chkActive.Value(mRecord.Active);
      C.txtDescription.Text(mRecord.Description);    
      
      C.txtNextClientId.Text(mRecord.NextClientId);
      C.chkCommunicationGeneral.Value(mRecord.CommunicationGeneral);
      C.chkCommunicationMarketing.Value(mRecord.CommunicationMarketing);
    }    
    
    //   New Client Wizard
    if (mRecord.AllowPageNewClientWizard) {
      C.chkHideInNewClientWizard.Value(mRecord.HideInNewClientWizard);
    
      C.chkNewWizardShowAddreses.Value(mRecord.NewWizardShowAddresses);
      C.chkNewWizardShowContactMethods.Value(mRecord.NewWizardShowContactMethods);
      C.chkNewWizardShowFullContacts.Value(mRecord.NewWizardShowFullContacts);
      C.chkNewWizardShowImage.Value(mRecord.NewWizardShowImage);
      C.chkNewWizardShowIdentification.Value(mRecord.NewWizardShowIdentification);
      C.chkNewWizardShowIdentificationDecision.Value(mRecord.NewWizardShowIdentificationDecision);
      C.chkNewWizardShowEmployment.Value(mRecord.NewWizardShowEmployment);
      C.chkNewWizardShowStatistics.Value(mRecord.NewWizardShowStatistics);
      C.chkNewWizardShowBankingDetails.Value(mRecord.NewWizardShowBankingDetails);
      C.chkNewWizardShowOtherInformation.Value(mRecord.NewWizardShowOtherInformation);
      C.chkNewWizardShowTax.Value(mRecord.NewWizardShowTaxInformation);
      C.chkNewWizardShowWebAccess.Value(mRecord.NewWizardShowWebAccess);
      C.chkNewWizardShowUserDefined.Value(mRecord.NewWizardShowUserDefined);
      
      C.chkNewWizardIndividualTaxNumberMandatory.Value(mRecord.NewWizardIndividualTaxNumberMandatory);
      C.chkNewWizardIndividualDateOfBirthMandatory.Value(mRecord.NewWizardIndividualDateOfBirthMandatory);
      C.chkNewWizardIndividualGenderMandatory.Value(mRecord.NewWizardIndividualGenderMandatory);
      
      C.chkNewWizardOrganisationBusinessNumberMandatory.Value(mRecord.NewWizardOrganisationBusinessNumberMandatory);
      C.chkNewWizardOrganisationTaxNumberMandatory.Value(mRecord.NewWizardOrganisationTaxNumberMandatory);
      C.chkNewWizardOrganisationCompanyNumberMandatory.Value(mRecord.NewWizardOrganisationCompanyNumberMandatory);
      
      C.cboNewWizardValidatorScript.Text(mRecord.NewWizardValidatorScriptId);
      
      C.cboPostalContactMethod.Text(mRecord.PostalContactMethodId);
      C.cboPhysicalContactMethod.Text(mRecord.PhysicalContactMethodId);
    }    
    
    //   Statistics Individual
    if (mRecord.AllowPageStatisticsIndividual) {
      C.cboIndUseStatistics.Text(mRecord.IndividualUseStatistics);
      
      C.chkIndStatisticsFixed.Value(mRecord.IndividualStatisticsFixed);
      C.numIndAvailableAssetsPercentage.Value(mRecord.IndividualAvailableAssetsPercent);
      C.numIndAvailableIncomePercentage.Value(mRecord.IndividualAvailableIncomePercent);
      C.cboIndStatisticsExpiryCycle.Text(mRecord.IndividualStatisticsExpiryCycle);
      C.cboIndStatisticsScript.Text(mRecord.IndividualStatisticsSummaryScriptId);
    }    
    
    //   Statistics Organisation
    if (mRecord.AllowPageStatisticsOrganisation) {
      C.cboOrgUseStatistics.Text(mRecord.OrganisationUseStatistics);
    
      C.chkOrgStatisticsFixed.Value(mRecord.OrganisationStatisticsFixed);
      C.numOrgAvailableAssetsPercentage.Value(mRecord.OrganisationAvailableAssetsPercent);
      C.numOrgAvailableIncomePercentage.Value(mRecord.OrganisationAvailableIncomePercent);
      C.cboOrgStatisticsExpiryCycle.Text(mRecord.OrganisationStatisticsExpiryCycle);
      C.cboOrgStatisticsScript.Text(mRecord.OrganisationStatisticsSummaryScriptId);
    }    
    
    //   Identification
    if (mRecord.AllowPageIdentification) {
      C.chkUseIdentification.Value(mRecord.UseIdentification);
      
      C.cboIdDecisionCard.Text(mRecord.IdentificationDecisionCardId);
      C.cboIdentificationDecisionExpiryCycle.Text(mRecord.IdentificationDecisionExpiryCycle);
    }    
    
    //   Parameter Sets
    if (mRecord.AllowPageParameterSets) {
      C.cboParameterSetUserDefined.Text(mRecord.UserDefinedParameterSetId);
    
      C.cboParameterSetUserDefinedWeb.Text(mRecord.UserDefinedWebParameterSetId);
    }    
    
    // User Defined
    if (mRecord.AllowPageUserDefined) {
      C.phUserDefined.Initialise(mRecord.UserDefinedParameters);
      C.phUserDefined.UpdateParameterValues(JSON.parse(mRecord.UserDataJson));
    }
  }

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

  // Update Controls  

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabDetails_Refresh();
  tabDetails_Resize();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  //   General
  if (mRecord.AllowPageGeneral) {
    mRecord.ClientGroupId = C.txtClientGroupId.Text();
    mRecord.Active = C.chkActive.Value();
    mRecord.Description = C.txtDescription.Text();
    
    mRecord.NextClientId = C.txtNextClientId.Text();
    mRecord.CommunicationGeneral = C.chkCommunicationGeneral.Value();
    mRecord.CommunicationMarketing = C.chkCommunicationMarketing.Value();
  }  
  
  //   New Client Wizard
  if (mRecord.AllowPageNewClientWizard) {
    mRecord.HideInNewClientWizard = C.chkHideInNewClientWizard.Value();
  
    mRecord.NewWizardShowAddresses = C.chkNewWizardShowAddreses.Value();
    mRecord.NewWizardShowContactMethods = C.chkNewWizardShowContactMethods.Value();
    mRecord.NewWizardShowFullContacts = C.chkNewWizardShowFullContacts.Value();
    mRecord.NewWizardShowImage = C.chkNewWizardShowImage.Value();
    mRecord.NewWizardShowIdentification = C.chkNewWizardShowIdentification.Value();
    mRecord.NewWizardShowIdentificationDecision = C.chkNewWizardShowIdentificationDecision.Value();
    mRecord.NewWizardShowEmployment = C.chkNewWizardShowEmployment.Value();
    mRecord.NewWizardShowStatistics = C.chkNewWizardShowStatistics.Value();
    mRecord.NewWizardShowBankingDetails = C.chkNewWizardShowBankingDetails.Value();
    mRecord.NewWizardShowOtherInformation = C.chkNewWizardShowOtherInformation.Value();
    mRecord.NewWizardShowTaxInformation = C.chkNewWizardShowTax.Value();
    mRecord.NewWizardShowWebAccess = C.chkNewWizardShowWebAccess.Value();
    mRecord.NewWizardShowUserDefined = C.chkNewWizardShowUserDefined.Value();
    
    mRecord.NewWizardIndividualTaxNumberMandatory = C.chkNewWizardIndividualTaxNumberMandatory.Value();
    mRecord.NewWizardIndividualDateOfBirthMandatory = C.chkNewWizardIndividualDateOfBirthMandatory.Value();
    mRecord.NewWizardIndividualGenderMandatory = C.chkNewWizardIndividualGenderMandatory.Value();
    
    mRecord.NewWizardOrganisationBusinessNumberMandatory = C.chkNewWizardOrganisationBusinessNumberMandatory.Value();
    mRecord.NewWizardOrganisationTaxNumberMandatory = C.chkNewWizardOrganisationTaxNumberMandatory.Value();
    mRecord.NewWizardOrganisationCompanyNumberMandatory = C.chkNewWizardOrganisationCompanyNumberMandatory.Value();
    
    mRecord.NewWizardValidatorScriptId = C.cboNewWizardValidatorScript.Text();
    
    mRecord.PostalContactMethodId = C.cboPostalContactMethod.Text();
    mRecord.PhysicalContactMethodId = C.cboPhysicalContactMethod.Text();
  }  
  
  //   Statistics Individual
  if (mRecord.AllowPageStatisticsIndividual) {
    mRecord.IndividualUseStatistics = C.cboIndUseStatistics.Text();
  
    mRecord.IndividualStatisticsFixed = C.chkIndStatisticsFixed.Value();
    mRecord.IndividualAvailableAssetsPercent = C.numIndAvailableAssetsPercentage.Value();
    mRecord.IndividualAvailableIncomePercent = C.numIndAvailableIncomePercentage.Value();
    mRecord.IndividualStatisticsExpiryCycle = C.cboIndStatisticsExpiryCycle.Text();
    mRecord.IndividualStatisticsSummaryScriptId = C.cboIndStatisticsScript.Text();
  }  
  
  //   Statistics Organisation
  if (mRecord.AllowPageStatisticsOrganisation) {
    mRecord.OrganisationUseStatistics = C.cboOrgUseStatistics.Text();
  
    mRecord.OrganisationStatisticsFixed = C.chkOrgStatisticsFixed.Value();
    mRecord.OrganisationAvailableAssetsPercent = C.numOrgAvailableAssetsPercentage.Value();
    mRecord.OrganisationAvailableIncomePercent = C.numOrgAvailableIncomePercentage.Value();
    mRecord.OrganisationStatisticsExpiryCycle = C.cboOrgStatisticsExpiryCycle.Text();
    mRecord.OrganisationStatisticsSummaryScriptId = C.cboOrgStatisticsScript.Text();
  }  
  
  //   Identification
  if (mRecord.AllowPageIdentification) {
    mRecord.UseIdentification = C.chkUseIdentification.Value();
  
    mRecord.IdentificationDecisionCardId = C.cboIdDecisionCard.Text();
    mRecord.IdentificationDecisionExpiryCycle = C.cboIdentificationDecisionExpiryCycle.Text();
  }  
  
  //   Parameter Sets
  if (mRecord.AllowPageParameterSets) {
    mRecord.UserDefinedParameterSetId = C.cboParameterSetUserDefined.Text();
  
    mRecord.UserDefinedWebParameterSetId = C.cboParameterSetUserDefinedWeb.Text();
  }  
  
  //   User Defined
  if (mRecord.AllowPageUserDefined) {
    mRecord.UserDataJson = JSON.stringify(C.phUserDefined.GetParameterValuesWithTypes());
  }
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    if (mRecord.Pk) {
      widget.SetHeading("Client Group (" + mRecord.ClientGroupId + ")");
    }
    else {
      widget.SetHeading("New Client Group");
    }
  }

  // Lists
  if (mRecord) {
    //   New Client Wizard
    C.cboPostalContactMethod.RefreshFromStandardRange("ContactMethods", mRecord.ContactAddressesSqlWhere, false, mRecord.PostalContactMethodId);
    C.cboPhysicalContactMethod.RefreshFromStandardRange("ContactMethods", mRecord.ContactAddressesSqlWhere, false, mRecord.PhysicalContactMethodId);
    C.cboNewWizardValidatorScript.RefreshFromStandardRange("Scripts", mRecord.WizardValidatorSqlWhere);
    
    //   Statistics Individual
    C.cboIndUseStatistics.ListFromCollection(mRecord.ClientGroupUseStatisticsList, "Description");
    C.cboIndStatisticsExpiryCycle.ListFromCsvString(mRecord.ExpiryCycleList);
    C.cboIndStatisticsScript.RefreshFromStandardRange("Scripts", mRecord.StatisticsSummarySqlWhere, false, mRecord.IndividualStatisticsSummaryScriptId);
    
    //   Statistics Organisation
    C.cboOrgUseStatistics.ListFromCollection(mRecord.ClientGroupUseStatisticsList, "Description");
    C.cboOrgStatisticsExpiryCycle.ListFromCsvString(mRecord.ExpiryCycleList);
    C.cboOrgStatisticsScript.RefreshFromStandardRange("Scripts", mRecord.StatisticsSummarySqlWhere, false, mRecord.OrganisationStatisticsSummaryScriptId);
    
    //   Identification
    C.cboIdDecisionCard.RefreshFromStandardRange("DecisionCards", mRecord.DecisionCardSqlWhere, false, mRecord.IdentificationDecisionCardId);
    C.cboIdentificationDecisionExpiryCycle.ListFromCsvString(mRecord.ExpiryCycleList);
    
    //   Parameter Sets
    C.cboParameterSetUserDefined.RefreshFromStandardRange("ParameterSets", "", false, mRecord.UserDefinedParameterSetId);
    
    if (mRecord.ShowUserDefinedWeb) {
      C.cboParameterSetUserDefinedWeb.RefreshFromStandardRange("ParameterSets", "", false, mRecord.UserDefinedWebParameterSetId);
    }
    else {
      C.lblParameterSetUserDefinedWeb.VisibleRow(false);
      C.cboParameterSetUserDefinedWeb.VisibleRow(false);
    }    
  }

  // Controls
  if (mRecord) {
  }

  // Pages
  if (mRecord) {
    // NOTE: Even though many pages are updated in tabDetails_Refresh, we must update them here to ensure controls are hidden since this is not a wizard and all pages are validated on "Finish"
    pageGeneral_Refresh();
    pageNewClientWizard_Refresh();
    if (mRecord.AllowPageStatisticsIndividual) pageStatisticsIndividual_Refresh();
    if (mRecord.AllowPageStatisticsOrganisation) pageStatisticsOrganisation_Refresh();    
    if (mRecord.AllowPageIdentification) pageIdentification_Refresh();
    pageDocuments_Refresh();
  }

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) {
    cmdFinish.prop("disabled", true);
    frmMain.FormReadOnly(C, true);
  }

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

  // Resize Tab
  tabDetails_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Mobile Optimisations
  var el = $(".mobile-indent th.indent1, .mobile-indent th.no-indent1");
  if (window.innerWidth &lt; 500) {
    el.addClass("no-indent1").removeClass("indent1");
  }
  else {
    el.addClass("indent1").removeClass("no-indent1");
  }

  // General

  // Tab
  tabDetails_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 tabDetails_Cancel() {
  if (Form_IsDirty()) {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form without saving your changes?", { heading: "Close Form" }, tabDetails_Cancel_Finalise);
  }
  else {
    // Cancel immediately
    tabDetails_Cancel_Finalise();
  }
}

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

// ==========
// Resize Tab
// ==========
function tabDetails_Resize() {
  switch (tabDetails.SelectedTabId()) {
    case "General":
      // General
      C.txtDescription.WidthResizeFromParent();
      break;
  }
}

// ===========
// Refresh Tab
// ===========
function tabDetails_Refresh() {
   // Load details
  switch (tabDetails.SelectedTabId()) {
    case "General":
      pageGeneral_Refresh();
      break;

    case "NewClientWizard":
      pageNewClientWizard_Refresh();
      break;

    case "StatisticsIndividual":
      pageStatisticsIndividual_Refresh();
      break;
      
    case "StatisticsOrganisation":
      pageStatisticsOrganisation_Refresh();
      break;

    case "Identification":
      pageIdentification_Refresh();
      break;

    case "Documents":
      pageDocuments_Refresh();
      break;

    default:
      break;
  }

  // Resize
  tabDetails_Resize();

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

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch(actionId) {
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Assume Success
  var Ok = true;

  // Validate
  Ok = tabDetails.Validate();

  // Prompt
  if (Ok) {
    if (mRecord.PromptOnSave) {
      // Confirm
      widget.UI.MsgBoxConfirm("Are you sure you want to save this record?",
                              { heading: "Save" },
                              Form_ExecuteAction_FinishPost);

    }
    else {
      // Save without prompting
      Form_ExecuteAction_FinishPost();
    }
  }
}

function Form_ExecuteAction_FinishPost() {
  // Disable Form
  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.StatisticTypes = null;

  // Finish
  widget.GetString("Finish", params,
    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();
    }
  );
}

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

  // Controls
}

// ===================
// pageNewClientWizard
// ===================
function pageNewClientWizard_Refresh() {
  if (!mRecord) return;
  
  // Controls
  if (!mRecord.AddonsClientAdvanced) {
    C.chkNewWizardShowIdentification.VisibleRow(false);
    C.chkNewWizardShowIdentificationDecision.VisibleRow(false);
    C.chkNewWizardShowEmployment.VisibleRow(false);      
  }
  if (!mRecord.AddonsClientStatistics) {
    C.chkNewWizardShowStatistics.VisibleRow(false);
  }
  if (!mRecord.AddonsWebAutomation) {
    C.chkNewWizardShowWebAccess.VisibleRow(false);
  }
  
  // Terminology
  if (mRecord.Terminology_TaxNumberIndividual) {
    C.chkNewWizardIndividualTaxNumberMandatory.Caption(mRecord.Terminology_TaxNumberIndividual + " is mandatory?");
  }
  else {
    C.chkNewWizardIndividualTaxNumberMandatory.VisibleRow(false);
  }
  
  if (mRecord.Terminology_BusinessNumber) {
    C.chkNewWizardOrganisationBusinessNumberMandatory.Caption(mRecord.Terminology_BusinessNumber + " is mandatory?");
  }
  else {
    C.chkNewWizardOrganisationBusinessNumberMandatory.VisibleRow(false);
  }
  
  if (mRecord.Terminology_TaxNumberOrganisation) {
    C.chkNewWizardOrganisationTaxNumberMandatory.Caption(mRecord.Terminology_TaxNumberOrganisation + " is mandatory?");
  }
  else {
    C.chkNewWizardOrganisationTaxNumberMandatory.VisibleRow(false);
  }
  
  if (mRecord.Terminology_CompanyNumber) {
    C.chkNewWizardOrganisationCompanyNumberMandatory.Caption(mRecord.Terminology_CompanyNumber + " is mandatory?");
  }
  else {
    C.chkNewWizardOrganisationCompanyNumberMandatory.VisibleRow(false);
  }
  
  // Grids
  gridContactMethods_Refresh();
  
  // Change Events
  chkNewWizardShowIdentification_Change();
}

// ========================
// pageStatisticsIndividual
// ========================
function pageStatisticsIndividual_Refresh() {
  if (!mRecord) return;

  // Controls
  
  // Grids
  gridIndStatistics_Refresh();
}

// ==========================
// pageStatisticsOrganisation
// ==========================
function pageStatisticsOrganisation_Refresh() {
  if (!mRecord) return;

  // Controls
  
  // Grids
  gridOrgStatistics_Refresh();
}

// ==================
// pageIdentification
// ==================
function pageIdentification_Refresh() {
  if (!mRecord) return;
  
  // Controls
  cboIdDecisionCard_Change();
}

// =============
// pageDocuments
// =============
function pageDocuments_Refresh() {
  if (!mRecord) return;

  // Controls
  
  // Grids
  gridDocuments_Refresh();
}

// ==============================
// chkNewWizardShowIdentification
// ==============================
function chkNewWizardShowIdentification_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.chkNewWizardShowIdentificationDecision.ReadOnly(!C.chkNewWizardShowIdentification.Value());
}

// =================
// cboIdDecisionCard
// =================
function cboIdDecisionCard_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.cboIdentificationDecisionExpiryCycle.ReadOnly(!C.cboIdDecisionCard.Text());
}

// =================
// cboStatisticClass
// =================
function cboStatisticClass_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Clear fields
  if (e) {
    C.cboStatisticTypeId.Text("");
    C.txtStatisticDescription.Text("");
    C.cboStatisticFrequency.Text("");
    C.cboStatisticFrequency.VisibleRow(false);
    C.numStatisticValue.Value(0);
    
    // Filter Statistic Type based upon the selected Class
    UpdateStatisticTypeList();
  }
}

// ==================
// cboStatisticTypeId
// ==================
function cboStatisticTypeId_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  if (e &amp;&amp; C.cboStatisticTypeId.Text()) {
    var statisticType = mRecord.StatisticTypes.GetItem(C.cboStatisticTypeId.Text());
    if (statisticType) {
      C.cboStatisticClass.Text(statisticType.StatisticClass);
      C.txtStatisticDescription.Text(statisticType.Description);
      C.cboStatisticFrequency.VisibleRow(statisticType.CanUpdateFrequencyPerAnnum);
      
      // Update Controls
      UpdateStatisticTypeList();
    }
  }
}

function UpdateStatisticTypeList() {
  var list;
    
  if (C.cboStatisticClass.Text()) {
    var list = [];
    
    for (var i = 0; i &lt; mRecord.StatisticTypes.length; i++) {
      var item = mRecord.StatisticTypes[i];
      
      if (item.StatisticClass == C.cboStatisticClass.Text()) {
        list.push(item);
      }
    }
  }
  else {      
    list = mStatisticTypeListFiltered;
  }    
  C.cboStatisticTypeId.RefreshFromCollection(list, "StatisticTypeId", "Description", "StatisticTypeId,StatisticClass,Description");
}

// ==================
// gridContactMethods
// ==================
function gridContactMethods_Refresh() {
  // Add Columns
  C.gridContactMethods.ClearColumns();
  C.gridContactMethods.AddColumnBoolean("Individual", { caption: "Individual", allowEdit: !mRecord.ReadOnly });
  C.gridContactMethods.AddColumnBoolean("Organisation", { caption: "Organisation", allowEdit: !mRecord.ReadOnly });
  C.gridContactMethods.AddColumnBoolean("Active", { caption: "Active" });
  C.gridContactMethods.AddColumnCode("ContactMethodId", { caption: "Id", width: "10em" });
  C.gridContactMethods.AddColumnString("Description", { caption: "Description" });

  // Actions
  if (!mRecord.ReadOnly) {
    C.gridContactMethods.Actions().Define([{ actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                          { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                          { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                          { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },                                          
                                          {},
                                          { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                          { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" },
                                          {},
                                          { actionId: "MoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" },
                                          { actionId: "MoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" },
                                         ]);
  }

  // Refresh
  C.gridContactMethods.VirtualDataRefresh(mRecord.ContactMethods);

  // Activate First Row
  C.gridContactMethods.ActivateFirstDataRow();
}

function gridContactMethods_InitialiseRow(e) {
  var item = mRecord.ContactMethods[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  
  // Styling
  e.row.cells.Individual.readOnly = mRecord.ReadOnly;
  e.row.cells.Organisation.readOnly = mRecord.ReadOnly;
  e.row.cells.Active.readOnly = true;
  e.row.cells.ContactMethodId.readOnly = true;
  e.row.cells.Description.readOnly = true;
  
  // Hyperlinks
  e.row.cells.ContactMethodId.hyperlink = "app://FormShow?form=ContactMethods&amp;id=" + widget.UI.HtmlEncode(item.ContactMethodId);
}

function gridContactMethods_Action(actionId) {
  switch (actionId.toUpperCase()) {
    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);
        }
      }
      C.gridContactMethods.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord.ContactMethods.length; i++) {
        indexes.push(i);
      }
      C.gridContactMethods.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTNONE":
      C.gridContactMethods.SetSelectedRowIndexes([], true);
      break;

    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridContactMethods.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mRecord.ContactMethods[selectedItems[i]];
        if (actionId.toUpperCase() == "CHECK") {
          item.Individual = true;
          item.Organisation = true;
        }
        else {
          item.Individual = false;
          item.Organisation = false;
        }
      }
      C.gridContactMethods.VirtualDataRefresh(mRecord.ContactMethods, true, { retainSelectedRows: true });
      break;
      
    case "MOVEUP":
      C.gridContactMethods.RowMoveUp();
      break;
      
    case "MOVEDOWN":
      C.gridContactMethods.RowMoveDown();
      break;
  }
  
  // Refresh buttons
  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);

  // Reset
  C.gridContactMethods.Actions().SetEnabled("SelectUp", false);
  C.gridContactMethods.Actions().SetEnabled("SelectDown", false);
  C.gridContactMethods.Actions().SetEnabled("Check", false);
  C.gridContactMethods.Actions().SetEnabled("Uncheck", false);
  C.gridContactMethods.Actions().SetEnabled("MoveUp", false);
  C.gridContactMethods.Actions().SetEnabled("MoveDown", false);

  switch (rows.length) {
    case 0:
      // Don't show anything
      break;
  
    case 1:
      C.gridContactMethods.Actions().SetEnabled("SelectUp", true);
      C.gridContactMethods.Actions().SetEnabled("SelectDown", true);
      C.gridContactMethods.Actions().SetEnabled("Check", true);
      C.gridContactMethods.Actions().SetEnabled("Uncheck", true);
      C.gridContactMethods.Actions().SetEnabled("MoveUp", true);
      C.gridContactMethods.Actions().SetEnabled("MoveDown", true);
      break;    
      
    default:
      C.gridContactMethods.Actions().SetEnabled("SelectUp", true);
      C.gridContactMethods.Actions().SetEnabled("SelectDown", true);
      C.gridContactMethods.Actions().SetEnabled("Check", true);
      C.gridContactMethods.Actions().SetEnabled("Uncheck", true);
      break;  
  }

  C.gridContactMethods.RefreshButtons();
}

function gridContactMethods_BeforeCellUpdate(e) {
  var item = mRecord.ContactMethods[e.row.listIndex];
  
  switch(e.columnKey) {
    case "Individual":
      item.Individual = e.newValue;
      break;
      
    case "Organisation":    
      item.Organisation = e.newValue;
      break;
  }
}

// =================
// gridIndStatistics
// =================
function gridIndStatistics_Refresh() {
  // Add Columns
  C.gridIndStatistics.ClearColumns();
  C.gridIndStatistics.AddColumnString("StatisticClass", { caption: "Class", visible: false, });
  C.gridIndStatistics.AddColumnCode("StatisticTypeId", { caption: "Statistic" });
  C.gridIndStatistics.AddColumnString("Description", { caption: "Description", allowEdit: !mRecord.ReadOnly, maxLength: 50 });
  C.gridIndStatistics.AddColumnString("FrequencyPerAnnum", { caption: "Frequency", allowEdit: !mRecord.ReadOnly, list: mRecord.FrequencyPerAnnumList, limitToList: true });
  C.gridIndStatistics.AddColumnCurrency("Value", { caption: "Value", blankIfZero: true, allowEdit: !mRecord.ReadOnly, width: "10em" });

  // Actions
  if (!mRecord.ReadOnly) {
    C.gridIndStatistics.Actions().Define([{ actionId: "Add", tooltipText:"Add a Statistic", icon: "Add" },
                                          { actionId: "Delete", tooltipText:"Delete a Statistic", icon: "Delete" },
                                          {},
                                          { actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                          { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                          { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                          { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },                                          
                                          {},
                                          { actionId: "MoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" },
                                          { actionId: "MoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" },
                                         ]);
  }

  // Refresh
  C.gridIndStatistics.VirtualDataRefresh(mRecord.IndividualStatistics);

  // Activate First Row
  C.gridIndStatistics.ActivateFirstDataRow();
}

function gridIndStatistics_InitialiseRow(e) {
  var item = mRecord.IndividualStatistics[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  
  // Styling
  
  // Read Only
  var statisticType = mRecord.StatisticTypes.GetItem(item.StatisticTypeId);
  if (statisticType) {
    if (statisticType.CanUpdateFrequencyPerAnnum) {
      e.row.cells.FrequencyPerAnnum.readOnly = false;
    }
    else {
      e.row.cells.FrequencyPerAnnum.readOnly = true;
      e.row.cells.FrequencyPerAnnum.value = "";
    }    
  }
  else {
    e.row.cells.FrequencyPerAnnum.readOnly = true;
  }
  
  // Hyperlinks
  e.row.cells.StatisticTypeId.hyperlink = "app://FormShow?form=StatisticTypes&amp;id=" + widget.UI.HtmlEncode(item.StatisticTypeId);
}

function gridIndStatistics_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "ADD":
      StatisticAdd(true);
      break;
      
    case "DELETE":
      C.gridIndStatistics.RemoveSelectedRowsAndCollectionItems();
      
      // Refresh Grid (to update grouping counts etc)
      C.gridIndStatistics.VirtualDataRefresh(mRecord.IndividualStatistics);
      break;
      
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridIndStatistics.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord.IndividualStatistics.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);
        }
      }
      C.gridIndStatistics.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord.IndividualStatistics.length; i++) {
        indexes.push(i);
      }
      C.gridIndStatistics.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTNONE":
      C.gridIndStatistics.SetSelectedRowIndexes([], true);
      break;
      
    case "MOVEUP":
      C.gridIndStatistics.RowMoveUp();
      break;
      
    case "MOVEDOWN":
      C.gridIndStatistics.RowMoveDown();
      break;
  }
  
  // Refresh buttons
  gridIndStatistics_RefreshButtons();
}

function gridIndStatistics_AfterRowActivate(e) {
  // Refresh Buttons
  gridIndStatistics_RefreshButtons();
}

function gridIndStatistics_SelectedRowsChanged(e) {
  // Refresh Buttons
  gridIndStatistics_RefreshButtons();
}

function gridIndStatistics_RefreshButtons() {
  var rows = C.gridIndStatistics.GetSelectedRowIndexes(true, true);

  // Reset
  C.gridIndStatistics.Actions().SetEnabled("Delete", false);
  C.gridIndStatistics.Actions().SetEnabled("SelectUp", false);
  C.gridIndStatistics.Actions().SetEnabled("SelectDown", false);
  C.gridIndStatistics.Actions().SetEnabled("Check", false);
  C.gridIndStatistics.Actions().SetEnabled("Uncheck", false);
  C.gridIndStatistics.Actions().SetEnabled("MoveUp", false);
  C.gridIndStatistics.Actions().SetEnabled("MoveDown", false);

  switch (rows.length) {
    case 0:
      // Don't show anything
      break;
  
    case 1:
      C.gridIndStatistics.Actions().SetEnabled("Delete", true);
      C.gridIndStatistics.Actions().SetEnabled("SelectUp", true);
      C.gridIndStatistics.Actions().SetEnabled("SelectDown", true);
      C.gridIndStatistics.Actions().SetEnabled("Check", true);
      C.gridIndStatistics.Actions().SetEnabled("Uncheck", true);
      C.gridIndStatistics.Actions().SetEnabled("MoveUp", true);
      C.gridIndStatistics.Actions().SetEnabled("MoveDown", true);
      break;    
      
    default:
      C.gridIndStatistics.Actions().SetEnabled("Delete", true);
      C.gridIndStatistics.Actions().SetEnabled("SelectUp", true);
      C.gridIndStatistics.Actions().SetEnabled("SelectDown", true);
      C.gridIndStatistics.Actions().SetEnabled("Check", true);
      C.gridIndStatistics.Actions().SetEnabled("Uncheck", true);
      break;  
  }

  C.gridIndStatistics.RefreshButtons();
}

function gridIndStatistics_BeforeCellUpdate(e) {
  var item = mRecord.IndividualStatistics[e.row.listIndex];
  
  switch(e.columnKey) {
    case "Description":
      item.Description = e.newValue;
      break;
  
    case "FrequencyPerAnnum":
      item.FrequencyPerAnnum = e.newValue;
      break;
      
    case "Value":
      item.Value = e.newValue;
      break;
  }
}

// =================
// gridOrgStatistics
// =================
function gridOrgStatistics_Refresh() {
  // Add Columns
  C.gridOrgStatistics.ClearColumns();
  C.gridOrgStatistics.AddColumnString("StatisticClass", { caption: "Class", visible: false, });
  C.gridOrgStatistics.AddColumnCode("StatisticTypeId", { caption: "Statistic" });
  C.gridOrgStatistics.AddColumnString("Description", { caption: "Description", allowEdit: !mRecord.ReadOnly, maxLength: 50 });
  C.gridOrgStatistics.AddColumnString("FrequencyPerAnnum", { caption: "Frequency", allowEdit: !mRecord.ReadOnly, list: mRecord.FrequencyPerAnnumList, limitToList: true });
  C.gridOrgStatistics.AddColumnCurrency("Value", { caption: "Value", blankIfZero: true, allowEdit: !mRecord.ReadOnly, width: "10em" });

  // Actions
  if (!mRecord.ReadOnly) {
    C.gridOrgStatistics.Actions().Define([{ actionId: "Add", tooltipText:"Add a Statistic", icon: "Add" },
                                          { actionId: "Delete", tooltipText:"Delete a Statistic", icon: "Delete" },
                                          {},
                                          { actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                          { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                          { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                          { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },                                          
                                          {},
                                          { actionId: "MoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" },
                                          { actionId: "MoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" },
                                         ]);
  }

  // Refresh
  C.gridOrgStatistics.VirtualDataRefresh(mRecord.OrganisationStatistics);

  // Activate First Row
  C.gridOrgStatistics.ActivateFirstDataRow();
}

function gridOrgStatistics_InitialiseRow(e) {
  var item = mRecord.OrganisationStatistics[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  
  // Styling
  
  // Read Only
  var statisticType = mRecord.StatisticTypes.GetItem(item.StatisticTypeId);
  if (statisticType) {
    if (statisticType.CanUpdateFrequencyPerAnnum) {
      e.row.cells.FrequencyPerAnnum.readOnly = false;
    }
    else {
      e.row.cells.FrequencyPerAnnum.readOnly = true;
      e.row.cells.FrequencyPerAnnum.value = "";
    }    
  }
  else {
    e.row.cells.FrequencyPerAnnum.readOnly = true;
  }
  
  // Hyperlinks
  e.row.cells.StatisticTypeId.hyperlink = "app://FormShow?form=StatisticTypes&amp;id=" + widget.UI.HtmlEncode(item.StatisticTypeId);
}

function gridOrgStatistics_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "ADD":
      StatisticAdd(false);
      break;
      
    case "DELETE":
      C.gridOrgStatistics.RemoveSelectedRowsAndCollectionItems();
      
      // Refresh Grid (to update grouping counts etc)
      C.gridOrgStatistics.VirtualDataRefresh(mRecord.OrganisationStatistics);
      break;
      
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridOrgStatistics.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord.OrganisationStatistics.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);
        }
      }
      C.gridOrgStatistics.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord.OrganisationStatistics.length; i++) {
        indexes.push(i);
      }
      C.gridOrgStatistics.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTNONE":
      C.gridOrgStatistics.SetSelectedRowIndexes([], true);
      break;
      
    case "MOVEUP":
      C.gridOrgStatistics.RowMoveUp();
      break;
      
    case "MOVEDOWN":
      C.gridOrgStatistics.RowMoveDown();
      break;
  }
  
  // Refresh buttons
  gridOrgStatistics_RefreshButtons();
}

function gridOrgStatistics_AfterRowActivate(e) {
  // Refresh Buttons
  gridOrgStatistics_RefreshButtons();
}

function gridOrgStatistics_SelectedRowsChanged(e) {
  // Refresh Buttons
  gridOrgStatistics_RefreshButtons();
}

function gridOrgStatistics_RefreshButtons() {
  var rows = C.gridOrgStatistics.GetSelectedRowIndexes(true, true);

  // Reset
  C.gridOrgStatistics.Actions().SetEnabled("Delete", false);
  C.gridOrgStatistics.Actions().SetEnabled("SelectUp", false);
  C.gridOrgStatistics.Actions().SetEnabled("SelectDown", false);
  C.gridOrgStatistics.Actions().SetEnabled("Check", false);
  C.gridOrgStatistics.Actions().SetEnabled("Uncheck", false);
  C.gridOrgStatistics.Actions().SetEnabled("MoveUp", false);
  C.gridOrgStatistics.Actions().SetEnabled("MoveDown", false);

  switch (rows.length) {
    case 0:
      // Don't show anything
      break;
  
    case 1:
      C.gridOrgStatistics.Actions().SetEnabled("Delete", true);
      C.gridOrgStatistics.Actions().SetEnabled("SelectUp", true);
      C.gridOrgStatistics.Actions().SetEnabled("SelectDown", true);
      C.gridOrgStatistics.Actions().SetEnabled("Check", true);
      C.gridOrgStatistics.Actions().SetEnabled("Uncheck", true);
      C.gridOrgStatistics.Actions().SetEnabled("MoveUp", true);
      C.gridOrgStatistics.Actions().SetEnabled("MoveDown", true);
      break;    
      
    default:
      C.gridOrgStatistics.Actions().SetEnabled("Delete", true);
      C.gridOrgStatistics.Actions().SetEnabled("SelectUp", true);
      C.gridOrgStatistics.Actions().SetEnabled("SelectDown", true);
      C.gridOrgStatistics.Actions().SetEnabled("Check", true);
      C.gridOrgStatistics.Actions().SetEnabled("Uncheck", true);
      break;  
  }

  C.gridOrgStatistics.RefreshButtons();
}

function gridOrgStatistics_BeforeCellUpdate(e) {
  var item = mRecord.OrganisationStatistics[e.row.listIndex];
  
  switch(e.columnKey) {
    case "Description":
      item.Description = e.newValue;
      break;
      
    case "FrequencyPerAnnum":
      item.FrequencyPerAnnum = e.newValue;
      break;
      
    case "Value":
      item.Value = e.newValue;
      break;
  }
}

// ===============
// Add a Statistic
// ===============
function StatisticAdd(individual) {
  // Create Modal
  mForm_StatisticAdd = widget.UI.Modal({
    title: "Add Default Statistic",
    height: 300,
    width: 500,

    onAction: StatisticAdd_Action,
  });
  mForm_StatisticAdd.individual = individual;
  
  // Actions
  mForm_StatisticAdd.Actions().Define([{ groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
                                       { groupId: "[buttons]", actionId: "Ok", caption: "Add Statistic" }, ]);

  // Clear Fields
  C.cboStatisticClass.Text("");
  C.cboStatisticTypeId.Text("");
  C.txtStatisticDescription.Text("");
  C.cboStatisticFrequency.Text("");
  C.cboStatisticFrequency.VisibleRow(false);
  C.numStatisticValue.Value(0);

  // Clear Flags
  mStatisticTypeListFiltered = null;

  // Update Controls
  var useStatisticsControlValue = null;
  var useStatisticsControlText = null;
  if (individual) {
    useStatisticsControlText = C.cboIndUseStatistics.Text();
  }
  else {
    useStatisticsControlText = C.cboOrgUseStatistics.Text();
  }
  
  // Update Lists depending on "Use Statistics" settings
  for (var i = 0; i &lt; mRecord.ClientGroupUseStatisticsList.length; i++) {
    var item = mRecord.ClientGroupUseStatisticsList[i];
    
    if (item.Description == useStatisticsControlText) {
      useStatisticsControlValue = item.Code;
      break;
    }
  }

  var statisticClassList = mRecord.StatisticClassList;  
  if (useStatisticsControlValue) {
    switch (useStatisticsControlValue) {
      case "IncomeExpenses":
        statisticClassList = "Income,Expense";
        
        mStatisticTypeListFiltered = [];
        for (var i = 0; i &lt; mRecord.StatisticTypes.length; i++) {
          var item = mRecord.StatisticTypes[i];
          
          if (item.StatisticClass == "Income" || item.StatisticClass == "Expense") {
            mStatisticTypeListFiltered.push(item);
          }
        }
        break;
      
      case "AssetsLiabilities":
        statisticClassList = "Asset,Liability";
        
        mStatisticTypeListFiltered = [];
        for (var i = 0; i &lt; mRecord.StatisticTypes.length; i++) {
          var item = mRecord.StatisticTypes[i];
          
          if (item.StatisticClass == "Asset" || item.StatisticClass == "Liability") {
            mStatisticTypeListFiltered.push(item);
          }
        }
        break;
    }
  }

  // Fallback
  if (!mStatisticTypeListFiltered) mStatisticTypeListFiltered = mRecord.StatisticTypes

  // Refresh Lists
  UpdateStatisticTypeList(); 
  C.cboStatisticClass.ListFromCsvString(statisticClassList);  
  C.cboStatisticFrequency.ListFromCsvString(mRecord.FrequencyPerAnnumList);

  // Show
  mForm_StatisticAdd.Show({contentSourceElement: "frmStatisticAdd"});

  // Focus
  C.cboStatisticClass.Focus();
  
  // Change Events
  cboStatisticTypeId_Change();
}

// Handle Actions
function StatisticAdd_Action(actionId) {
  switch(actionId) {
    case "Cancel":
      mForm_StatisticAdd.Close();
      break;

   case "Ok":
      StatisticAdd_Action_Ok();
      break;

    default:
      window.alert(actionId);
  }
}

function StatisticAdd_Action_Ok() {
  var o = {
    Description: C.txtStatisticDescription.Text(),
    OrigIndex: -1,
    StatisticClass: C.cboStatisticClass.Text(),
    StatisticTypeId: C.cboStatisticTypeId.Text(),
    FrequencyPerAnnum: "",
    Value: C.numStatisticValue.Value(),
  };
  
  var statisticType = mRecord.StatisticTypes.GetItem(C.cboStatisticTypeId.Text());
  if (statisticType &amp;&amp; statisticType.CanUpdateFrequencyPerAnnum) {
    o.FrequencyPerAnnum = C.cboStatisticFrequency.Text();
  }
  
  // Validate
  var Ok = true;
  if (!C.cboStatisticClass.Text()) {
    Ok = false;
    C.cboStatisticClass.Focus();
  }
  else if (!statisticType) {
    Ok = false;
    C.cboStatisticTypeId.Focus();
  }
  else if (statisticType.CanUpdateFrequencyPerAnnum &amp;&amp; !C.cboStatisticFrequency.Text()) {
    Ok = false;
    C.cboStatisticFrequency.Focus();
  }
  
  // Add item
  if (Ok) {
    if (mForm_StatisticAdd.individual) {
      StatisticAdd_Action_Ok_Insert(mRecord.IndividualStatistics, o);
      
      // Refresh Grid
      C.gridIndStatistics.VirtualDataRefresh(mRecord.IndividualStatistics);
    }
    else {
      mRecord.OrganisationStatistics.push(o);
      
      // Refresh Grid
      C.gridOrgStatistics.VirtualDataRefresh(mRecord.OrganisationStatistics);
    }
    
    // Close Modal
    mForm_StatisticAdd.Close();
  }
}

// Add the new Statistic into the collection - ensure it is inserted after the last item of the same Statistic Class
function StatisticAdd_Action_Ok_Insert(collection, item) {
  var found = false;

  for (i = collection.length - 1; i &gt;= 0; i--) {
    var item2 = collection[i];
    
    if (item2.StatisticClass == item.StatisticClass) {
      found = true;
      collection.splice(i + 1, 0, item);
      break;
    }
  }
  
  // Existing Class not found? Add to end
  if (!found) collection.push(item);
}

// =============
// gridDocuments
// =============
function gridDocuments_Refresh() {
  // Add Columns
  C.gridDocuments.ClearColumns();
  C.gridDocuments.AddColumnString("Category", { caption: "Category", visible: false, });
  C.gridDocuments.AddColumnBoolean("Available", { caption: "Available", allowEdit: !mRecord.ReadOnly });
  C.gridDocuments.AddColumnBoolean("Active", { caption: "Active" });
  C.gridDocuments.AddColumnCode("DocumentId", { caption: "Document" });
  C.gridDocuments.AddColumnString("Description", { caption: "Description" });

  // Actions
  if (!mRecord.ReadOnly) {
    C.gridDocuments.Actions().Define([{ actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                      { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                      { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                      { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },
                                      { actionId: "SelectGroup", tooltipText:"Select all rows in the current Group", icon: "Select_Same" },
                                      {},
                                      { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                      { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
                                     ]);
  }

  // Refresh
  C.gridDocuments.VirtualDataRefresh(mRecord.Documents);

  // Activate First Row
  C.gridDocuments.ActivateFirstDataRow();
}

function gridDocuments_InitialiseRow(e) {
  var item = mRecord.Documents[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  if (!item.Category) e.row.cells.Category.value = "(no category)";
  
  // Styling
  
  // Read Only
  e.row.cells.Active.readOnly = true;
  e.row.cells.DocumentId.readOnly = true;
  e.row.cells.Description.readOnly = true;
  
  // Hyperlinks
  e.row.cells.DocumentId.hyperlink = "app://FormShow?form=Documents&amp;id=" + widget.UI.HtmlEncode(item.DocumentId);
}

function gridDocuments_Action(actionId) {
  switch (actionId.toUpperCase()) {      
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridDocuments.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord.Documents.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);
        }
      }
      C.gridDocuments.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord.Documents.length; i++) {
        indexes.push(i);
      }
      C.gridDocuments.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTNONE":
      C.gridDocuments.SetSelectedRowIndexes([], true);
      break;
      
    case "SELECTGROUP":
      var i = C.gridDocuments.ActiveDataRowListIndex();
      
      if (i != -1) {
        var item = mRecord.Documents[i];        
        var indexes = [];
        
        for(var j = 0; j &lt; mRecord.Documents.length; j++) {        
          var item2 = mRecord.Documents[j];
          
          if (item2.Category == item.Category) indexes.push(j);
        }          
        C.gridDocuments.SetSelectedRowIndexes(indexes, true);
      }
      break;  
      
    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridDocuments.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mRecord.Documents[selectedItems[i]];
        item.Available = (actionId.toUpperCase() == "CHECK")
      }
      C.gridDocuments.VirtualDataRefresh(mRecord.Documents, true, { retainSelectedRows: true });
      break;
  }
  
  // Refresh buttons
  gridDocuments_RefreshButtons();
}

function gridDocuments_AfterRowActivate(e) {
  // Refresh Buttons
  gridDocuments_RefreshButtons();
}

function gridDocuments_SelectedRowsChanged(e) {
  // Refresh Buttons
  gridDocuments_RefreshButtons();
}

function gridDocuments_RefreshButtons() {
  var rows = C.gridDocuments.GetSelectedRowIndexes(true, true);

  // Reset
  C.gridDocuments.Actions().SetEnabled("SelectUp", rows.length != 0);
  C.gridDocuments.Actions().SetEnabled("SelectDown", rows.length != 0);
  C.gridDocuments.Actions().SetEnabled("SelectGroup", rows.length != 0);
  C.gridDocuments.Actions().SetEnabled("Check", rows.length != 0);
  C.gridDocuments.Actions().SetEnabled("Uncheck", rows.length != 0);

  C.gridDocuments.RefreshButtons();
}

function gridDocuments_BeforeCellUpdate(e) {
  var item = mRecord.Documents[e.row.listIndex];
  
  switch(e.columnKey) {
    case "Available":
      item.Available = e.newValue;
      break;
  }
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId) {
     case "FormClose":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabDetails_Cancel();
      break;
   }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>wTAyxOcWk0izLN86NxXONg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Client Group</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</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>ClientGroup</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="HideOtherPages" type="Boolean">
            <BlankTip />
            <Caption>Hide pages other than the one being edited?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Configuration options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <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="ClientGroupId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>ClientGroups</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="DuplicateRecordId" 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="Page" 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>General,NewClientWizard,StatisticsIndividual,StatisticsOrganisation,Identification,Documents,ParameterSets,UserDefined</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>