<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-02-09T01:56:15.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2020-11-06T00:42:00.5970000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2024-02-09T01:56:01.4540000</UpdatedUtcDate>
    <ScriptId>WCSS</ScriptId>
    <Description>Client Statistics Set</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ClientStatisticsSet
Option Explicit On
Option Strict On

' #################################################################
' Client Statistics Set wizard HTML Widget
'
' Version: 1.04 (09/02/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.03  20/03/2023  ISS      J030712   Visual glitch when first loaded
'    1.04  09/02/2024  ISS      J032887   Added ability to default from last approved set
' #################################################################

' Constants
Private Const FORM_KEY As String = "ClientStatisticsSet"

' Common Parameters
Private mClientId As String
Private mClientStatisticsSetPk As Integer
Private mClientStatisticsSetJson As String
Private mDefaultFromLastApproved As Boolean
Private mEditJson As Boolean
Private mReadOnly As Boolean

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

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

  ' Assume Success
  Main = True

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

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

  ' Get Common Parameters
  With mCombinedParameters
    mClientId = .GetString("ClientId")
    mClientStatisticsSetPk = .GetInteger("ClientStatisticsSetPk")
    mClientStatisticsSetJson = .GetString("ClientStatisticsSetJson")
    mDefaultFromLastApproved = .GetBoolean("DefaultFromLastApproved")
    mEditJson = .GetBoolean("EditJson")    
    mReadOnly = .GetBoolean("ReadOnly")
  End With

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

    Case "Delete"
      ' Delete Client Statistics Set
      Main = Delete(returnValue)

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

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

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

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

End Function

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

  Dim ClientGroupId As String
  Dim ClientTypeId As String
  Dim kvl As ISKeyValueList
  Dim StatisticsFixed As Boolean
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  client = finBL.CreateClient()
  clientStatisticsSet = Nothing

  ' Load Client
  If Success Then
    If mEditJson Then
      ' From New Client wizard
    Else
      Success = client.Load(mClientId)
    End If
  End If

  ' Get Statistics Set
  If Success Then
    If mEditJson Then
      ' From New Client wizard
      clientStatisticsSet = client.StatisticsSets.CreateClientStatisticsSet()

      If Len(mClientStatisticsSetJson) &lt;&gt; 0 Then
        ' Client Group and Client Type are contained in the JSON representation to assist this wizard
        clientStatisticsSet.FromHtmlWidgetJsonString(mClientStatisticsSetJson)
        
        ' Set on Client
        If client.IsNew Then
          kvl = finBL.CreateKeyValueList()
          With kvl
            .FromSimpleJsonString(mClientStatisticsSetJson)
            ClientGroupId = .GetString("ClientGroupId")
            ClientTypeId = .GetString("ClientTypeId")
          End With
          
          If Len(ClientGroupId) &lt;&gt; 0 Then client.ClientGroupIdSet(ClientGroupId)
          If Len(ClientTypeId) &lt;&gt; 0 Then client.ClientTypeIdSet(ClientTypeId)
        End If
      End If
    Else
      ' Find Client Statistics Set
      If mClientStatisticsSetPk = -1 Then
        clientStatisticsSet = client.StatisticsSets.CreateClientStatisticsSet()
        
        If mDefaultFromLastApproved AndAlso finBL.CurrentUser.Permissions.Allow("Client.StatisticsSets.DefaultExisting") AndAlso client.StatisticsSets.LastApprovedIndex &lt;&gt; -1 Then
          ' Default from the last approved set
          clientStatisticsSet = client.StatisticsSets.CreateClientStatisticsSet()
          If clientStatisticsSet.DefaultFromStatisticsSet(clientStatisticsSet.Parent(clientStatisticsSet.Parent.LastApprovedIndex), client.ClientGroupId, client.IsIndividual, StatisticsFixed, warnings) Then
            If Len(warnings) &lt;&gt; 0 Then
              If StatisticsFixed Then
                warnings = "Client Statistics were defaulted from the most recent 'Approved' set but, due to this Client's Client Group indicating that Statistics should be fixed, the following warnings were given:" &amp; vbNewLine &amp; vbNewLine &amp; Warnings
              Else
                warnings = "Client Statistics were defaulted from the most recent 'Approved' set but, due to this Client's Client Group indicating that Statistics should only include Income and Expense type statistics, the following warnings were given:" &amp; vbNewLine &amp; vbNewLine &amp; Warnings
              End If
            End If
          Else
            Success = False
          End If
        Else
          ' Default from Client Group
          Success = clientStatisticsSet.DefaultFromClientGroup(client.ClientGroupId, client.IsIndividual)
        End If

        ' Other Defaults
        If Success Then
          If client.IsIndividual Then
            clientStatisticsSet.DateExpiry = finBL.Utilities.DateCycleGetTermEndDate(client.ClientGroup.IndividualStatisticsExpiryCycle, clientStatisticsSet.DateStart)
          Else
            clientStatisticsSet.DateExpiry = finBL.Utilities.DateCycleGetTermEndDate(client.ClientGroup.OrganisationStatisticsExpiryCycle, clientStatisticsSet.DateStart)
          End If
        End If

        ' Add in any Loans/ Deposits etc
        If Success Then
          Success = client.StatisticsRefresh(clientStatisticsSet)
        End If
      ElseIf client.StatisticsSets.ExistsPk(mClientStatisticsSetPk) Then
        clientStatisticsSet = client.StatisticsSets.ItemByPk(mClientStatisticsSetPk)
      Else
        Success = False
        finBL.Error.ErrorBeginFormat("Invalid Client Statistics Set Pk {0}.", mClientStatisticsSetPk)
      End If
    End If
  End If

  ' Update Client Statistics Set
  If Success AndAlso parameters IsNot Nothing Then
    Success = clientStatisticsSet.FromHtmlWidgetJsonString(parameters.ClientStatisticsSetJson)
  End If

  Return Success

End Function

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

  Dim Client As finClient
  Dim ClientStatisticsSet As finClientStatisticsSet
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Create Client and Client Statistics Set objects
  If Success Then
    Success = CreateClientStatisticsSet(WizardFinishParameters, Client, ClientStatisticsSet, "")
  End If

  ' Delete and Save
  If Success Then
    ' Remove from collection
    Success = Client.StatisticsSets.Remove(ClientStatisticsSet)

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

  Return Success

End Function

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

  Dim Client As finClient
  Dim ClientStatisticsSet As finClientStatisticsSet
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Client and Client Statistics Set objects
  If Success Then
    Success = CreateClientStatisticsSet(WizardFinishParameters, Client, ClientStatisticsSet, "")
  End If

  ' If a new Client Statistics Set add to collection
  If Success AndAlso mClientStatisticsSetPk = -1 AndAlso Not mEditJson Then
    Client.StatisticsSets.Add(ClientStatisticsSet)
  End If

  ' Save
  If Success AndAlso Not mEditJson Then
    Success = Client.Save()
  End If

  ' Finalise
  If Success Then
    If mEditJson Then
      ' Tidy up invalid default properties
      ClientStatisticsSet.FromHtmlWidgetJsonString(ClientStatisticsSet.ToHtmlWidgetJsonString())

      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(ClientStatisticsSet.ToHtmlWidgetJsonString()), returnValue)
    Else
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(""), returnValue)
    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 Client As finClient
  Dim ClientStatisticsSet As finClientStatisticsSet
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim s As String
  Dim StatisticType As finStatisticTypeRO
  Dim Success As Boolean
  Dim Warnings As String

  ' Assume Success
  Success = True

  ' Validate
  If mEditJson Then
    ' Editing from New Account wizard
  ElseIf Len(mClientId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Client Id not specified.")
  ElseIf mClientStatisticsSetPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Client Statistics Set Pk not specified.")
  ElseIf Not finBL.Settings.AddOns.ClientStatistics Then
    Success = False
    finBL.Error.ErrorBegin("You are not licensed for the Client Statistics Add-On.")
  ElseIf finBL.CurrentUserInformation.IsClientFilteredOut(mClientId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Client.")
  End If

  ' Create Client and Client Statistics Set objects
  If Success Then
    Success = CreateClientStatisticsSet(Nothing, Client, ClientStatisticsSet, Warnings)
  End If

  ' Validate Client
  If Success Then
    If mClientStatisticsSetPk = -1 AndAlso Client.StatisticsSets.HasOpen Then
      Success = False
      finBL.Error.ErrorBegin("This Client already has an 'Open' Statistics Set which must be either 'Approved' or 'Rejected' before a new set can be created.")
    End If
  End If

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

      ' Make Read-Only if no permission to update
      If Not .ReadOnly Then
        .ReadOnly = ClientStatisticsSet.IsApprovedOrRejected OrElse ClientStatisticsSet.IsVerified OrElse ClientStatisticsSet.Status &lt;&gt; isefinClientStatisticStatus.Open
      End If

      ' Record
      .IsNew = ClientStatisticsSet.IsNew
      .Timestamp = ClientStatisticsSet.Timestamp
      
      ' Warnings (if defaulting from the last approved set)
      .Warnings = Warnings

      ' Client
      .ClientId = Client.ClientId
      .ClientName = Client.Name

      ' Client Statistics Set
      .ClientStatisticsSet = ClientStatisticsSet.ToHtmlWidgetJsonObject()

      ' Lists
      .FrequencyPerAnnumList = finBL.Enums.isefinFrequencyPerAnnum_GetList(False).ToCsvString()

      ' Global Collections
      For Each StatisticType In finBL.StatisticTypes
        .StatisticTypes.Add(New StatisticTypeInfo(StatisticType))
      Next

      ' Other
      .ClientGroup = New ClientGroupInfo(client, ClientStatisticsSet)
      For Each s In finBL.Enums.isefinFrequencyPerAnnum_GetList()
        .Frequencies.Add(New With { .Text = s, .Value = finBL.Enums.isefinFrequencyPerAnnum_FromStringToInt(s) })
      Next

      ' Advanced Sections
      .ShowGeneralOther = mCombinedParameters.GetString("ShowGeneralOther") : If Len(.ShowGeneralOther) = 0 Then .ShowGeneralOther = "Advanced"
      .ShowCategory = finBL.InformationLists("StatisticsSetCategory").Pk &lt;&gt; 0 ' Don't show category if the Information List has not been configured in any way
      .ShowStatisticComments = mCombinedParameters.GetString("ShowStatisticComments") : If Len(.ShowStatisticComments) = 0 Then .ShowStatisticComments = "Advanced"
      .ShowStatisticTypeId = mCombinedParameters.GetString("ShowStatisticTypeId") : If Len(.ShowStatisticTypeId) = 0 Then .ShowStatisticTypeId = "Advanced"
      .PageGeneralHasAdvanced = (.ShowGeneralOther = "Advanced")

      ' Configuration
      If finBL.Database.IsReadOnly OrElse mReadOnly Then
        .CanDelete = False
      ElseIf mEditJson Then
        ' From New Client wizard
        .CanDelete = False
      ElseIf .IsNew Then
        .CanDelete = False
      Else
        If ClientStatisticsSet.IsApproved Then
          .CanDelete = finBL.CurrentUser.Permissions.Allow("Client.StatisticsSets.DeleteApproved")
        ElseIf ClientStatisticsSet.IsVerified Then
          .CanDelete = finBL.CurrentUser.Permissions.Allow("Client.StatisticsSets.DeleteVerified")
        Else
          .CanDelete = finBL.CurrentUser.Permissions.Allow("Client.StatisticsSets.Delete")
        End If
      End If
      .EditJson = mEditJson
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .StatisticsDisplayFrequency = CInt(finBL.Settings.ClientStatisticsDisplayFrequency)
      .StatisticsDisplayFrequencyText = finBL.Settings.ClientStatisticsDisplayFrequencyText

      ' If Statistics Set is not fixed, we cannot completely hide Statistic Type since adding new items means we need to be able to select it
      If .ShowStatisticTypeId = "False" AndAlso Not .ReadOnly AndAlso Not .ClientGroup.StatisticsFixed Then .ShowStatisticTypeId = "Advanced"
    End With
  End If

  ' Further Validations
  If Success Then
    If FormInitialisationInfo.ReadOnly AndAlso mClientStatisticsSetPk = -1 AndAlso Not mEditJson Then
      Success = False
      finBL.Error.ErrorBegin("Cannot add a new Standard Transaction whilst form is Read-Only.")
    End If
  End If

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

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

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

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

  Return Success

End Function

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

  Dim Client As finClient
  Dim ClientStatisticsSet As finClientStatisticsSet
  Dim obj As Object
  Dim Record As WizardFinishParameters
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

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

  ' Create Client and Client Statistics Set objects
  If Success Then
    Success = CreateClientStatisticsSet(Record, Client, ClientStatisticsSet, "")
  End If

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

  Return Success

End Function



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

  ' Record
  Public IsNew As Boolean
  Public Timestamp As Integer
  
  ' Warnings
  Public Warnings As String

  ' Client Properties
  Public ClientId As String
  Public ClientName As String

  ' Client Statistics Set
  Public ClientStatisticsSet As finClientStatisticsSet.jsonHtmlWidgetClientStatisticsSet

  ' Lists
  Public FrequencyPerAnnumList As String

  ' Global Collections
  Public StatisticTypes As New List(Of StatisticTypeInfo)

  ' Other
  Public ClientGroup As ClientGroupInfo
  Public Frequencies As New List(Of Object)

  ' Advanced Sections
  Public ShowGeneralOther As String
  Public ShowCategory As Boolean
  Public ShowStatisticComments As String
  Public ShowStatisticTypeId As String
  Public PageGeneralHasAdvanced As Boolean

  ' Configuration
  Public CanDelete As Boolean
  Public EditJson As Boolean
  Public PromptOnSave As Boolean
  Public [ReadOnly] As Boolean
  Public StatisticsDisplayFrequency As Integer
  Public StatisticsDisplayFrequencyText As String

End Class

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

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

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

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

  End Sub

End Class

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

  Public ClientStatisticsSetJson As String
  Public Timestamp As Integer

End Class

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

  Public ClientStatisticsSetJson As String
  Public Warning As String

  Public Sub New(clientStatisticsSetJson As String)

    Me.ClientStatisticsSetJson = clientStatisticsSetJson

  End Sub

End Class


''' &lt;summary&gt;
'''  Information about this Client's Client Group (Statistics related information only).
''' &lt;/summary&gt;
Public Class ClientGroupInfo

  Public AvailableAssetsPercent As Double
  Public AvailableIncomePercent As Double
  Public ShowIncome As Boolean
  Public ShowExpenses As Boolean
  Public ShowAssets As Boolean
  Public ShowLiabilities As Boolean
  Public StatisticsFixed As Boolean

  Public Sub New(client As finClient,
                 clientStatisticsSet As finClientStatisticsSet)

    With client.ClientGroup
      If client.IsIndividual Then
        ' Individual
        Me.AvailableAssetsPercent = .IndividualAvailableAssetsPercent
        Me.AvailableIncomePercent = .IndividualAvailableIncomePercent
        Me.StatisticsFixed = .IndividualStatisticsFixed

        Select Case .IndividualUseStatistics
          Case isefinClientGroupUseStatistics.AssetsLiabilities
            Me.ShowAssets = True
            Me.ShowLiabilities = True

          Case isefinClientGroupUseStatistics.IncomeExpenses
            Me.ShowIncome = True
            Me.ShowExpenses = True

          Case isefinClientGroupUseStatistics.Yes
            Me.ShowIncome = True
            Me.ShowExpenses = True
            Me.ShowAssets = True
            Me.ShowLiabilities = True
        End Select
      Else
        ' Organisation
        Me.AvailableAssetsPercent = .OrganisationAvailableAssetsPercent
        Me.AvailableIncomePercent = .OrganisationAvailableIncomePercent
        Me.StatisticsFixed = .OrganisationStatisticsFixed

        Select Case .OrganisationUseStatistics
          Case isefinClientGroupUseStatistics.AssetsLiabilities
            Me.ShowAssets = True
            Me.ShowLiabilities = True

          Case isefinClientGroupUseStatistics.IncomeExpenses
            Me.ShowIncome = True
            Me.ShowExpenses = True

          Case isefinClientGroupUseStatistics.Yes
            Me.ShowIncome = True
            Me.ShowExpenses = True
            Me.ShowAssets = True
            Me.ShowLiabilities = True
        End Select
      End If
    End With

    ' For Fixed Statistics, we can hide blocks if no items defined
    If Me.StatisticsFixed AndAlso Me.ShowIncome AndAlso Me.ShowExpenses AndAlso Me.ShowAssets AndAlso Me.ShowLiabilities Then
      If clientStatisticsSet.Income.Count = 0 Then Me.ShowIncome = False
      If clientStatisticsSet.Expenses.Count = 0 Then Me.ShowExpenses = False
      If clientStatisticsSet.Assets.Count = 0 Then Me.ShowAssets = False
      If clientStatisticsSet.Liabilities.Count = 0 Then Me.ShowLiabilities = False
    End If

  End Sub

End Class


''' &lt;summary&gt;
'''  Simple information about a Statistic Type.
''' &lt;/summary&gt;
Public Class StatisticTypeInfo

  Public StatisticTypeId As String
  Public [Class] As String
  Public Description As String
  Public MinimumValue As Decimal

  Public Sub New(statisticType As finStatisticTypeRO)

    With statisticType
      Me.StatisticTypeId = .StatisticTypeId
      Me.Class = .StatisticClass.ToString()
      Me.Description = .Description
      Me.MinimumValue = .MinimumValue
    End With

  End Sub

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

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

NOTE: This has special functionality to enable it to edit a JSON item passed from a New Client wizard.

Other Information
============
* Category will never be displayed if the "StatisticsSetCategory" Information List is not configured in any way.
* For new Statistics Sets, Statistics will always be defaulted from the Client Group, not from a previously held Client Statistics Set.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
div.is-repeater {
  /* New items MUST always show Statistic Type */
  &amp;.has-new {
    div[templateid='divStatisticType'] {
      display:block !important;
    }
  }
}

div.is-repeater-item {
  &amp;:not(:last-child) {
    border-bottom:1px solid rgba(0,0,0,0.1);
  }

  &amp;:hover:not(.is-sel) {
    /* https://cssgradient.io/ */
    background: linear-gradient(0deg, rgba(240,240,240,0.6) 0%, rgba(255,255,255,0.6) 25%, rgba(255,255,255,0.6) 75%, rgba(240,240,240,0.6) 100%);
  }

  &gt; .content {
    padding:8px;
  }

  input[templateid='txtDescription'] {
    font-weight:bold;
  }

  &amp;:not(.is-sel) input:not(:focus):not(:hover),
  input.is-readonly {
    border-color:transparent !important;
    background-color:transparent !important;
  }
}

div.statistics-group {
  border-radius:4px;
  display:inline-block;
  margin:12px 8px 0 0;
  width:48%;
  max-width:600px;
  min-width:480px;

  /* Heading */
  &gt; label {
    color:white;
    display:block;
    font-weight:bold;
    font-size:18px;
    line-height:26px;
    padding:4px;

    /* Totals */
    &gt; div {
      display:inline-block;
      float:right;
      font-size:14px;
      color:rgba(255,255,255,0.9);
      line-height:26px;
    }
  }

  &amp;#divIncome, &amp;#divAssets {
    background-color:lighten(#8BC34A,40%);
    border:4px solid #8BC34A;
    &gt; label { background-color:#8BC34A; }
  }

  &amp;#divExpenses, &amp;#divLiabilities {
    background-color:lighten(#F44336,37.5%);
    border:4px solid #F44336;
    &gt; label { background-color:#F44336; }
  }
}

div.statistic {
  &gt; div:first-child {
    display:flex;
    flex-direction:row;
    align-items:stretch;

    &gt; div[templateid='divDescription'] {
      flex-grow:1;
      flex-shrink:1;
      position:relative;

      /* Account floats as tag over Description to preserve space */
      &gt; div[templateid='divAccount'] {
        background-color:#fffff0;
        border:1px solid rgba(0,0,0,0.1);
        font-size:11px;
        padding:2px;
        line-height:100%;
        position:absolute;
        top:0;
        right:0;
        text-align:right;
      }
    }

    &gt; div:not(:last-child) {
      margin-right:4px;
    }
  }

  &gt; div:last-child:not(.advanced) {
    display:inline-block;
    margin-top:4px;
    width:100%;
  }
}

div.totals {
  align-items:center;
  border-radius:4px;
  display:flex;
  font-size:14px;
  flex-flow:row wrap;
  margin-bottom:8px;
  text-align:left;
  padding:8px;

  &gt; div {
    line-height:22px;
    margin-right:24px;

    &gt; div {
      display:flex;

      &gt; label {
        flex-grow:0;
        display:inline-block;
        font-size:13px;
        margin-right:12px;
      }

      &gt; span {
        flex-grow:1;
        font-weight:bold;
        text-align:right;
      }
    }

    &amp;.stats-debt-ratio {
      &gt; div {
        display:flex;
        flex-direction:row;
        align-items:center;

        &gt; label, &gt; span {
          line-height:auto;
          vertical-align:middle;
        }

        &gt; span {
          font-size:24px;
        }
      }
    }
  }


  &amp;.warning-level-0 {
    background-color:#8BC34A;
    color:white;
  }

  &amp;.warning-level-1 {
    background-color:#FF9800;
    color:white;
  }

  &amp;.warning-level-2 {
    background-color:#F44336;
    color:white;
  }
}

#divIncomeExpenses,
#divAssetsLiabilities {
  display:flex;
  flex-direction:row;
}

/* Responsive */
@media screen and (max-width:700px) {
  body.advanced-visible {
  }

  div.statistics-group {
    display:block;
    min-width:unset !important;
    width:100% !important;
  }

  div.totals {
    display:none;
  }


}

@media screen and (max-width:1200px) {
  #divIncomeExpenses,
  #divAssetsLiabilities {
    display:block;
  }

  div.statistics-group {
    display:block;
  }
}
&lt;/style&gt;

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

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General"&gt;Client Statistics Set&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:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblDateAsAt"&gt;The 'Date As At' for these Statistics&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateDateStart"&gt;Date As At:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateDateStart" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="GeneralOther"&gt;
          &lt;th&gt;&lt;label for="dateDateExpiry"&gt;Expires:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateDateExpiry" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr id="trCategoryHeading" advancedId="GeneralOther"&gt;&lt;th colspan="2"&gt;&lt;label id="lblCategory"&gt;Category&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr id="trCategory" advancedId="GeneralOther"&gt;
          &lt;th&gt;&lt;label for="cboCategory"&gt;Category:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCategory" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

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


      &lt;div id="divIncomeExpenses"&gt;
        &lt;div id="divIncome" class="statistics-group"&gt;
          &lt;label&gt;Income&lt;div id="divTotalIncome"&gt;x&lt;/div&gt;&lt;/label&gt;
          &lt;div id="rptIncome"&gt;
            &lt;template&gt;
              &lt;div class="statistic"&gt;
                &lt;div&gt;
                  &lt;div templateid="divStatisticType"&gt;&lt;input templateid="cboStatisticType"/&gt;&lt;/div&gt;
                  &lt;div templateid="divDescription"&gt;&lt;input templateid="txtDescription"/&gt;&lt;div templateid="divAccount"&gt;&lt;/div&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input templateid="cboFrequency" /&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input templateid="numValue" /&gt;&lt;/div&gt;
                &lt;/div&gt;
                &lt;div templateid="divComments"&gt;&lt;input templateid="txtComments"/&gt;&lt;/div&gt;
               &lt;/div&gt;
            &lt;/template&gt;
          &lt;/div&gt;
        &lt;/div&gt;

        &lt;div id="divExpenses" class="statistics-group"&gt;
          &lt;label id="lblExpenses"&gt;Expenses&lt;div id="divTotalExpenses"&gt;x&lt;/div&gt;&lt;/label&gt;
          &lt;div id="rptExpenses"&gt;
            &lt;template&gt;
              &lt;div class="statistic"&gt;
                &lt;div&gt;
                  &lt;div templateid="divStatisticType"&gt;&lt;input templateid="cboStatisticType"/&gt;&lt;/div&gt;
                  &lt;div templateid="divDescription"&gt;&lt;input templateid="txtDescription"/&gt;&lt;div templateid="divAccount"&gt;&lt;/div&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input templateid="cboFrequency" /&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input templateid="numValue" /&gt;&lt;/div&gt;
                &lt;/div&gt;
                &lt;div templateid="divComments"&gt;&lt;input templateid="txtComments"/&gt;&lt;/div&gt;
               &lt;/div&gt;
            &lt;/template&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;


      &lt;div id="divAssetsLiabilities"&gt;
        &lt;div id="divAssets" class="statistics-group"&gt;
          &lt;label id="lblAssets"&gt;Assets&lt;div id="divTotalAssets"&gt;x&lt;/div&gt;&lt;/label&gt;
          &lt;div id="rptAssets"&gt;
            &lt;template&gt;
              &lt;div class="statistic"&gt;
                &lt;div&gt;
                  &lt;div templateid="divStatisticType"&gt;&lt;input templateid="cboStatisticType"/&gt;&lt;/div&gt;
                  &lt;div templateid="divDescription"&gt;&lt;input templateid="txtDescription"/&gt;&lt;div templateid="divAccount"&gt;&lt;/div&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input templateid="numValue" /&gt;&lt;/div&gt;
                &lt;/div&gt;
                &lt;div templateid="divComments"&gt;&lt;input templateid="txtComments"/&gt;&lt;/div&gt;
               &lt;/div&gt;
            &lt;/template&gt;
          &lt;/div&gt;
        &lt;/div&gt;

        &lt;div id="divLiabilities" class="statistics-group"&gt;
          &lt;label id="lblLiabilities"&gt;Liabilities&lt;div id="divTotalLiabilities"&gt;x&lt;/div&gt;&lt;/label&gt;
          &lt;div id="rptLiabilities"&gt;
            &lt;template&gt;
              &lt;div class="statistic"&gt;
                &lt;div&gt;
                  &lt;div templateid="divStatisticType"&gt;&lt;input templateid="cboStatisticType"/&gt;&lt;/div&gt;
                  &lt;div templateid="divDescription"&gt;&lt;input templateid="txtDescription"/&gt;&lt;div templateid="divAccount"&gt;&lt;/div&gt;&lt;/div&gt;
                  &lt;div&gt;&lt;input templateid="numValue" /&gt;&lt;/div&gt;
                &lt;/div&gt;
                &lt;div templateid="divComments"&gt;&lt;input templateid="txtComments"/&gt;&lt;/div&gt;
               &lt;/div&gt;
            &lt;/template&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;div id="divTotals" class="totals"&gt;&lt;/div&gt;

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

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

&lt;/div&gt;

&lt;script&gt;
// Record
var mRecord;
var mRecord_ClientGroup;
var mRecord_ClientStatisticsSet;

var mOriginalJson;

// Global Collections
var mStatisticTypes;

// Controls
var C = {
  // General
  lblDateAsAt: null,
  dateDateStart: null,
  dateDateExpiry: null,

  trCategoryHeading: null,
  lblCategory: null,
  trCategory: null,
  cboCategory: null,

  lblNotes: null,
  txtNotes: null,

  rptIncome: null,
  divTotalIncome: null,

  rptExpenses: null,
  divTotalExpenses: null,

  rptAssets: null,
  divTotalAssets: null,

  rptLiabilities: null,
  divTotalLiabilities: null,

  // Footer
  divTotals: null,
}

// Form
var frmMain;
var tabWizard;

// Other
var mValueData;

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

var cmdAdvanced;

// Other
var mAdvancedVisible = false;

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

  // --------
  // Controls
  // --------
  //   General
  C.lblDateAsAt = widget.UI.Label("lblDateAsAt", {});
  C.dateDateStart = widget.UI.DateBox("dateDateStart", {
    allowBlank: false,
  });
  C.dateDateExpiry = widget.UI.DateBox("dateDateExpiry", {});

  C.trCategoryHeading = $("#trCategoryHeading");
  C.lblCategory = widget.UI.Label("lblCategory", {});
  C.trCategory = $("#trCategory");
  C.cboCategory = widget.UI.InformationListComboBox("cboCategory", {
    maxLength: 50,
  });

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

  C.divTotalIncome = $("#divTotalIncome");
  C.rptIncome = widget.UI.Repeater("rptIncome", {
    onAction: rptStatistics_Action,
    onAfterRowActivate: rptStatistics_AfterRowActivate,
    onInitialiseRow: function (sender, e) { rptStatistics_InitialiseRow(sender, e, 0); },
    onRowAdd: rptStatistics_RowAdd,
  });

  C.divTotalExpenses = $("#divTotalExpenses");
  C.rptExpenses = widget.UI.Repeater("rptExpenses", {
    onAction: rptStatistics_Action,
    onAfterRowActivate: rptStatistics_AfterRowActivate,
onInitialiseRow: function (sender, e) { rptStatistics_InitialiseRow(sender, e, 1); },
    onRowAdd: rptStatistics_RowAdd,
  });

  C.divTotalAssets = $("#divTotalAssets");
  C.rptAssets = widget.UI.Repeater("rptAssets", {
    onAction: rptStatistics_Action,
    onAfterRowActivate: rptStatistics_AfterRowActivate,
    onInitialiseRow: function (sender, e) { rptStatistics_InitialiseRow(sender, e, 2); },
    onRowAdd: rptStatistics_RowAdd,
  });

  C.divTotalLiabilities = $("#divTotalLiabilities");
  C.rptLiabilities = widget.UI.Repeater("rptLiabilities", {
    onAction: rptStatistics_Action,
    onAfterRowActivate: rptStatistics_AfterRowActivate,
    onInitialiseRow: function (sender, e) { rptStatistics_InitialiseRow(sender, e, 3); },
    onRowAdd: rptStatistics_RowAdd,
  });

  //   Footer
  C.divTotals = $("#divTotals");

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

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

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

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

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

  // Reset
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

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

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

      // Global Collections
      mStatisticTypes = mRecord.StatisticTypes;

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

      // Load Fields
      Fields_Load();

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

      // Define Actions
      var actions = [];
      if (mRecord.CanDelete) actions.push({ groupId: "Record", actionId: "Delete", caption: "Delete", icon: "Delete" });
      frmMain.ActionsDefine(actions, "cmdActions", Form_ExecuteAction);
      
      // Warnings (if defaulting from the last approved set)?
      if (mRecord.Warnings) {
        widget.UI.MsgBoxAlert(mRecord.Warnings);
      }
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.dateDateStart.Value(mRecord_ClientStatisticsSet.DateStart);
    C.dateDateExpiry.Value(mRecord_ClientStatisticsSet.DateExpiry);

    C.cboCategory.Text(mRecord_ClientStatisticsSet.Category);

    C.txtNotes.Text(mRecord_ClientStatisticsSet.Notes);
    C.rptIncome.VirtualDataRefresh(mRecord_ClientStatisticsSet.Income);
    C.rptExpenses.VirtualDataRefresh(mRecord_ClientStatisticsSet.Expenses);
    C.rptAssets.VirtualDataRefresh(mRecord_ClientStatisticsSet.Assets);
    C.rptLiabilities.VirtualDataRefresh(mRecord_ClientStatisticsSet.Liabilities);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord_ClientStatisticsSet.DateStart = C.dateDateStart.Value();
  mRecord_ClientStatisticsSet.DateExpiry = C.dateDateExpiry.Value();

  mRecord_ClientStatisticsSet.Category = C.cboCategory.Text();

  mRecord_ClientStatisticsSet.Notes = C.txtNotes.Text();
}

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

  // Information Lists
  C.cboCategory.SetComboFromInformationList("StatisticsSetCategory", true);

  // Lists
  if (mRecord) {
    //C.cboElement.RefreshFromStandardRange("Elements", mRecord.ElementFilter);

    //C.cboCycle.ListFromCsvString(mRecord.CycleList);
  }

  // Controls
  if (mRecord) {
    // Initialise Advanced
    AdvancedInitialise();

    // Repeaters
    if (!mRecord.ReadOnly &amp;&amp; !mRecord_ClientGroup.StatisticsFixed) {
      var actions = [];

      actions.push({ actionId: "AddRow", tooltipText: "Add row", icon: "Add" });
      actions.push({});
      actions.push({ actionId: "DeleteRow", tooltipText: "Remove row", icon: "Delete" });
      actions.push({});
      actions.push({ actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" });
      actions.push({ actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });

      C.rptIncome.Actions().Define(actions);
      rptStatistics_RefreshButtons(C.rptIncome);
      C.rptExpenses.Actions().Define(actions);
      rptStatistics_RefreshButtons(C.rptExpenses);
      C.rptAssets.Actions().Define(actions);
      rptStatistics_RefreshButtons(C.rptAssets);
      C.rptLiabilities.Actions().Define(actions);
      rptStatistics_RefreshButtons(C.rptLiabilities);
    }

    // Hide sections not used
    if (!mRecord_ClientGroup.ShowIncome) $("#divIncome").hide();
    if (!mRecord_ClientGroup.ShowExpenses) $("#divExpenses").hide();
    if (!mRecord_ClientGroup.ShowAssets) $("#divAssets").hide();
    if (!mRecord_ClientGroup.ShowLiabilities) $("#divLiabilities").hide();

    // Totals
    divTotals_Refresh();

    // Refresh
    pageGeneral_Refresh();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

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

  // Set default Advanced headings
  AdvancedToggle_General();

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

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

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

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

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

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

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.cboCategory.WidthResizeFromParent();
      //C.txtNotes.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

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

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

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

      default:
        break;
    }
  }

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

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "General":
      var summary = "";
      var heading = "Client Statistics";
      if (mRecord.IsNew) {
        if (mRecord_ClientStatisticsSet) heading += " (New)";
      }
      else {
        if (mRecord_ClientStatisticsSet) heading += " (" + mRecord_ClientStatisticsSet.StatusText + ")";
      }
      if (!mRecord || mRecord.EditJson || !mRecord.ClientId) {
        summary = "Enter Client Statistics.";
      }
      else {
        if (mRecord.ReadOnly) {
          summary = "Review ";
        }
        else {
          summary = "Enter ";
        }
        summary += " Client Statistics for Client '" + mRecord.ClientId + "', " + mRecord.ClientName + ".";
      }
      frmMain.RefreshHeading(heading, summary);
      break;

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

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

  // Resize Wizard
  tabWizard_Resize();

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

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

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

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

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

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

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

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

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

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

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

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

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

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "DELETE":
      Form_ExecuteAction_Delete();
      break;

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

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

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

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

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

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

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

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

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

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

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

  // Create Parameters
  var params = CreateFinishParameters();

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

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

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

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

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

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

function Form_ExecuteAction_FinishPost_Finalise(data) {
  // Not really saving, just passing details back to parent form
  // NOTE: The reason we went through the whole save process was to validate and update details such as totals on the object
  if (mRecord.EditJson) {
    // Notify parent (e.g., New Client wizard) that a new Client Statistics Set has been created or an item edited
    // NOTE: This is essential if this wizard needs to be run from a New Client wizard
    widget.ParentNotify("RecordUpdated", data.ClientStatisticsSetJson);

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

  // Close Form
  widget.Close();

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

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

function CreateFinishParameters() {
  // Save Fields
  Fields_Save();

  return { ClientStatisticsSetJson: JSON.stringify(mRecord_ClientStatisticsSet), Timestamp: mRecord.Timestamp };
}

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

  if (mRecord) {
    //C.lblPaymentMethod.VisibleRow(mRecord.IsPaymentElement);
    //C.pdaPaymentDetails.Visible(mRecord.IsPaymentElement);
  }
//
//  // Advanced Button visible?
//  if (mRecord &amp;&amp; !mHasAdvancedOptions) {
//    // Hide button
//    cmdAdvanced.hide();
//
//    // Remove advanced section styling for everything
//    $("tr").removeClass("advanced");
//  }
//  else if (mAdvancedVisible) {
//    // Showing
//    $("body").addClass("advanced-visible");
//    cmdAdvanced.attr("showing", true);
//  }
//  else {
//    // Not showing
//    $("body").removeClass("advanced-visible");
//    cmdAdvanced.attr("showing", false);
//  }
}

// =================
// Advanced handling
// =================
function AdvancedInitialise() {
  // Tweaks
  if (!mRecord.ShowCategory) {
    C.trCategoryHeading.attr("advancedId", "");
    C.trCategory.attr("advancedId", "");
    C.trCategoryHeading.hide();
    C.trCategory.hide();
  }
//  // Reset heading classes
//  $("#trClientTypeGroup").removeClass("advanced");
//  $("#trBranchManager").removeClass("advanced");
//
////  // General Other
//  if (mRecord.ShowGeneralOther.toUpperCase() == "ADVANCED") {
//    $("#trClientTypeGroup").addClass("advanced");
//  }
//  else if (mRecord.ShowClientGroup.toUpperCase() == "ADVANCED" &amp;&amp; (mRecord.ShowClientType.toUpperCase() == "ADVANCED" || mRecord.ShowClientType.toUpperCase() == "FALSE")) {
//    $("#trClientTypeGroup").addClass("advanced");
//  }
//
//  // Branch and Client Manager
//  if (mRecord.ShowBranch.toUpperCase() == "ADVANCED" &amp;&amp; (mRecord.ShowManager.toUpperCase() == "ADVANCED" || mRecord.ShowManager.toUpperCase() == "FALSE")) {
//    $("#trBranchManager").addClass("advanced");
//  }
//  else if (mRecord.ShowManager.toUpperCase() == "ADVANCED" &amp;&amp; (mRecord.ShowBranch.toUpperCase() == "ADVANCED" || mRecord.ShowBranch.toUpperCase() == "FALSE")) {
//    $("#trBranchManager").addClass("advanced");
//  }
//
  // General
  AdvancedInitialiseSection("GeneralOther", mRecord.ShowGeneralOther);
//  AdvancedInitialiseSection("ClientGroup", mRecord.ShowClientGroup);
}

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

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

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

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

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

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

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

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

function AdvancedToggle_General() {
  // General Other
  if (C.dateDateExpiry.VisibleRow()) {
    C.lblDateAsAt.Text("Enter the 'As At' and Expiry dates for these Statistics");
  }
  else {
    C.lblDateAsAt.Text("Enter the 'As At' date for these Statistics");
  }
}

// =============
// rptStatistics
// =============
function rptStatistics_InitialiseRow(sender, e, statisticsClass) {
  var statistics = sender.GetVirtualClass();
  var item = statistics[e.row.listIndex];

  // Statistics Class
  // NOTE: 0 = isefinStatisticClass.Income, 1 = Expenses, 2 = Assets, 3 = Liabilities
  var useFreq = statisticsClass &lt; 2;

  // Create Controls
  var C = e.row.controls;

  // Get Statistic Type
  var statisticType = mStatisticTypes.GetItem(item.StatisticTypeId);

  C.cboStatisticType = widget.UI.DBCombo(e.row.GetElement("cboStatisticType"), {
    allowBlank: false,
    readOnly: mRecord.ReadOnly,
    showDescription: false,
    width: widget.UI.FIELD_WIDTH_CODE_5,

    onChange: function (sender, e) {
      if (e) e.ChangeHandled = true;
      item.StatisticTypeId = sender.Text();

      // Default other fields
      var statisticType2 = mStatisticTypes.GetItem(item.StatisticTypeId);
      if (statisticType2) {
        item.Description = statisticType2.Description;
        C.txtDescription.Text(item.Description);
      }
    }
  });
  C.cboStatisticType.Text(item.StatisticTypeId);

  C.txtDescription = widget.UI.TextBox(e.row.GetElement("txtDescription"), {
    allowBlank: false,
    maxLength: 50,
    readOnly: mRecord.ReadOnly,
    width: "100%",

    onChange: function (sender, e) {
      if (e) e.ChangeHandled = true;
      item.Description = sender.Text();
    }
  });
  C.txtDescription.Text(item.Description);
  if (statisticType) C.txtDescription.BlankTip(statisticType.Description);
  C.txtDescription.WidthResizeFromParent();

  C.divAccount = e.row.GetElement("divAccount");
  C.divAccount.text(item.AccountId);
  if (!item.AccountId) C.divAccount.hide();

  if (useFreq) {
    C.cboFrequency = widget.UI.ComboBox(e.row.GetElement("cboFrequency"), {
      allowBlank: false,
      listCsv: mRecord.FrequencyPerAnnumList,
      readOnly: mRecord.ReadOnly,
      width: "8em",

      onChange: function (sender, e) {
        if (e) e.ChangeHandled = true;
        item.FrequencyPerAnnumText = sender.Text();

        // Totals
        divTotals_Refresh();
      }
    });
    C.cboFrequency.Text(item.FrequencyPerAnnumText);
  }

  C.numValue = widget.UI.NumberBox(e.row.GetElement("numValue"), {
    blankIfZero: true,
    blankTip: "Value",
    decimals: -1,
    minValue: 0,
    readOnly: mRecord.ReadOnly,
    width: useFreq ? "8em" : "12em",

    onChange: function (sender, e) {
      if (e) e.ChangeHandled = true;
      item.Value = sender.Value();

      // Totals
      divTotals_Refresh();
    }
  });
  C.numValue.Value(item.Value);

  C.txtComments = widget.UI.TextBox(e.row.GetElement("txtComments"), {
    blankTip: "Comments",
    maxLength: 255,
    readOnly: mRecord.ReadOnly,

    onChange: function (sender, e) {
      if (e) e.ChangeHandled = true;
      item.Comments = sender.Text();
    }
  });
  C.txtComments.Text(item.Comments);

  // Fixed Statistics Set?
  if (mRecord_ClientGroup.StatisticsFixed) {
    C.cboStatisticType.ReadOnly(true);
    C.txtDescription.ReadOnly(true);
    C.txtDescription.Element().attr("tabindex", -1);
  }
  else {
    C.cboStatisticType.RefreshFromStandardRange("StatisticTypes", "StatisticClass=" + statisticsClass);
  }

  // Configuration Settings
  C.divStatisticType = e.row.GetElement("divStatisticType");
  switch(mRecord.ShowStatisticTypeId.toUpperCase()) {
    case "TRUE":
      // Always show, i.e., not advanced
      break;

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

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

  C.divComments = e.row.GetElement("divComments");
  switch(mRecord.ShowStatisticComments.toUpperCase()) {
    case "TRUE":
      // Always show, i.e., not advanced
      break;

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

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

  // Account-based Statistic?
  if (item.AccountId) {
    C.cboStatisticType.ReadOnly(true);
    C.txtDescription.ReadOnly(true);
    if (useFreq) C.cboFrequency.ReadOnly(true);
    C.numValue.ReadOnly(true);
    C.txtComments.ReadOnly(true);
  }
}

function rptStatistics_Action(sender, id) {
  switch(id) {
    case "AddRow":
      if (sender.AddRow(true)) {
        // Ensure Statistic Type is always visible
        sender.Element().addClass("has-new");
      }
      break;

    case "DeleteRow":
      sender.RemoveRowAndCollectionItem(sender.ActiveDataRowListIndex());
      sender.Focus();

      // Refresh Buttons
      rptStatistics_RefreshButtons(sender);
      break;

    case "RowMoveDown":
      sender.RowMoveDown();
      break;

    case "RowMoveUp":
      sender.RowMoveUp();
      break;

    default:
      window.alert(id);
  }
}

function rptStatistics_AfterRowActivate(sender, e) {
  // Refresh Buttons
  rptStatistics_RefreshButtons(sender);
}

function rptStatistics_RefreshButtons(sender) {
  var statistics = sender.GetVirtualClass();

  if (sender.ActiveDataRowListIndex() == -1) {
    sender.Actions().SetEnabled("DeleteRow", false);
    sender.Actions().SetEnabled("RowMoveUp", false);
    sender.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    sender.Actions().SetEnabled("DeleteRow", true);
    sender.Actions().SetEnabled("RowMoveUp", sender.ActiveDataRowListIndex() &gt; 0);
    sender.Actions().SetEnabled("RowMoveDown", sender.ActiveDataRowListIndex() &lt; statistics.length - 1);
  }

  sender.RefreshButtons();
}

function rptStatistics_RowAdd(sender, e) {
  var statistics = sender.GetVirtualClass();

  // Create item
  var item = {
    StatisticTypeId: "",
    Description: "",
    FrequencyPerAnnumText: "",
    Comments: "",
    Value: 0,
    OrigIndex: -1, // New item
  };

  // Inherit Frequency
  if (statistics.length &gt; 0) {
    item.FrequencyPerAnnumText = statistics[statistics.length - 1].FrequencyPerAnnumText;
  }

  // Add
  statistics.push(item);
}

// =========
// divTotals
// =========
function divTotals_Refresh() {
  // Income
  var totalIncome = 0;
  for (var i = 0; i &lt; mRecord_ClientStatisticsSet.Income.length; i++) {
    totalIncome += GetStatisticAtFrequency(mRecord_ClientStatisticsSet.Income[i]);
  }
  C.divTotalIncome.html("&lt;small style='font-weight:normal'&gt;" + mRecord.StatisticsDisplayFrequencyText + "&lt;/small&gt; " + widget.FormatCurrency(totalIncome, true));

  // Expenses
  var totalExpenses = 0;
  for (var i = 0; i &lt; mRecord_ClientStatisticsSet.Expenses.length; i++) {
    totalExpenses += GetStatisticAtFrequency(mRecord_ClientStatisticsSet.Expenses[i]);
  }
  C.divTotalExpenses.html("&lt;small style='font-weight:normal'&gt;" + mRecord.StatisticsDisplayFrequencyText + "&lt;/small&gt; " + widget.FormatCurrency(totalExpenses, true));

  // Assets
  var totalAssets = 0;
  for (var i = 0; i &lt; mRecord_ClientStatisticsSet.Assets.length; i++) {
    totalAssets += mRecord_ClientStatisticsSet.Assets[i].Value;
  }
  C.divTotalAssets.text(widget.FormatCurrency(totalAssets, true));

  // Liabilities
  var totalLiabilities = 0;
  for (var i = 0; i &lt; mRecord_ClientStatisticsSet.Liabilities.length; i++) {
    totalLiabilities += mRecord_ClientStatisticsSet.Liabilities[i].Value;
  }
  C.divTotalLiabilities.text(widget.FormatCurrency(totalLiabilities, true));

  // Debt Ratio
  var debtRatio = 0;
  if (mRecord_ClientGroup.ShowIncome &amp;&amp; mRecord_ClientGroup.ShowExpenses &amp;&amp; mRecord_ClientGroup.ShowAssets &amp;&amp; mRecord_ClientGroup.ShowLiabilities) {
  }

  // Footer Stats
  var s = "";
  var warningLevel = 0;

  if (mRecord_ClientGroup.ShowIncome &amp;&amp; mRecord_ClientGroup.ShowExpenses) {
    var netIncome = widget.RoundCurrency(totalIncome - totalExpenses);
    var availableIncome = widget.RoundCurrency(netIncome * mRecord_ClientGroup.AvailableIncomePercent / 100);

    if (netIncome &lt;= 1000 / mRecord.StatisticsDisplayFrequency &amp;&amp; warningLevel &lt; 1) warningLevel = 1;
    if (netIncome &lt;= 0 &amp;&amp; warningLevel &lt; 2) warningLevel = 2;

    s += "&lt;div class='stats-income'&gt;";
    s += "&lt;div&gt;&lt;label&gt;Net " + mRecord.StatisticsDisplayFrequencyText + " Income&lt;/label&gt;&lt;span&gt;" + widget.FormatCurrency(netIncome, true) + "&lt;/span&gt;&lt;/div&gt;";
    s += "&lt;div&gt;&lt;label&gt;Available " + mRecord.StatisticsDisplayFrequencyText + " Income&lt;/label&gt;&lt;span&gt;" + widget.FormatCurrency(availableIncome, true) + "&lt;/span&gt;&lt;/div&gt;";
    s += "&lt;/div&gt;";
  }

  if (mRecord_ClientGroup.ShowAssets &amp;&amp; mRecord_ClientGroup.ShowLiabilities) {
    var netAssets = widget.RoundCurrency(totalAssets - totalLiabilities);
    var availableAssets = widget.RoundCurrency((totalAssets * mRecord_ClientGroup.AvailableAssetsPercent / 100) - totalLiabilities);

    if (netAssets &lt; 0 &amp;&amp; warningLevel &lt; 2) warningLevel = 2;

    s += "&lt;div class='stats-assets'&gt;";
    s += "&lt;div&gt;&lt;label&gt;Net Assets&lt;/label&gt;&lt;span&gt;" + widget.FormatCurrency(netAssets, true) + "&lt;/span&gt;&lt;/div&gt;";
    s += "&lt;div&gt;&lt;label&gt;Available Assets&lt;/label&gt;&lt;span&gt;" + widget.FormatCurrency(availableAssets, true) + "&lt;/span&gt;&lt;/div&gt;";
    s += "&lt;/div&gt;";

    // Debt ratio
    var debtRatio = 0;
    if (totalAssets != 0) debtRatio = totalLiabilities / totalAssets
    s += "&lt;div class='stats-debt-ratio'&gt;";
    s += "&lt;div&gt;&lt;label&gt;Debt Ratio&lt;/label&gt;&lt;span&gt;" + widget.FormatNumber(debtRatio * 100, 2) + "%&lt;/span&gt;&lt;/div&gt;";
    s += "&lt;/div&gt;";

    if (debtRatio &gt;= 1 &amp;&amp; warningLevel &lt; 2) warningLevel = 2;
  }

  C.divTotals.html(s);
  C.divTotals.removeClass("warning-level-0 warning-level-1 warning-level-2");
  C.divTotals.addClass("warning-level-" + warningLevel);
}

function GetStatisticAtFrequency(statistic) {
  // NOTE: Code as per finClientStatisticSet.IncomeTotal
  if (mRecord.StatisticsDisplayFrequency == 0 || !statistic.FrequencyPerAnnumText) {
    // Just in case!
    return 0;
  }
  else if(mRecord.StatisticsDisplayFrequencyText == statistic.FrequencyPerAnnumText) {
    return statistic.Value;
  }
  else {
    // Calculate annual value
    var freq = 1;
    for (var i = 0; i &lt; mRecord.Frequencies.length; i++) {
      var item = mRecord.Frequencies[i];
      if (item.Text == statistic.FrequencyPerAnnumText) {
        freq = item.Value;
        break;
      }
    }
    var valueAnnual = statistic.Value * freq;

    // Value as at display frequency
    return widget.RoundCurrency(valueAnnual / mRecord.StatisticsDisplayFrequency);
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>-H86H-3SaU+uXn9mfGTGUQ</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>2000</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1240</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>If you do not specify a Default Transaction Type, the Transaction Type selection will be shown regardless of the settings specified below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowGeneralOther" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowStatisticTypeId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression>This must always be shown for new Statistics, e.g., those added to a non-fixed Statistics Set</DefaultValueExpression>
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowStatisticComments" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ReadOnly" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ClientId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Clients</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ClientStatisticsSetPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>For 'Quote' Accounts, this should be the 0-based index of the item in the collection</TooltipText>
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="EditJson" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ClientStatisticsSetJson" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Used by the New Account wizard to add and edit unsaved or "Quote" Standard Transactions.</TooltipText>
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>4</Rows>
          </Parameter>
          <Parameter name="DefaultFromLastApproved" 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>