<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-05-15T01:54:39.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-05-15T01:31:05.2770000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-05-15T01:53:33.4760000</UpdatedUtcDate>
    <ScriptId>HWABR</ScriptId>
    <Description>Accounts Breakdown Report</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category>Management Reports</Category>
    <Code>' HtmlWidget_AccountsBreakdown
Option Explicit On
Option Strict On

' #################################################################
' Accounts Breakdown Report HTML Widget
'
' Version: 1.17 (15/05/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.15  02/06/2021  ISS                Updated
'    1.16  11/05/2022  ISS      J028712   Removed obsoleted Functions
'    1.17  15/05/2024  ISS      J033295   Allowing prepaid values to be included
' #################################################################

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

' Other
Private mAccountClass As String
Private mColumns As ISList

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)

  ' Other Parameters
  With mCombinedParameters
    mColumns = .GetListFromGroupingList("Columns")
    mAccountClass = UCase(.GetString("AccountClass"))
  End With
  If mColumns.Count = 0 Then mColumns.FromCsvString("Balance,Overdue,Contractual")

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

    Case "GetReportData"
      ' Get Report Data
      Main = GetReportData(returnValue)

    Case "GetBreakdownData"
      ' Get Breakdown Report Data
      Main = GetBreakdownData(returnValue)
  End Select

End Function

Private Function GetPage() As String

  Dim AccountStatuses As ISList
  Dim AllowBreakdown As Boolean
  Dim AutoShowBreakdown As Boolean
  Dim BasisList As ISCodeDescriptionList
  Dim CustomReportTitle As String
  Dim DefaultBasis As String
  Dim Html As String
  Dim Layout As String
  Dim ShowOverdue As Boolean

  ' Initialise
  Html = ScriptInfo.TemplateText

  ' Get Parameters
  With mCombinedParameters
    AccountStatuses = .GetList("AccountStatuses")
    AllowBreakdown = .GetBoolean("AllowBreakdown", True)
    AutoShowBreakdown = .GetBoolean("AutoShowBreakdown", True)
    CustomReportTitle = .GetString("CustomReportTitle")
    DefaultBasis = .GetString("Basis")
    Layout = .GetString("Layout", "Page")
  End With
  If Len(CustomReportTitle) = 0 Then
    If mAccountClass = "DEPOSIT" Then
      CustomReportTitle = "Deposits"
    Else
      CustomReportTitle = "Loans"
    End If
  End If
  If Len(DefaultBasis) = 0 Then DefaultBasis = "Account Type"

  ' Translate Default Basis
  Select Case DefaultBasis
    Case "Monitor Category A": DefaultBasis = finBL.Settings.MonitorCategoryADescriptionResolved
    Case "Monitor Category B": DefaultBasis = finBL.Settings.MonitorCategoryBDescriptionResolved
    Case "Monitor Category C": DefaultBasis = finBL.Settings.MonitorCategoryCDescriptionResolved
  End Select

  ' Build Basis List available to the User (this is licence-dependent)
  ' NOTE: As far a cusomising this Widget is concerned, the full list is defined as a Script parameter
  BasisList = finBL.Runtime.CreateCodeDescriptionList()
  With BasisList
    If AccountStatuses.Count &gt; 1 Then .Add("Account Status", "Account Status")
    .Add("Account Type", "Account Type")
    If finBL.Settings.AddOns.Branch Then .Add("Branch", "Branch")
    If finBL.Settings.AddOns.ExternalPartyBrokers AndAlso Not (finBL.CurrentUserInformation.IsExternalUser AndAlso finBL.CurrentUserInformation.ExternalPartyType &lt;&gt; isefinExternalPartyType.Broker) Then .Add("Broker", "Broker")
    If finBL.Settings.AddOns.ExternalPartyDealers AndAlso Not (finBL.CurrentUserInformation.IsExternalUser AndAlso finBL.CurrentUserInformation.ExternalPartyType &lt;&gt; isefinExternalPartyType.Dealer) Then .Add("Dealer", "Dealer")
    .Add("Manager", "Manager")
    If finBL.Settings.MonitorCategoryAUse Then .Add("Monitor Category A", finBL.Settings.MonitorCategoryADescriptionResolved)
    If finBL.Settings.MonitorCategoryBUse Then .Add("Monitor Category B", finBL.Settings.MonitorCategoryBDescriptionResolved)
    If finBL.Settings.MonitorCategoryCUse Then .Add("Monitor Category C", finBL.Settings.MonitorCategoryCDescriptionResolved)
  End With

  ' Overdue supported?
  ShowOverdue = (mAccountClass = "LOAN" AndAlso AccountStatuses.Exists(finBL.Enums.isefinAccountStatus_ToString(isefinAccountStatus.Open)))
  If Not ShowOverdue Then
    mColumns.Remove("Overdue")
    mColumns.Remove("Contractual")
  End If

  ' Replace Tags
  Html = Replace(Html, "&lt;%[ShowOverdue]%&gt;",  LCase(CStr(ShowOverdue)))
  Html = Replace(Html, "&lt;%[AccountClass]%&gt;", mAccountClass)
  Html = Replace(Html, "&lt;%[AllowBreakdown]%&gt;", LCase(CStr(AllowBreakdown)))
  Html = Replace(Html, "&lt;%[AutoShowBreakdown]%&gt;", LCase(CStr(AutoShowBreakdown)))
  Html = Replace(Html, "&lt;%[BasisList]%&gt;", BasisList.ToJsonString(False))
  Html = Replace(Html, "&lt;%[Columns]%&gt;", mColumns.ToJsonString())
  Html = Replace(Html, "&lt;%[CustomReportTitle]%&gt;", finBL.Runtime.HtmlUtilities.JavascriptEncode(CustomReportTitle, True))
  Html = Replace(Html, "&lt;%[DefaultBasis]%&gt;", DefaultBasis)
  Html = Replace(Html, "&lt;%[HasUserFilters]%&gt;", LCase(CStr(finBL.CurrentUserInformation.HasFilterAccount)))
  Html = Replace(Html, "&lt;%[Layout]%&gt;", Layout)

  Select Case mAccountClass
    Case "DEPOSIT"
      Html = Replace(Html, "&lt;%[AccountClassDescription]%&gt;", "Deposits")

    Case Else
      Html = Replace(Html, "&lt;%[AccountClassDescription]%&gt;", "Loans")
  End Select

  Return Html

End Function

Private Function GetReportData(ByRef returnValue As String) As Boolean

  Dim Basis As String
  Dim Database As ISDatabaseBL
  Dim dr As IDataReader
  Dim IncludePrepaidValues As Boolean
  Dim sqb As ISSelectQueryBuilder
  Dim Record As Record
  Dim Records As List(Of Record)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  Database = finBL.Database
  Records = New List(Of Record)

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

  ' Validate
  If Success Then
  End If

  ' Build Query
  If Success Then
    sqb = Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Account"
      
      ' Fields
      With .Fields
        .AddCount("Count")
        .AddSum("Balance", "Balance")
        
        If IncludePrepaidValues Then
          ' Include Pre-Paid
          .AddSum("BalanceOverdue", "BalanceOverdue")
          .AddSum("BalanceOverdueC", "BalanceOverdueC")
        Else
          ' Exclude Pre-Paid
          .AddFunction("Sum(" &amp; finBL.Database.SqlIif("[BalanceOverdue]&gt;0", "[BalanceOverdue]", "0", True) &amp; ")", "BalanceOverdue")
          .AddFunction("Sum(" &amp; finBL.Database.SqlIif("[BalanceOverdueC]&gt;0", "[BalanceOverdueC]", "0", True) &amp; ")", "BalanceOverdueC")
        End If
      End With

      ' SQL Where
      AppendSqlWhere(sqb.SqlWhere)

      ' Basis-Specific
      Select Case UCase(Basis)
        Case "ACCOUNT STATUS"
          .Fields.Add("Status", "TypePk")
          .GroupByFields.Add("Status")

        Case "ACCOUNT TYPE"
          .Fields.Add("AccountTypePk", "TypePk")
          .GroupByFields.Add("AccountTypePk")

        Case "BRANCH"
          .Fields.Add("BranchPk", "TypePk")
          .GroupByFields.Add("BranchPk")

        Case "BROKER"
          .Fields.Add("BrokerExPartyPk", "TypePk")
          .GroupByFields.Add("BrokerExPartyPk")

        Case "DEALER"
          .Fields.Add("DealerExPartyPk", "TypePk")
          .GroupByFields.Add("DealerExPartyPk")

        Case "MANAGER"
          .Fields.Add("AccountManagerUserPk", "TypePk")
          .GroupByFields.Add("AccountManagerUserPk")

        Case "MONITOR CATEGORY A"
          .Fields.Add("MonitorCatAPk", "TypePk")
          .GroupByFields.Add("MonitorCatAPk")

        Case "MONITOR CATEGORY B"
          .Fields.Add("MonitorCatBPk", "TypePk")
          .GroupByFields.Add("MonitorCatBPk")

        Case "MONITOR CATEGORY C"
          .Fields.Add("MonitorCatCPk", "TypePk")
          .GroupByFields.Add("MonitorCatCPk")
      End Select
    End With
  End If

  ' Execute Query and get Results
  If Success Then
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        ' Create Record
        Record = New Record()

        ' General
        Record.Pk = Database.GetFieldInteger(dr!TypePk)
        Record.Count = Database.GetFieldInteger(dr!Count)
        Record.BalanceOverdue = Database.GetFieldDecimal(dr!BalanceOverdue)
        Record.BalanceOverdueC = Database.GetFieldDecimal(dr!BalanceOverdueC)

        ' Reverse Balance for Deposits (pie charts can't display negative values!)
        Select Case mAccountClass
          Case "DEPOSIT"
            Record.Balance = -Database.GetFieldDecimal(dr!Balance)

          Case Else
            Record.Balance = Database.GetFieldDecimal(dr!Balance)
        End Select

        ' Basis-Specific
        Select Case UCase(Basis)
          Case "ACCOUNT STATUS"
            Record.Code = DirectCast(Database.GetFieldEnum(dr!TypePk, GetType(isefinAccountStatus)), isefinAccountStatus).ToString()
            Record.Description = finBL.Enums.isefinAccountStatus_ToString(DirectCast(Database.GetFieldEnum(dr!TypePk, GetType(isefinAccountStatus)), isefinAccountStatus))

          Case "ACCOUNT TYPE"
            With finBL.AccountTypes.ItemByPk(Database.GetFieldInteger(dr!TypePk))
              Record.Code = .AccountTypeId
              Record.Description = .Description
            End With

          Case "BRANCH"
            If Database.GetFieldInteger(dr!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No Branch)"
            Else
              With finBL.Branches.ItemByPk(Database.GetFieldInteger(dr!TypePk))
                Record.Code = .BranchId
                Record.Description = .Description
              End With
            End If

          Case "BROKER"
            If Database.GetFieldInteger(dr!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No Broker)"
            Else
              With finBL.ExternalParties.ItemByPk(Database.GetFieldInteger(dr!TypePk))
                Record.Code = .ExternalPartyId
                Record.Description = .Description
              End With
            End If

          Case "DEALER"
            If Database.GetFieldInteger(dr!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No Dealer)"
            Else
              With finBL.ExternalParties.ItemByPk(Database.GetFieldInteger(dr!TypePk))
                Record.Code = .ExternalPartyId
                Record.Description = .Description
              End With
            End If

          Case "MANAGER"
            If Database.GetFieldInteger(dr!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No Manager)"
            Else
              With finBL.Users.ItemByPkSafe(Database.GetFieldInteger(dr!TypePk))
                Record.Code = .UserId
                Record.Description = .Name
              End With
            End If

          Case "MONITOR CATEGORY A"
            If Database.GetFieldInteger(dr!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No " &amp; finBL.Settings.MonitorCategoryADescriptionResolved &amp; ")"
            Else
              With finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(dr!TypePk))
                Record.Code = .MonitorCategoryId
                Record.Description = .Description
              End With
            End If

          Case "MONITOR CATEGORY B"
            If Database.GetFieldInteger(dr!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No " &amp; finBL.Settings.MonitorCategoryBDescriptionResolved &amp; ")"
            Else
              With finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(dr!TypePk))
                Record.Code = .MonitorCategoryId
                Record.Description = .Description
              End With
            End If

          Case "MONITOR CATEGORY C"
            If Database.GetFieldInteger(dr!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No " &amp; finBL.Settings.MonitorCategoryCDescriptionResolved &amp; ")"
            Else
              With finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(dr!TypePk))
                Record.Code = .MonitorCategoryId
                Record.Description = .Description
              End With
            End If
        End Select

        ' Add
        Records.Add(Record)
      Loop
      Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' Return a JSON Object
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Records, returnValue)
  End If

  Return Success

End Function

Private Sub AppendSqlWhere(swb As ISSqlWhereBuilder)

  Dim AccountStatuses As String
  Dim SqlWhere As String

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

  ' Update SQL Where
  With swb
    ' Account Class
    Select Case mAccountClass
      Case "DEPOSIT"
        ' Deposits
        .AppendComparisonInteger("AccountClass", "=", isefinAccountClass.Deposit)

      Case Else
        ' Loans
      .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
      .AppendComparisonInteger("AccountClass", "=", isefinAccountClass.LoanFR)
      .AppendComparisonInteger("AccountClass", "=", isefinAccountClass.LoanFT)
      .AppendComparisonInteger("AccountClass", "=", isefinAccountClass.LoanRC)
      .BlockEnd()
    End Select

    ' Account Status
    .AppendEnumRangeUsingStringConverter("Account.Status", AccountStatuses, AddressOf finBL.Enums.isefinAccountStatus_FromStringToInt)

    ' User Filters
    .Append(finBL.CurrentUserInformation.FilterAccountSqlWhere)

    ' Custom SQL Where Parameter
    If Len(SqlWhere) &lt;&gt; 0 Then .Append(SqlWhere)
  End With

End Sub

Private Function GetBreakdownData(ByRef returnValue As String) As Boolean

  Dim AllowBreakdown As Boolean
  Dim Basis As String
  Dim BreakdownPk As Integer
  Dim Database As ISDatabaseBL
  Dim dr As IDataReader
  Dim IncludePrepaidValues As Boolean
  Dim sqb As ISSelectQueryBuilder
  Dim Record As Record
  Dim Records As List(Of Record)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  Database = finBL.Database
  Records = New List(Of Record)

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

  ' Validate
  If Success Then
    If Not AllowBreakdown Then
      Success = False
      finBL.Error.ErrorBegin("Breakdowns are disabled for this Widget.")
    End If
  End If

  ' Build Query
  If Success Then
    sqb = Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Account"
      
      ' Fields
      With .Fields
        .AddList("Pk,AccountId,Name,Balance")
      
        If IncludePrepaidValues Then
          ' Include Prepaid
          .Add("BalanceOverdue", "BalanceOverdue")
          .Add("BalanceOverdueC", "BalanceOverdueC")
        Else
          ' Exclude Prepaid
          .AddFunction(finBL.Database.SqlIif("[BalanceOverdue]&gt;0", "[BalanceOverdue]", "0", True), "BalanceOverdue")
          .AddFunction(finBL.Database.SqlIif("[BalanceOverdueC]&gt;0", "[BalanceOverdueC]", "0", True), "BalanceOverdueC")
        End If
      End With

      ' SQL Where
      With .SqlWhere
        ' General
        AppendSqlWhere(sqb.SqlWhere)

        ' Breakdown-Specific
        Select Case UCase(Basis)
          Case "ACCOUNT STATUS"
            .AppendComparisonInteger("Status", "=", BreakdownPk)

          Case "ACCOUNT TYPE"
            .AppendComparisonInteger("AccountTypePk", "=", BreakdownPk)

          Case "BRANCH"
            .AppendComparisonInteger("BranchPk", "=", BreakdownPk)

          Case "BROKER"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("BrokerExPartyPk")
            Else
              .AppendComparisonInteger("BrokerExPartyPk", "=", BreakdownPk)
            End If

          Case "DEALER"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("DealerExPartyPk")
            Else
              .AppendComparisonInteger("DealerExPartyPk", "=", BreakdownPk)
            End If

          Case "MANAGER"
            .AppendComparisonInteger("AccountManagerUserPk", "=", BreakdownPk)

          Case "MONITOR CATEGORY A"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("MonitorCatAPk")
            Else
              .AppendComparisonInteger("MonitorCatAPk", "=", BreakdownPk)
            End If

          Case "MONITOR CATEGORY B"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("MonitorCatBPk")
            Else
              .AppendComparisonInteger("MonitorCatBPk", "=", BreakdownPk)
            End If

          Case "MONITOR CATEGORY C"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("MonitorCatCPk")
            Else
              .AppendComparisonInteger("MonitorCatCPk", "=", BreakdownPk)
            End If
        End Select
      End With
    End With
  End If

  ' Execute Query and get Results
  If Success Then
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        ' Create Record
        Record = New Record()

        ' General
        Record.Pk = Database.GetFieldInteger(dr!Pk)
        Record.Code = Database.GetFieldString(dr!AccountId)
        Record.Description = Database.GetFieldString(dr!Name)
        Record.Balance = Database.GetFieldDecimal(dr!Balance)
        Record.BalanceOverdue = Database.GetFieldDecimal(dr!BalanceOverdue)
        Record.BalanceOverdueC = Database.GetFieldDecimal(dr!BalanceOverdueC)

        ' Add
        Records.Add(Record)
      Loop
      Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' Return a JSON Object
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Records, returnValue)
  End If

  Return Success

End Function


' Classes

Public Class Record

  Public Pk As Integer
  Public Code As String
  Public Description As String
  Public Count As Integer
  Public Balance As Decimal
  Public BalanceOverdue As Decimal
  Public BalanceOverdueC As Decimal

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget to provide a sample Management Dashboard that shows a breakdown of overdue Accounts by various different basis.

A parameter allows the Account Class to be defined, therefore this Widget can be used for both Loans and Deposits.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;head&gt;
&lt;!--Load Google Maps AJAX API--&gt;
&lt;script type="text/javascript" src="https://www.google.com/jsapi"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;


&lt;div id="divReport" class="is-widget-content" style="display:none"&gt;

  &lt;div id="divHeading"&gt;
    &lt;h1 id="lblMainTitle"&gt;Summary of Accounts&lt;/h1&gt;
  &lt;/div&gt;

  &lt;div id="divMain" style="max-width:800px;"&gt;
    &lt;table id="gridItems" style="width:auto"&gt;
      &lt;thead&gt;
        &lt;th key="ShowBreakdown" data-type="drilldown" style="width:20px" drilldown-glyph="breakdown"&gt;&lt;/th&gt;
        &lt;th key="Code" caption="Code" data-type="html" sortable="true" style="width:8em"&gt;&lt;input id="cboBasis"/&gt;&lt;/th&gt;
        &lt;th key="Description" data-type="string" sortable="true"&gt;Description&lt;/th&gt;
        &lt;th key="Count" data-type="integer" sortable="true" selectable="true" summary="sum"&gt;Count&lt;/th&gt;
      &lt;/thead&gt;
    &lt;/table&gt;
  &lt;/div&gt;


  &lt;div id="divChart" style="position:relative"&gt;
    &lt;div id="blChartActions"&gt;&lt;/div&gt;
    &lt;div id="divCharts"&gt;
      &lt;div id="divChartMain"&gt;&lt;div id="chrtMain"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartBreakdown"&gt;&lt;div id="chrtBreakdown"&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;


  &lt;div id="divBreakdown" style="clear:both; display:none; padding-top:8px"&gt;

    &lt;h2 id="lblBreakdownTitle"&gt;&lt;/h2&gt;

    &lt;div id="divBreakdownTable"&gt;
      &lt;table id="gridBreakdown" class="is-grid is-widget-report" style="float:left; width:auto"&gt;
        &lt;thead&gt;
          &lt;th key="Code" data-type="code" sortable="true" summary="count"&gt;Account&lt;/th&gt;
          &lt;th key="Description" data-type="string" sortable="true"&gt;Name&lt;/th&gt;
        &lt;/thead&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;div&gt;

&lt;/div&gt;


&lt;script&gt;
// Server-side information
var mAccountClass = "&lt;%[AccountClass]%&gt;";
var mAccountClassDescription = "&lt;%[AccountClassDescription]%&gt;";
var mAllowBreakdown = &lt;%[AllowBreakdown]%&gt;;
var mAutoShowBreakdown = &lt;%[AutoShowBreakdown]%&gt;;
var mBasisList = &lt;%[BasisList]%&gt;;
var mColumns = &lt;%[Columns]%&gt;;
var mCustomReportTitle = &lt;%[CustomReportTitle]%&gt;;
var mDefaultBasis = "&lt;%[DefaultBasis]%&gt;";
var mHasUserFilters = &lt;%[HasUserFilters]%&gt;;
var mLayout = "&lt;%[Layout]%&gt;";
var mShowOverdue = &lt;%[ShowOverdue]%&gt;;

var mResultsMain = null;
var mResultsBreakdown = null;
var mChart;

// Controls
var C = {
  // Main
  lblMainTitle: null,
  gridItems: null,
  cboBasis: null,

  // Charts
  divCharts: null,
  divChart: null,
  blChartActions: null,

  divChartMain: null,
  chrtMain: null,

  divChartBreakdown: null,
  chrtBreakdown: null,

  // Breakdown
  divBreakdown: null,
  lblBreakdownTitle: null,
  divBreakdownTable: null,
  gridBreakdown: null,
}

var mResultsMain = null;
var mResultsMainFiltered = null;
var mResultsBreakdown = null;
var mUpdateChartsPanelTimer;

var mBasis;
var mBasisDescription;
var mBreakdownIndex = -1;
var mMainChartFieldId;
var mBreakdownChartFieldId;

var mChartColoursMain = ["#3366cc","#dc3912","#ff9900","#109618","#990099","#0099c6","#dd4477","#66aa00","#b82e2e","#316395","#994499","#22aa99","#aaaa11","#6633cc","#e67300","#8b0707","#651067","#329262","#5574a6","#3b3eac","#b77322","#16d620","#b91383","#f4359e","#9c5935","#a9c413","#2a778d","#668d1c","#bea413","#0c5922","#743411"];
var mChartsZoomed = false;
var mChartTitleMain = "";
var mChartTitleSub = "";

// Load the Visualization API and the corechart package.
google.charts.load("current", {"packages":["corechart", "bar"]});


// Initialise
$(function () {
  // ----------------
  // Dashboard Layout
  // ----------------
  var stickyHeader = false;
  if (mLayout == "Dashboard" &amp;&amp; !widget.UI.IsSmallMobileBrowser()) {
    // Create Dashboard
    stickyHeader = true;
    var DashboardLayout = widget.UI.DashboardLayout("divReport", {});

    DashboardLayout.AddHeading("divHeading");
    DashboardLayout.AddColumn({ width: "50%"}, [
      { element: "divMain" }
    ]);
    DashboardLayout.AddColumn({ width: "50%", maxWidth: "720px", minWidth: "320px"}, [
      {
        element: "divChart",
        maxHeight: "360px",
        zoomable: true,
        onZoomIn: function() { mChartsZoomed = true; UpdateChartsPanel(); },
        onZoomOut: function() { mChartsZoomed = false; UpdateChartsPanel(); }
      },
      { element: "divBreakdown", headingElement: "lblBreakdownTitle", visible: mAllowBreakdown },
    ]);

    // Additional Dashboard formatting
    $("#blChartActions").css({ "margin-left": "4px" });
    $("#divCharts").css({ position: "absolute", top: "38px", left: "4px", right: 0, bottom: 0, "overflow-x": "hidden", "overflow-y":"auto" });
  }

  // --------
  // Controls
  // --------
  C.lblMainTitle = widget.UI.Label("lblMainTitle", {});
  C.cboBasis = widget.UI.ComboBox("cboBasis", {
    limitToList: true,
    width: "10em",

    onChange: cboBasis_Change,
  });

  C.divBreakdown = $("#divBreakdown");
  C.lblBreakdownTitle = widget.UI.Label("lblBreakdownTitle", {});
  C.divBreakdownTable = $("#divBreakdownTable");

  C.divCharts = $("#divCharts");
  C.divChart = $("#divChart");
  C.blChartActions = widget.UI.ButtonList("blChartActions", {
    style: "actions",
    size: "normal",
    onChange: blChartActions_Change
  });

  C.divChartMain = $("#divChartMain");
  C.divChartBreakdown = $("#divChartBreakdown");

  // Defaults
  C.cboBasis.ListFromCollection(mBasisList, "Description");
  C.cboBasis.Text(mDefaultBasis);

  // Initialise Grids
  C.gridItems = widget.UI.Grid("gridItems", {
    style: "report",
    stickyHeader: stickyHeader,

    showRowSelectors: true,
    allowMultiRowSelect: true,

    onInitialiseRow: gridItems_InitialiseRow,
    onAfterRowActivate: gridItems_AfterRowActivate,
    onColumnSelect: gridItems_ColumnSelect,
    onAfterColumnSort: gridItems_AfterColumnSort,
    onRowDrilldown: gridItems_RowDrilldown,
    onSelectedRowsChanged: gridItems_SelectedRowsChanged,
  });

  C.gridBreakdown = widget.UI.Grid("gridBreakdown", {
    style: "",
    stickyHeader: stickyHeader,

    onInitialiseRow: gridBreakdown_InitialiseRow,
    onColumnSelect: gridBreakdown_ColumnSelect,
  });

  // Mandatory Main Grid columns
  C.gridItems.ColumnVisible("ShowBreakdown", mAllowBreakdown &amp;&amp; !mAutoShowBreakdown);

  // Add optional Main Grid columns
  mMainChartFieldId = "Count";
  for(var i = 0; i &lt; mColumns.length; i++) {
    switch(mColumns[i].toUpperCase()) {
      case "BALANCE":
        C.gridItems.AddColumnCurrency("Balance", {caption: "Balance", selectable: true, sortable: true, summary: "$sum"});
        break;

      case "CONTRACTUAL":
        C.gridItems.AddColumnCurrency("BalanceOverdueC", {caption: "Contractual", selectable: true, sortable: true, summary: "$sum"});
        break;

      case "OVERDUE":
        C.gridItems.AddColumnCurrency("BalanceOverdue", {caption: "Overdue", selectable: true, sortable: true, summary: "$sum"});
        break;
    }
  }
  C.gridItems.SelectedColumnKey(mMainChartFieldId);

  // Add optional Breakdown Grid columns
  mBreakdownChartFieldId = "Balance";
  for(var i = 0; i &lt; mColumns.length; i++) {
    switch(mColumns[i].toUpperCase()) {
      case "BALANCE":
        C.gridBreakdown.AddColumnCurrency("Balance", {caption: "Balance", selectable: true, sortable: true, summary: "$sum"});
        break;

      case "CONTRACTUAL":
        C.gridBreakdown.AddColumnCurrency("BalanceOverdueC", {caption: "Contractual", selectable: true, sortable: true, summary: "$sum"});
        break;

      case "OVERDUE":
        C.gridBreakdown.AddColumnCurrency("BalanceOverdue", {caption: "Overdue", selectable: true, sortable: true, summary: "$sum"});
        break;
    }
  }
  C.gridBreakdown.SelectedColumnKey(mBreakdownChartFieldId);

  // Define Chart Action buttons
  var chartButtons = [];
  chartButtons.push({ id: "Selected", caption: "Selected" });
  if (mBreakdownChartFieldId) {
    chartButtons.push({ id: "BreakdownSelected", caption: "Breakdown", visible: false });
  }
  else {
    // No chartable columns for breakdown grid
  }
  C.blChartActions.ButtonsDefine(chartButtons);
  C.blChartActions.SelectedItemId("Selected");

  // Set a callback to run when the Google Visualization API is loaded
  google.charts.setOnLoadCallback(RunMain);

  // Resize charts when window resized
  $(window).resize(function() { UpdateChartsPanel(true); });

  // Finalise
  $(".is-widget-content").show();
});


function LayoutDashboard(containerElement, options, panels) {
  // Initialise
  if (typeof containerElement == "string") containerElement = $("#" + containerElement);

  // Container
  containerElement.css({display:"flex", "flex-flow":"row wrap", "align-content":"stretch", position:"absolute", top:"0", right:"0", left:"0", bottom:"0", overflow:"hidden", "padding-left":"0", "padding-right":"0", "padding-top":"0", "padding-bottom":"0"});

  // Position Panels
  for (var i = 0; i &lt; panels.length; i++) {
    var panel = panels[i];
    var element = panel.element;
    var position = panel.position;

    if (typeof element == "string") element = $("#" + element);

    // Position
    var css = { margin:"0", "float":"none"};
    switch(position.toUpperCase()) {
      case "HEADING":
        // Heading
        element.css({flex:"0 100%", overflow:"hidden", "border-bottom":"1px solid rgba(0,0,0,0.05)", "background-color":"rgba(0,0,0,0.025)"});
        break;

      case "HIDDEN":
        // Hidden
        element.css({display:"hidden"});
        break;

      case "LEFT":
        // Left
        element.css({flex:"1 auto", "border-right":"4px solid rgba(0,0,0,0.05)", overflow:"auto", width:"50%", height:"100%"});
        break;

      case "RIGHT":
        // Right
        element.css({flex:"1 auto", overflow:"auto", width:"50%", height:"100%"});
        break;

      case "TOPRIGHT":
      case "RIGHTTOP":
        // Top Right
        element.css({flex:"1 auto", "align-self":"flex-start", "border-bottom":"4px solid rgba(0,0,0,0.05)", overflow:"auto", width:"50%", height:"50%"});
        break;

      case "BOTTOMRIGHT":
      case "RIGHTBOTTOM":
        // Bottom Right
        element.css({flex:"1 auto", border:"4px solid pink", overflow:"auto", width:"50%", height:"50%"});
        break;

      default:
        window.alert("Unhandled Panel Position '" + position + "'. Valid positions are: Heading, Left, Right, Top, Bottom, TopLeft, BottomLeft, TopRight, BottomRight, Hidden");
        break;
    }
    if (panel.maxWidth) element.css("max-width", panel.maxWidth);
    element.css({position:"relative", "padding-left":"4px", "padding-top":"4px", "padding-right":"4px", "padding-bottom":"4px"});
    element.css(css);
  }

}

// ===============
// Run Main Report
// ===============
function RunMain() {
  // Can we run?
  var basisIndex = C.cboBasis.ListIndex();
  if (basisIndex == -1) return;

  // Initialise
  C.divBreakdown.hide();
  C.lblBreakdownTitle.Visible(false);
  C.gridItems.Sort("");

  // Update title
  mBasis = mBasisList[basisIndex].Code;
  mBasisDescription = C.cboBasis.Text();

  // Create parameters
  var params = { basis: mBasisList[basisIndex].Code };

  // Block UI
  widget.UI.Block("Please wait...");

  // Get Report Results
  widget.GetString("GetReportData", params, RunMain_Done, Run_Fail);
}

function RunMain_Done(data) {
  // Parse Main Results
  mResultsMain = JSON.parse(data);

  // Bind grid
  C.gridItems.VirtualDataRefresh(mResultsMain);

  // Update title
  var title = mCustomReportTitle + " by &lt;span class='parameter'&gt;" + widget.UI.HtmlEncode(mBasisDescription) + "&lt;/span&gt;";
  if (mHasUserFilters) title += "&lt;div class='is-info-text warning small'&gt;User Filters have been applied to the results&lt;/div&gt;";
  mChartTitleMain = mCustomReportTitle + " by " + mBasisDescription;
  //mChartTitleSub = "for period ";
  C.lblMainTitle.Html(title);

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

  // Create Charts
  mBreakdownIndex = -1;
  UpdateChartsPanel();
}

function Run_Fail(errorMessage) {
  window.alert(errorMessage);

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

// ====================
// Run Breakdown Report
// ====================
function RunBreakdown(index) {
  // Disabled?
  if (!mAllowBreakdown) return;

  // Already showing?
  if (index == mBreakdownIndex) return;

  // Initialise
  mBreakdownIndex = index;
  if (mBreakdownIndex == -1) {
    C.divBreakdown.hide();
    C.lblBreakdownTitle.Visible(false);
  }
  else {
    C.divBreakdown.show();
    C.lblBreakdownTitle.Visible(true);
  }

  // Recreate chart to explode pie segment
  CreatePieChart(mResultsMain, mResultsMainFiltered, "chrtMain", "Main", mMainChartFieldId, mBreakdownIndex);

  // Showing breakdown?
  if (mBreakdownIndex == -1) return;

  // Update title
  if (mResultsMain[mBreakdownIndex].Code) {
    C.lblBreakdownTitle.Text(mResultsMain[mBreakdownIndex].Code + ", " + mResultsMain[mBreakdownIndex].Description);
  }
  else {
    C.lblBreakdownTitle.Text("(No " + mBasisDescription + ")");
  }

  // Highlight selected row
  C.gridItems.ActiveDataRowListIndex(index);

  // Create parameters
  var params = { basis: mBasis, breakdownPk: mResultsMain[index].Pk };

  // Block UI
  widget.UI.Block("Please wait...");

  // Get Report Results
  widget.GetString("GetBreakdownData", params, RunBreakdown_Done, Run_Fail);
}

function RunBreakdown_Done(data) {
  // Parse Breakdown Results
  mResultsBreakdown = JSON.parse(data);

  // Bind grid
  C.gridBreakdown.VirtualDataRefresh(mResultsBreakdown);

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

  // Show and scroll into view
  C.divBreakdown.show();
  C.lblBreakdownTitle.Visible(true);
  widget.UI.ScrollToTop("divBreakdown");

  // Update Breakdown Chart
  blChartActions_Change();
}

// =========
// gridItems
// =========
function gridItems_InitialiseRow(e) {
  var item = mResultsMain[e.row.listIndex];

  // Legend for code cell
  item._listIndex = e.row.listIndex;
  item._legendColour = mChartColoursMain[e.row.listIndex % mChartColoursMain.length];
  e.row.cells.Code.value = "&lt;nobr&gt;&lt;span class='legend' style='background-color:" + item._legendColour + "'&gt;&lt;/span&gt;" + widget.UI.HtmlEncode(item.Code) + "&lt;/nobr&gt;";
  e.row.cells.Code.sortValue = item.Code;

  e.row.cells.Description.value = item.Description;
  e.row.cells.Count.value = item.Count;
  if (e.row.cells.Balance != undefined) e.row.cells.Balance.value = item.Balance;
  if (e.row.cells.BalanceOverdue != undefined) e.row.cells.BalanceOverdue.value = item.BalanceOverdue;
  if (e.row.cells.BalanceOverdueC != undefined) e.row.cells.BalanceOverdueC.value = item.BalanceOverdueC;

  // Row style

  // Cell styles
  e.row.cells.Description.small = true;
  if (e.row.cells.BalanceOverdue != undefined &amp;&amp; item.BalanceOverdue &gt; 0) e.row.cells.BalanceOverdue.colour = "red";
  if (e.row.cells.BalanceOverdueC != undefined &amp;&amp; item.BalanceOverdueC &gt; 0) e.row.cells.BalanceOverdueC.colour = "red";
}

function gridItems_AfterRowActivate() {
  if (mAutoShowBreakdown) {
    // Run breakdown and explode segment
    RunBreakdown(C.gridItems.ActiveDataRowListIndex());
  }
  else {
    // Explode segment but do not run breakdown
    CreatePieChart(mResultsMain, mResultsMainFiltered, "chrtMain", "Main", mMainChartFieldId, C.gridItems.ActiveDataRowListIndex());
  }
}

function gridItems_ColumnSelect() {
  mMainChartFieldId = C.gridItems.SelectedColumnKey();

  // Show chart for column
  C.blChartActions.SelectedItemId("Selected");
  blChartActions_Change();
}

function gridItems_AfterColumnSort() {
  // Get filtered data and redraw charts to account for new sort order
  UpdateChartsPanel();
}

function gridItems_RowDrilldown(e) {
  RunBreakdown(e.row.listIndex);
}

function gridItems_SelectedRowsChanged(e) {
  // Update charts
  UpdateChartsPanel(true);
}

// =============
// gridBreakdown
// =============
function gridBreakdown_InitialiseRow(e) {
  var item = mResultsBreakdown[e.row.listIndex];

  item._listIndex = e.row.listIndex;

  e.row.cells.Code.value = item.Code;
  e.row.cells.Description.value = item.Description;
  if (e.row.cells.Balance != undefined) e.row.cells.Balance.value = item.Balance;
  if (e.row.cells.BalanceOverdue != undefined) e.row.cells.BalanceOverdue.value = item.BalanceOverdue;
  if (e.row.cells.BalanceOverdueC != undefined) e.row.cells.BalanceOverdueC.value = item.BalanceOverdueC;

  // Cell styles
  e.row.cells.Description.small = true;
  if (e.row.cells.BalanceOverdue != undefined &amp;&amp; item.BalanceOverdue &gt; 0) e.row.cells.BalanceOverdue.colour = "red";
  if (e.row.cells.BalanceOverdueC != undefined &amp;&amp; item.BalanceOverdueC &gt; 0) e.row.cells.BalanceOverdueC.colour = "red";

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

function gridBreakdown_ColumnSelect() {
  mBreakdownChartFieldId = C.gridBreakdown.SelectedColumnKey();

  // Show chart for column
  C.blChartActions.SelectedItemId("BreakdownSelected");
  blChartActions_Change();
}

// ==============
// blChartActions
// ==============
function blChartActions_Change(sender, e) {
  // Hide all charts
  C.divChartMain.hide();
  C.divChartBreakdown.hide();

  // Update Chart action captions
  var c = C.gridItems.SelectedColumn();
  if (c) {
    C.blChartActions.ButtonCaption("Selected", c.caption);
  }
  var c = C.gridBreakdown.SelectedColumn();
  if (c &amp;&amp; mResultsBreakdown) {
    C.blChartActions.ButtonCaption("BreakdownSelected", "Breakdown (" + c.caption + ")");
    C.blChartActions.ButtonVisible("BreakdownSelected", true);
  }
  else {
    C.blChartActions.ButtonVisible("BreakdownSelected", false);
    if (C.blChartActions.SelectedItemId() == "BreakdownSelected") {
      C.blChartActions.SelectedItemId("Selected", false);
    }
  }

  // Create and show selected chart (create each time to force a redraw)
  // NOTE: Add slight delay to avoid resize issues
  window.setTimeout(function () {
    switch(C.blChartActions.SelectedItemId()) {
      case "Selected":
        // Main (Selected) Pie Chart
        C.divChartMain.show();
        CreatePieChart(mResultsMain, mResultsMainFiltered, "chrtMain", "Main", mMainChartFieldId, mBreakdownIndex);
        break;

      case "BreakdownSelected":
        // Breakdown (Selected) Pie Chart
        C.divChartBreakdown.show();
        //CreatePieChart(chartData, chartData, "chrtBreakdown", "Breakdown", "Value", -999);
        CreateBarChart(mResultsBreakdown, mResultsBreakdown, "chrtBreakdown", "Breakdown", mBreakdownChartFieldId);
        break;
    }
   }
   , 100);

}

// ================
// Create Pie Chart
// ================
function CreatePieChart(records, recordsFiltered, chartDivId, chartKey, fieldId, explodeSegmentListIndex) {
  // Initialise
  var chartDiv = $("#" + chartDivId);
  var chart = C["chrt" + chartKey];

  // Can we create a chart?
  if (recordsFiltered &amp;&amp; recordsFiltered.length != 0) {
    chartDiv.show();
  }
  else {
    chartDiv.hide();
    return;
  }

  // Create the data table
  var data = new google.visualization.DataTable();
  data.addColumn("string", "Code");
  data.addColumn("number", "Value");
  for(var i = 0; i &lt; recordsFiltered.length; i++) {
    data.addRow([recordsFiltered[i].Code, recordsFiltered[i][fieldId]]);
  }

  // Create slices array so we can colour and explode slices
  var slices = [];
  for(var i = 0; i &lt; recordsFiltered.length; i++) {
    var item = recordsFiltered[i];

    var slice = { color: item._legendColour, _listIndex: item._listIndex };
    slices.push(slice);

    // Explode slice?
    if (item._listIndex == explodeSegmentListIndex) slice.offset = 0.1;
  }

  // Chart options
  var options = {title: "",
                 legend: {position: "right"},
                 chartArea: {width: "95%", height: "95%", left: 24, top: 0},
                 is3D: false,
                 slices: slices};

  // Zoomed chart options
  if (mChartsZoomed) {
    // Title and Legend
    var tabCaption = C.blChartActions.GetButtonCaptionText(C.blChartActions.SelectedItemId());
    options.title = mChartTitleMain + ": " + tabCaption + "\n" + mChartTitleSub;
    if (records.length != recordsFiltered.length) options.title += " (filtered)";
    options.titleTextStyle = {fontName: "arial black", fontSize: 22, bold: false};

    // Size
    options.width = window.innerWidth - 24;
    options.height= window.innerHeight - 24;
    options.chartArea.top = 80;
  }
  else {
    // Size
    if (mLayout == "Dashboard" &amp;&amp; !widget.UI.IsSmallMobileBrowser()) {
      // Dashboard
      options.width = C.divCharts.innerHeight() + 100;
      options.height = C.divCharts.innerHeight() - 20;
    }
    else {
      // Page
      options.width = 400;
      options.height = 300;
    }
  }

  // Draw chart
  if (!chart) {
    chart = new google.visualization.PieChart(chartDiv[0]);
  }
  else {
    google.visualization.events.removeListener(chart._listener);
  }
  C["chrt" + chartKey] = chart;
  chart.draw(data, options);

  // Allow segment click to show breakdown
  if (explodeSegmentListIndex == -999) {
    // Not supported, e.g., charting breakdown data
  }
  else {
    chart._listener = google.visualization.events.addListener(C.chrtMain, "select", function () {
      var sliceIndex = chart.getSelection()[0].row;

      if (sliceIndex != null) {
        // Get real list index of segment record
        var listIndex = slices[sliceIndex]._listIndex;

        if (mAutoShowBreakdown) {
          // Run breakdown and explode segment
          RunBreakdown(listIndex);
        }
        else {
          // Select row (also explodes segment)
          C.gridItems.ActiveDataRowListIndex(listIndex);
        }
      }
    });
  }
}

// ================
// Create Bar Chart
// ================
function CreateBarChart(records, recordsFiltered, chartDivId, chartKey, fieldId) {
  // Initialise
  var chartDiv = $("#" + chartDivId);
  var chart = C["chrt" + chartKey];
  var dt = [];

  // Create data table header row
  var headerRow = ["Account", "Value"];
  var series = {};
  series[0] = {};
  dt.push(headerRow);

  // Add data rows
  for (var j = 0; j &lt; recordsFiltered.length; j++) {
    var item = recordsFiltered[j];
    var row = [item.Code, item[fieldId]];
    dt.push(row);
  }

  // Finalise data table
  var data = new google.visualization.arrayToDataTable(dt);

  // Chart options
  var options = { title: "",
                  legend: {position: "top"},
                  bars: "horizontal",
                  height: 100 + (recordsFiltered.length * 20),
                  width: chartDiv.innerWidth() - 20,
                  isStacked: true,
                  series: series,
                  hAxis: { title: "", format: "decimal", textStyle: {fontSize: 10}},
                  vAxes: { 0: { title: "Account", viewWindow: { }, textStyle: {fontSize: 10.5}}},
                };

  // Zoomed chart options
  if (mChartsZoomed) {
    var tabCaption = C.blChartActions.GetButtonCaptionText(C.blChartActions.SelectedItemId());
    options.title = mChartTitleMain + ": " + tabCaption;
    if (records.length != recordsFiltered.length) options.title += " (filtered)";
    options.subtitle = mChartTitleSub;
    options.titleTextStyle = { fontName: "arial black", fontSize: 22, bold: false };
    options.height += 100;
  }

  // Draw chart
  if (!chart) {
    chart = new google.charts.Bar(chartDiv[0]);
  }
  else {
    google.visualization.events.removeListener(chart._listener);
  }
  C["chrt" + chartKey] = chart;
  chart.draw(data, google.charts.Bar.convertOptions(options));

  // Allow bar segment click to highlight record in breakdown grid
  chart._listener = google.visualization.events.addListener(chart, "select", function () {
    if (chart.getSelection()[0]) {
      var index = chart.getSelection()[0].row;
      if (index != null) {
        C.gridBreakdown.ActiveDataRowListIndex(recordsFiltered[index]._listIndex);
      }
    }
  });
}

// ================
// Helper Functions
// ================
function PeriodUpdate(period, holdRun) {
  // Initialise
  mPeriod = period;

  // Set selected action (but do not fire events)
  C.blActions.SelectedItemId(period, true);

  // Update Chart actions (but do not fire events)
  if (C.blChartActions.SelectedItemIndex() == -1) {
    C.blChartActions.SelectedItemId("Overall", true);
  }

  // Run
  if(period == "Custom") {
    $("#divCustomPeriod").show();
    mResultsMain = [];
  }
  else {
    $("#divCustomPeriod").hide();
    if (!holdRun) RunMain();
  }
}

function UpdateChartsPanel(delay) {
  // Initialise
  if (mUpdateChartsPanelTimer) {
    window.clearTimeout(mUpdateChartsPanelTimer);
    mUpdateChartsPanelTimer = null;
  }

  // Update
  if (delay) {
    mUpdateChartsPanelTimer = window.setTimeout(UpdateChartsPanel_Done, 750);
  }
  else {
    UpdateChartsPanel_Done();
  }

  // Controls
  C.blChartActions.Visible(!mChartsZoomed);
  if (mChartsZoomed) {
    C.divChart.css({position: "absolute", top: 0, left: 0, right:0, bottom: 0});
    C.divChart.css({"margin-top": "-" + C.blChartActions.Element().outerHeight() + "px"});
  }
  else {
    C.divChart.css({position: "static"});
    C.divChart.css({"margin-top": 0});
  }
}

function UpdateChartsPanel_Done() {
  // Initialise
  mUpdateChartsPanelTimer = null;

  // Get filtered results
  mResultsMainFiltered = C.gridItems.GetVirtualDataForSelectedRows(true);

  // Redraw charts
  blChartActions_Change();
}

// ========
// cboBasis
// ========
function cboBasis_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Re-run report
  RunMain();
}
&lt;/script&gt;


&lt;/body&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>AYeIM1z44k2cGJShJ7rsoA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Accounts Breakdown</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>0</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>true</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>true</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Select the default reporting Basis and Account Statuses to include.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="Basis" 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>Account Type</Value>
            <Visible>true</Visible>
            <List>Account Status,Account Type,Branch,Broker,Dealer,Manager,Monitor Category A,Monitor Category B,Monitor Category C</List>
            <LimitToList>true</LimitToList>
            <MaxLength>12</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountClass" 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>Loan</Value>
            <Visible>true</Visible>
            <List>Loan,Deposit</List>
            <LimitToList>true</LimitToList>
            <MaxLength>12</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountStatuses" type="CheckList">
            <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>Open</Value>
            <Visible>true</Visible>
            <List>Quote,Open,Closed,Closed (Pending),Declined,Unwanted</List>
            <LimitToList>true</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>8</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Other options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>On small mobile devices, "Page" layout will always be used.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="Layout" type="List">
            <BlankTip />
            <Caption>Report Layout</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>Dashboard</Value>
            <Visible>true</Visible>
            <List>Dashboard,Page</List>
            <LimitToList>true</LimitToList>
            <MaxLength>10</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AllowBreakdown" type="Boolean">
            <BlankTip />
            <Caption>Allow User to show a Breakdown?</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="AutoShowBreakdown" type="Boolean">
            <BlankTip />
            <Caption>Automatically show Breakdown when selecting a row?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>1</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Optionally, customise the Columns to display.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Overdue and Contractual columns will only be shown if Accounts and Statuses that support showing these columns are selected, regardless of the selection made below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="Columns" type="GroupingList">
            <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>Balance,Overdue,Contractual</List>
            <GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton>
            <NoIndent>true</NoIndent>
          </Parameter>
          <Parameter name="IncludePrepaidValues" type="Boolean">
            <BlankTip />
            <Caption>Include Prepaid values in Overdue/ Contractual columns?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Specify advanced customisation details.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>An SQL Where Clause can be specified to filter both main and breakdown results.
Always prefix with the table name, e.g.:
[Account].[Region] = 'Wellington'</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="SqlWhere" type="Text">
            <BlankTip />
            <Caption>SQL Where Clause</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>3</Rows>
          </Parameter>
          <Parameter name="CustomReportTitle" type="Text">
            <BlankTip />
            <Caption>Custom Report Title</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>