<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-08-14T00:20:51.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2017-05-22T03:34:06.3370000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2023-08-14T00:20:36.8620000</UpdatedUtcDate>
    <ScriptId>WIDPMS</ScriptId>
    <Description>Promise Management Summary</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category>Management Reports</Category>
    <Code>' HtmlWidget_PromiseManagementSummary
Option Explicit On
Option Strict On

' #################################################################
' Promise Management Summary HTML Widget
'
' Version: 1.08 (14/08/2023)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.07  04/05/2021  ISS
'    1.08  14/08/2023  ISS      J031780   Promise Status added + other
' #################################################################

' Constants
Private Const PERIODS As String = "7 Days,4 Weeks,Last Month,This Month,3 Months,6 Months,This Year,Last Year,Forever"

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

' Other
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")
  End With
  If mColumns.Count = 0 Then mColumns.FromCsvString("Overall Count,Overall Value,Pending Count,Pending Value,Pass Count,Pass Value,Fail Count,Fail Value,Broken Count,Broken Value,Cancelled Count,Cancelled Value")

  ' 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 AllowBreakdown As Boolean
  Dim AutoShowBreakdown As Boolean
  Dim CustomReportTitle As String
  Dim DefaultPeriod As String
  Dim DefaultSortOrder As String
  Dim Html As String
  Dim Layout As String

  ' Initialise
  Html = ScriptInfo.TemplateText

  ' Get Parameters
  With mCombinedParameters
    AllowBreakdown = .GetBoolean("AllowBreakdown", True)
    AutoShowBreakdown = .GetBoolean("AutoShowBreakdown", True)
    CustomReportTitle = .GetString("CustomReportTitle")
    DefaultPeriod = .GetString("DefaultPeriod")
    DefaultSortOrder = Replace(mCombinedParameters.GetString("DefaultSortOrder"), " ", "")
    Layout = .GetString("Layout", "Page")
  End With
  If Len(CustomReportTitle) = 0 Then CustomReportTitle = "Promises"
  If Len(DefaultPeriod) = 0 OrElse DefaultPeriod = "(Auto)" Then DefaultPeriod = GetLatestPeriodWithData()

  ' Replace Tags
  Html = Replace(Html, "&lt;%[AllowBreakdown]%&gt;", LCase(CStr(AllowBreakdown)))
  Html = Replace(Html, "&lt;%[AutoShowBreakdown]%&gt;", LCase(CStr(AutoShowBreakdown)))
  Html = Replace(Html, "&lt;%[Columns]%&gt;", mColumns.ToJsonString())
  Html = Replace(Html, "&lt;%[CustomReportTitle]%&gt;", finBL.Runtime.HtmlUtilities.JavascriptEncode(CustomReportTitle, True))
  Html = Replace(Html, "&lt;%[DefaultSortOrder]%&gt;", DefaultSortOrder)
  Html = Replace(Html, "&lt;%[HasUserFilters]%&gt;", LCase(CStr(finBL.CurrentUserInformation.HasFilterAccount)))
  Html = Replace(Html, "&lt;%[Layout]%&gt;", Layout)
  Html = Replace(Html, "&lt;%[Periods]%&gt;", PERIODS)
  Html = Replace(Html, "&lt;%[Period]%&gt;", DefaultPeriod)

  Return Html

End Function

Private Function GetReportData(ByRef returnValue As String) As Boolean

  Dim Database As ISDatabaseBL
  Dim DateRange As ISDateRange
  Dim DataRow As DataRow
  Dim dt As DataTable
  Dim PromiseStatus As isefinTransactionPromiseStatus
  Dim Record As Record
  Dim Response As ReportResponse
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  Database = finBL.Database

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
  End With

  ' Initialise Response
  Response = New ReportResponse()
  With Response
    .Items = New List(Of Record)
  End With

  ' Build Query
  If Success Then
    sqb = Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "AccountPayArrange"
      .Fields.AddList("AccountPayArrange.CreatedUserPk,AccountTransaction.PromiseStatus,AccountTransaction.PromiseValue")

      ' SQL Where
      AppendSqlWhere(.SqlWhere, DateRange)

      ' Joins
      .Joins.Add("AccountTransaction", "AccountPayArrange.Pk", "AccountTransaction.AccountPayArrangePk", iseSelectQueryJoinType.Inner)
      .Joins.Add("Account", "Account.Pk", "AccountPayArrange.AccountPk", iseSelectQueryJoinType.Inner)

      ' Order By
      .OrderByFields.Add("AccountPayArrange.CreatedUserPk")
    End With
  End If

  ' Execute Query and get Results
  If Success Then
    If sqb.ExecuteDataTable(dt) Then
      For Each DataRow In dt.Rows
        ' Check for existing User Record
        If Response.Items.Count &lt;&gt; 0 AndAlso Response.Items(Response.Items.Count - 1).Pk = Database.GetFieldInteger(DataRow!CreatedUserPk) Then
          Record = Response.Items(Response.Items.Count-1)
        Else
          ' Create new User Record
          Record = New Record()
          With Record
            .Pk = Database.GetFieldInteger(DataRow!CreatedUserPk)
            .Code = finBL.Users.ItemByPk(Database.GetFieldInteger(DataRow!CreatedUserPk)).UserId
            .Description = finBL.Users.ItemByPk(Database.GetFieldInteger(DataRow!CreatedUserPk)).Name
          End With
          Response.Items.Add(Record)
        End If

        ' Add count and amount
        PromiseStatus = DirectCast(Database.GetFieldEnum(DataRow!PromiseStatus, GetType(isefinTransactionPromiseStatus), isefinTransactionPromiseStatus.NotApplicable), isefinTransactionPromiseStatus)

        If PromiseStatus &lt;&gt; isefinTransactionPromiseStatus.NotApplicable Then
          With Record
            .OverallCount += 1
            .OverallValue += Database.GetFieldDecimal(DataRow!PromiseValue)

            Select Case PromiseStatus
              Case isefinTransactionPromiseStatus.Pending
                .PendingCount += 1
                .PendingValue += Database.GetFieldDecimal(DataRow!PromiseValue)

              Case isefinTransactionPromiseStatus.Pass
                .PassCount += 1
                .PassValue += Database.GetFieldDecimal(DataRow!PromiseValue)

              Case isefinTransactionPromiseStatus.Fail
                .FailCount += 1
                .FailValue += Database.GetFieldDecimal(DataRow!PromiseValue)

              Case isefinTransactionPromiseStatus.Broken
                .BrokenCount += 1
                .BrokenValue += Database.GetFieldDecimal(DataRow!PromiseValue)

              Case isefinTransactionPromiseStatus.Cancelled
                .CancelledCount += 1
                .CancelledValue += Database.GetFieldDecimal(DataRow!PromiseValue)
            End Select
          End With
        End If
      Next
    Else
      Success = False
    End If
  End If

  ' Finalise Response
  If Success Then
    With Response
      If Not DateRange.HasValue() Then
        ' Forever
      ElseIf DateRange.ValueFrom &lt;&gt; Nothing AndAlso DateRange.ValueFrom.TimeOfDay &lt;&gt; Nothing Then
        ' Include time
        .FromDateText = "starting " &amp; finBL.FormatDateTimeLong(DateRange.ValueFrom, True)
        .ToDateText = finBL.FormatDateTimeLong(DateRange.ValueTo, True)
      Else
        ' Date only
        If DateRange.ValueFrom &lt;&gt; Nothing Then .FromDateText = "starting " &amp; finBL.FormatDateLong(DateRange.ValueFrom)
        If DateRange.ValueTo &lt;&gt; Nothing Then .ToDateText = "the end of " &amp; finBL.FormatDateLong(DateRange.ValueTo.AddDays(-1))
      End If
    End With
  End If

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

  Return Success

End Function

Private Sub AppendSqlWhere(swb As ISSqlWhereBuilder,
                           ByRef dateRange As ISDateRange)

  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
    SqlWhere = .GetString("SqlWhere")

    If .GetString("Period") = "Custom" Then
      ' Custom  Dates
      dateRange = New ISDateRange(.GetDate("FromDate"), .GetDate("ToDate"))
    Else
      ' Named Range
      dateRange = GetDateRangeFromPeriod(.GetString("Period"))
    End If
  End With

  ' Update SQL Where
  With swb
    ' Date Range
    .AppendDateRange("AccountTransaction.Date", dateRange, False)

    ' 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 BreakdownPk As Integer
  Dim Database As ISDatabaseBL
  Dim DataRowView As DataRowView
  Dim dt As DataTable
  Dim Record As BreakdownRecord
  Dim Response As List(Of BreakdownRecord)
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  Database = finBL.Database

  ' 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")
    BreakdownPk = .GetInteger("BreakdownPk")
  End With

  ' Initialise Response
  Response = New List(Of BreakdownRecord)

  ' 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 = "AccountType"
      .Fields.AddList("AccountType.AccountTypeId,AccountType.Description")
      .Fields.AddList("Account.AccountId,Account.Name,Account.Pk")
      .Fields.AddList("AccountTransaction.PromiseStatus,AccountTransaction.PromiseValue,AccountTransaction.Date")
      .Fields.AddList("AccountPayArrange.ArrangementType")

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

        ' User
        .AppendComparisonInteger("AccountPayArrange.CreatedUserPk", "=", BreakdownPk)
      End With

      ' Joins
      With .Joins
        .Add("Account", "AccountType.Pk", "Account.AccountTypePk")
        .Add("AccountTransaction", "Account.Pk", "AccountTransaction.AccountPk")
        .Add("AccountPayArrange", "AccountPayArrange.Pk", "AccountTransaction.AccountPayArrangePk")
      End With

      ' Order By
      .OrderByFields.AddList("AccountTransaction.PromiseStatus,AccountTransaction.Date,Account.AccountId")
    End With
  End If

  ' Execute Query and get Results
  If Success Then
    If sqb.ExecuteDataTable(dt) Then
      ' Create Record
      For Each DataRowView In dt.DefaultView
        ' Create Record
        Record = New BreakdownRecord()

        ' Add Transactions
        With Record
          .AccountPk = Database.GetFieldInteger(DataRowView!Pk)
          .AccountId = Database.GetFieldString(DataRowView!AccountId)
          .AccountName = Database.GetFieldString(DataRowView!Name)
          .AccountType = Database.GetFieldString(DataRowView!AccountTypeId)
          .AccountTypeDescription = Database.GetFieldString(DataRowView!Description)
          .ArrangementType = Database.GetFieldString(DataRowView!ArrangementType)
          .Status = finBL.Enums.isefinTransactionPromiseStatus_ToString(DirectCast(Database.GetFieldEnum(DataRowView!PromiseStatus, GetType(isefinTransactionPromiseStatus)), isefinTransactionPromiseStatus))
          .TransactionDate = Database.GetFieldDate(DataRowView!Date)
          .Value = Database.GetFieldDecimal(DataRowView!PromiseValue)
        End With

        Response.Add(Record)
      Next
    Else
      Success = False
    End If
  End If

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

  Return Success

End Function

Public Function GetDateRangeFromPeriod(datePeriod As String) As ISDateRange

  Dim DateTemp As Date
  Dim DateRange As ISDateRange
  Dim Today As DateTime

  ' Initialise
  Today = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

  Select Case datePeriod
    Case "7 Days"
      DateRange = New ISDateRange(Today.AddDays(-6), Today.AddDays(1))

    Case "4 Weeks"
      DateRange = New ISDateRange(Today.AddDays(-27), Today.AddDays(1))

    Case "This Month"
      DateRange = New ISDateRange(finBL.Runtime.DateUtilities.BeginningOfMonth(Today), finBL.Runtime.DateUtilities.EndOfMonth(Today).AddDays(1))

    Case "Last Month"
      DateTemp = finBL.Runtime.DateUtilities.EndOfPreviousMonth(Today)
      DateRange = New ISDateRange(finBL.Runtime.DateUtilities.BeginningOfMonth(DateTemp), DateTemp.AddDays(1))

    Case "3 Months"
      DateRange = New ISDateRange(Today.AddMonths(-3).AddDays(1), Today.AddDays(1))

    Case "6 Months"
      DateRange = New ISDateRange(Today.AddMonths(-6).AddDays(1), Today.AddDays(1))

    Case "This Year"
      DateRange = New ISDateRange(New DateTime(Today.Year, 1, 1), New DateTime(Today.Year, 12, 31).AddDays(1))

    Case "Last Year"
      DateRange = New ISDateRange(New DateTime(Today.Year - 1, 1, 1), New DateTime(Today.Year - 1, 12, 31).AddDays(1))

    Case "Forever"
      DateRange = New ISDateRange()

    Case Else
      finBL.Trace.WriteWarning("Unhandled Date Range.")
  End Select

  Return DateRange

End Function

Private Function GetLatestPeriodWithData() As String

  Dim AccountAppStatuses As String
  Dim sqb As ISSelectQueryBuilder
  Dim tempDate As Date

  ' Initialise
  AccountAppStatuses = mCombinedParameters.GetString("AccountAppStatuses")

  sqb = finBL.Database.CreateSelectQueryBuilder()
  With sqb
    .Table = "AccountPayArrange"
    .Fields.AddMax("AccountTransaction.Date")

    ' SQL Where
    AppendSqlWhere(.SqlWhere, Nothing)

    ' Joins
    .Joins.Add("AccountTransaction", "AccountPayArrange.Pk", "AccountTransaction.AccountPayArrangePk", iseSelectQueryJoinType.Inner)
    .Joins.Add("Account", "Account.Pk", "AccountPayArrange.AccountPk", iseSelectQueryJoinType.Inner)

    ' Execute
    If .GetScalarDate(tempDate) AndAlso tempDate &lt;&gt; Nothing Then
      Return GetPeriodFromDate(tempDate)
    Else
      ' Ignore
    End If
  End With

  Return "This Year"

End Function

Public Function GetPeriodFromDate(d As Date) As String

  Dim List As ISList
  Dim s As String

  ' Initialise
  List = New ISList(PERIODS)

  ' Scan Periods
  For Each s In List
    Select Case s
      Case "Forever"
        ' Ignore

      Case Else
        If GetDateRangeFromPeriod(s).IsValueInRange(d) Then
          ' Found
          Return s
        End If
    End Select
  Next

  Return "This Year"

End Function


' Classes
Public Class ReportResponse

  Public FromDateText As String
  Public ToDateText As String
  Public Items As List(Of Record)

End Class

Public Class Record

  Public Pk As Integer
  Public Code As String
  Public Description As String
  Public OverallCount As Integer
  Public OverallValue As Decimal
  Public PendingCount As Integer
  Public PendingValue As Decimal
  Public PassCount As Integer
  Public PassValue As Decimal
  Public FailCount As Integer
  Public FailValue As Decimal
  Public BrokenCount As Integer
  Public BrokenValue As Decimal
  Public CancelledCount As Integer
  Public CancelledValue As Decimal

End Class

Public Class BreakdownRecord

  Public AccountPk As Integer
  Public AccountId As String
  Public AccountName As String
  Public AccountType As String
  Public AccountTypeDescription As String
  Public ArrangementType As String
  Public Status As String
  Public TransactionDate As Date
  Public Value As Decimal

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget to provide a sample Management Dashboard that shows a breakdown of Promises by User.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;head&gt;
&lt;!--Load Google Charts 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;Promises&lt;/h1&gt;

    &lt;div id="blActions"&gt;&lt;/div&gt;
    &lt;div id="divCustomPeriod" style="display:none; margin-top:4px; margin-bottom:4px"&gt;
      &lt;input id="dateFromDate" field-type="date"/&gt;
      &lt;label for="dateToDate"&gt; &lt;small&gt;to&lt;/small&gt; &lt;/label&gt;&lt;input id="dateToDate" field-type="date"/&gt;
      &lt;button id="cmdRunCustom" class="is-button small"&gt;Run&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;div id="divMain" style="max-width:1400px;"&gt;
    &lt;table id="gridItems" class="is-grid is-widget-report" style="width:100%"&gt;
      &lt;thead&gt;
        &lt;tr&gt;
          &lt;th key="ShowBreakdown" data-type="drilldown" style="width:20px" drilldown-glyph="breakdown"&gt;&lt;/th&gt;
          &lt;th key="Code" data-type="html" sortable="true" selectable="false" summary="count" style="width:1em"&gt;User&lt;/th&gt;
          &lt;th key="Description" data-type="string" sortable="true" selectable="false"&gt;Name&lt;/th&gt;
        &lt;/tr&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="divChartOverallCount"&gt;&lt;div id="chrtOverallCount"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartOverallValue"&gt;&lt;div id="chrtOverallValue"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartOverallCountPercent"&gt;&lt;div id="chrtOverallCountPercent"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartOverallValuePercent"&gt;&lt;div id="chrtOverallValuePercent"&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="width:auto"&gt;
        &lt;thead&gt;
          &lt;tr&gt;
            &lt;th key="Status" data-type="string" visible="false" sortable="true" selectable="false"&gt;Status&lt;/th&gt;
            &lt;th key="Account" data-type="code" sortable="true" selectable="false" summary="count" width="8px"&gt;Account&lt;/th&gt;
            &lt;th key="AccountName" data-type="string" sortable="true" selectable="false"&gt;Name&lt;/th&gt;
            &lt;th key="AccountType" data-type="string" sortable="true" selectable="true" width="8px"&gt;Type&lt;/th&gt;
            &lt;th key="ArrangementType" data-type="string" sortable="true" selectable="true" width="8px"&gt;Arrangement&lt;/th&gt;
            &lt;th key="Status" data-type="string" sortable="true" selectable="true" width="8px"&gt;Status&lt;/th&gt;
            &lt;th key="TransactionDate" data-type="date" sortable="true" selectable="false"&gt;Date&lt;/th&gt;
            &lt;th key="Value" data-type="currency" sortable="true" selectable="false" summary="$sum"&gt;Value&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;div&gt;

&lt;/div&gt;


&lt;script&gt;
// Server-side information
var mAllowBreakdown = &lt;%[AllowBreakdown]%&gt;;
var mAutoShowBreakdown = &lt;%[AutoShowBreakdown]%&gt;;
var mColumns = &lt;%[Columns]%&gt;;
var mCustomReportTitle = &lt;%[CustomReportTitle]%&gt;;
var mHasUserFilters = &lt;%[HasUserFilters]%&gt;;
var mLayout = "&lt;%[Layout]%&gt;";
var mPeriods = "&lt;%[Periods]%&gt;".split(",");
var mPeriod = "&lt;%[Period]%&gt;";

// Controls
var C = {
  // Main
  blActions: null,
  dateFromDate: null,
  dateToDate: null,

  lblMainTitle: null,

  gridItems: null,

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

  divChartMain: null,
  chrtMain: null,

  divChartOverallCount: null,
  chrtOverallCount: null,
  divChartOverallValue: null,
  chrtOverallValue: null,
  divChartOverallCountPercent: null,
  chrtOverallCountPercent: null,
  divChartOverallValuePercent: null,
  chrtOverallValuePercent: null,

  divChartBreakdown: null,
  chrtBreakdown: null,

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

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

var mBasisDescription = "User";
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.blActions = widget.UI.ButtonList("blActions", {
    style: "actions",
    onChange: blActions_Change
  });

  C.dateFromDate = widget.UI.DateBox("dateFromDate", {});
  C.dateToDate = widget.UI.DateBox("dateToDate", {});

  C.lblMainTitle = widget.UI.Label("lblMainTitle", {});

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

  C.divChartMain = $("#divChartMain");
  C.divChartOverallCount = $("#divChartOverallCount");
  C.divChartOverallValue = $("#divChartOverallValue");
  C.divChartOverallCountPercent = $("#divChartOverallCountPercent");
  C.divChartOverallValuePercent = $("#divChartOverallValuePercent");
  C.divChartBreakdown = $("#divChartBreakdown");

  C.lblBreakdownTitle = widget.UI.Label("lblBreakdownTitle", {});

  C.divBreakdown = $("#divBreakdown");

  // 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
  for(var i = 0; i &lt; mColumns.length; i++) {
    switch(mColumns[i].toUpperCase()) {
      case "OVERALL COUNT":
        C.gridItems.AddColumnInteger("OverallCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid cyan'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Overall #", colourChart: "cyan"});
        if (!mMainChartFieldId) mMainChartFieldId = "OverallCount";
        break;

      case "OVERALL VALUE":
        C.gridItems.AddColumnCurrency("OverallValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid cyan'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Overall " + widget.CurrencySymbol(), colourChart: "cyan"});
        if (!mMainChartFieldId) mMainChartFieldId = "OverallValue";
        break;

      case "PENDING COUNT":
        C.gridItems.AddColumnInteger("PendingCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid blue'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Pending #", colourChart: "blue"});
        if (!mMainChartFieldId) mMainChartFieldId = "PendingCount";
        break;

      case "PENDING VALUE":
        C.gridItems.AddColumnCurrency("PendingValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid blue'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Pending " + widget.CurrencySymbol(), colourChart: "blue"});
        if (!mMainChartFieldId) mMainChartFieldId = "PendingValue";
        break;

      case "PASS COUNT":
        C.gridItems.AddColumnInteger("PassCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid lime'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Pass #", colourChart: "lime"});
        if (!mMainChartFieldId) mMainChartFieldId = "PassCount";
        break;

      case "PASS VALUE":
        C.gridItems.AddColumnCurrency("PassValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid lime'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Pass " + widget.CurrencySymbol(), colourChart: "lime"});
        if (!mMainChartFieldId) mMainChartFieldId = "PassValue";
        break;

      case "FAIL COUNT":
        C.gridItems.AddColumnInteger("FailCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid red'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Fail #", colourChart: "red"});
        if (!mMainChartFieldId) mMainChartFieldId = "FailCount";
        break;

      case "FAIL VALUE":
        C.gridItems.AddColumnCurrency("FailValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid red'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Fail " + widget.CurrencySymbol(), colourChart: "red"});
        if (!mMainChartFieldId) mMainChartFieldId = "FailValue";
        break;

      case "BROKEN COUNT":
        C.gridItems.AddColumnInteger("BrokenCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid maroon'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Broken  #", colourChart: "maroon"});
        if (!mMainChartFieldId) mMainChartFieldId = "BrokenCount";
        break;

      case "BROKEN VALUE":
        C.gridItems.AddColumnCurrency("BrokenValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid maroon'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Broken " + widget.CurrencySymbol(), colourChart: "maroon"});
        if (!mMainChartFieldId) mMainChartFieldId = "BrokenValue";
        break;

      case "CANCELLED COUNT":
        C.gridItems.AddColumnInteger("CancelledCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid orange'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", summary: "sum", captionChart: "Cancelled  #", colourChart: "orange"});
        if (!mMainChartFieldId) mMainChartFieldId = "CancelledCount";
        break;

      case "CANCELLED VALUE":
        C.gridItems.AddColumnCurrency("CancelledValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid orange'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Cancelled " + widget.CurrencySymbol(), colourChart: "orange"});
        if (!mMainChartFieldId) mMainChartFieldId = "CancelledValue";
        break;
    }
  }
  C.gridItems.SelectedColumnKey(mMainChartFieldId);

  C.gridItems.MergeColumnHeaders("OverallCount,OverallValue","Overall");
  C.gridItems.MergeColumnHeaders("PendingCount,PendingValue","Pending");
  C.gridItems.MergeColumnHeaders("PassCount,PassValue","Pass");
  C.gridItems.MergeColumnHeaders("FailCount,FailValue","Fail");
  C.gridItems.MergeColumnHeaders("BrokenCount,BrokenValue","Broken");
  C.gridItems.MergeColumnHeaders("CancelledCount,CancelledValue","Cancelled");

  // Add optional Breakdown Grid columns
  mBreakdownChartFieldId = "AccountType";
  C.gridBreakdown.SelectedColumnKey(mBreakdownChartFieldId);

  // Define Action buttons
  var buttons = [];
  for(var i = 0; i &lt; mPeriods.length; i++) {
    var period = mPeriods[i];
    buttons.push({ id: period, caption: period });
  }
  buttons.push({ id: "Custom", caption: "Custom" });
  C.blActions.ButtonsDefine(buttons);
  $("#cmdRunCustom").click(RunMain);

  // Define Chart Action buttons
  var chartButtons = [];
  chartButtons.push({ id: "Selected", caption: "Selected" });
  chartButtons.push({ id: "OverallCount", caption: "Count" });
  chartButtons.push({ id: "OverallValue", caption: "Value" });
  chartButtons.push({ id: "OverallCountPercent", caption: "Count (%)" });
  chartButtons.push({ id: "OverallValuePercent", caption: "Value (%)" });
  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");

  // Refresh (but do not run yet since charts are not initalised)
  PeriodUpdate(mPeriod, true);

  // 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();
});

// ===============
// Run Main Report
// ===============
function RunMain() {
  var params = {};

  // Initialise
  mResultsBreakdown = null;
  C.divBreakdown.hide();
  C.lblBreakdownTitle.Visible(false);
  C.gridItems.Sort("", false, true);
  mCurrentUser = -1;

  // Create parameters
  params.period = mPeriod;
  if(mPeriod == "Custom") {
    if(C.dateFromDate.Value() || C.dateToDate.Value()){
      params.fromDate = C.dateFromDate.Value();
      params.toDate = C.dateToDate.Value();
    }
    else {
      widget.UI.MsgBoxAlert("Please enter a valid date in the from and to fields.");
      C.dateFromDate.Focus();
      return;
    }
  }

  // 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
  var dataParsed = JSON.parse(data);
  mResultsMain = dataParsed.Items;
  mResultsMainFiltered = mResultsMain;
  var fromDate = dataParsed.FromDateText;
  var toDate = dataParsed.ToDateText;

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

  // Update title
  var title = mCustomReportTitle + " &lt;small&gt;for period&lt;/small&gt; ";
  mChartTitleMain = mCustomReportTitle;
  mChartTitleSub = "for period ";
  switch(mPeriod) {
    case "Custom":
      if (fromDate &amp;&amp; toDate) {
        title += "&lt;span class='parameter'&gt;" + fromDate + "&lt;/span&gt; &lt;small&gt;to&lt;/small&gt; &lt;span class='parameter'&gt;" + toDate + "&lt;/span&gt;";
        mChartTitleSub += fromDate + " to " + toDate;
      }
      else {
        if (fromDate) {
          title += "&lt;small&gt;from&lt;/small&gt; &lt;span class='parameter'&gt; " + fromDate + "&lt;/span&gt;";
          mChartTitleSub += " from " + fromDate;
        }
        if (toDate) {
          title += "&lt;small&gt;to&lt;/small&gt; &lt;span class='parameter'&gt; " + toDate + "&lt;/span&gt;";
          mChartTitleSub += " to " + toDate;
        }
      }
      C.lblMainTitle.TooltipText("");
      break;

    case "Forever":
      title += "&lt;span class='parameter'&gt;" + mPeriod + "&lt;/span&gt;";
      mChartTitleSub += mPeriod;
      C.lblMainTitle.TooltipText("");
      break;

    default:
      title += "&lt;span class='parameter'&gt;" + mPeriod + "&lt;/span&gt;";
      mChartTitleSub += mPeriod + " (" + fromDate + " to " + toDate + ")";
      C.lblMainTitle.TooltipText("For the period " + fromDate + " to " + toDate);
      break;
  }
  if (mHasUserFilters) title += "&lt;div class='is-info-text warning small'&gt;User Filters have been applied to the results&lt;/div&gt;";
  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;

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

  // Create parameters
  var params = { breakdownPk: mResultsMain[index].Pk, period: mPeriod };
  if(mPeriod == "Custom") {
    if(C.dateFromDate.Value() || C.dateToDate.Value()){
      params.fromDate = C.dateFromDate.Value();
      params.toDate = C.dateToDate.Value();
    }
    else {
      widget.UI.MsgBoxAlert("Please enter a valid date in the from and to fields.");
      C.dateFromDate.Value().Focus();
      return;
    }
  }

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

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

function RunBreakdown_Done(data) {
  // Parse and Save Main Results
  if (data) mResultsBreakdown = JSON.parse(data);
  
  // Show/ Hide grid columns
  var showArrangementType = false;
  for (var i = 0; i &lt; mResultsBreakdown; i++) {
    var item = mResultsBreakdown[i];
    if (item.ArrangementType) showArrangementType = true;
  }
  C.gridBreakdown.ColumnVisible("ArrangementType", showArrangementType);

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

  // Update breakdown title
  if (mResultsMain[mBreakdownIndex].Code) {
    var title = mResultsMain[mBreakdownIndex].Code;
    if (mResultsMain[mBreakdownIndex].Code != mResultsMain[mBreakdownIndex].Description) {
      title += ", " + mResultsMain[mBreakdownIndex].Description;
    }

    // Finalise
    C.lblBreakdownTitle.Text(title);
  }
  else {
    C.lblBreakdownTitle.Text("(No " + mBasisDescription + ")");
  }

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

  // Columns
  e.row.cells.Description.value = item.Description;
  if (e.row.cells.OverallCount != undefined) e.row.cells.OverallCount.value = item.OverallCount;
  if (e.row.cells.OverallValue != undefined) e.row.cells.OverallValue.value = item.OverallValue;
  if (e.row.cells.PendingCount != undefined) e.row.cells.PendingCount.value = item.PendingCount;
  if (e.row.cells.PendingValue != undefined) e.row.cells.PendingValue.value = item.PendingValue;
  if (e.row.cells.PassCount != undefined) e.row.cells.PassCount.value = item.PassCount;
  if (e.row.cells.PassValue != undefined) e.row.cells.PassValue.value = item.PassValue;
  if (e.row.cells.FailCount != undefined) e.row.cells.FailCount.value = item.FailCount;
  if (e.row.cells.FailValue != undefined) e.row.cells.FailValue.value = item.FailValue;
  if (e.row.cells.BrokenCount != undefined) e.row.cells.BrokenCount.value = item.BrokenCount;
  if (e.row.cells.BrokenValue != undefined) e.row.cells.BrokenValue.value = item.BrokenValue;
  if (e.row.cells.CancelledCount != undefined) e.row.cells.CancelledCount.value = item.CancelledCount;
  if (e.row.cells.CancelledValue != undefined) e.row.cells.CancelledValue.value = item.CancelledValue;

  // Row style

  // Cell styles
  e.row.cells.Description.small = true;
}

function gridItems_AfterRowActivate() {
  if (mAutoShowBreakdown) {
    // Run breakdown and explode segment
    RunBreakdown(C.gridItems.ActiveDataRowListIndex());
  }
  else {
    // Explode main chart 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];

  // Columns
  e.row.cells.Status.value = item.Status;
  e.row.cells.Account.value = item.AccountId;
  e.row.cells.AccountName.value = item.AccountName;
  e.row.cells.AccountType.value = item.AccountType;
  e.row.cells.ArrangementType.value = item.ArrangementType;
  e.row.cells.Status.value = item.Status;
  e.row.cells.TransactionDate.value = item.TransactionDate;
  e.row.cells.Value.value = item.Value;

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

  // Cell styles
  e.row.cells.AccountName.small = true;
}

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

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

// =========
// blActions
// =========
function blActions_Change(sender, e) {
  PeriodUpdate(C.blActions.SelectedItemId());
}

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

  // Update Chart action captions
  var c = C.gridItems.SelectedColumn();
  if (c) {
    C.blChartActions.ButtonCaption("Selected", "&lt;HTML&gt;&lt;span style='border-bottom:2px solid " + c.colourChart + "'&gt;" + widget.UI.HtmlEncode(c.captionChart) + "&lt;/span&gt;");
  }
  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 "OverallCount":
        // Overall Count Bar Chart
        C.divChartOverallCount.show();
        CreateBarChart(mResultsMain, mResultsMainFiltered, "chrtOverallCount", "Count");
        break;

      case "OverallValue":
        // Overall Value Bar Chart
        C.divChartOverallValue.show();
        CreateBarChart(mResultsMain, mResultsMainFiltered, "chrtOverallValue", "Value");
        break;

      case "OverallCountPercent":
        // Overall Count (%) Bar Chart
        C.divChartOverallCountPercent.show();
        CreateBarChart(mResultsMain, mResultsMainFiltered, "chrtOverallCountPercent", "Count", true);
        break;

      case "OverallValuePercent":
        // Overall Value (%) Bar Chart
        C.divChartOverallValuePercent.show();
        CreateBarChart(mResultsMain, mResultsMainFiltered, "chrtOverallValuePercent", "Value", true);
        break;

      case "BreakdownSelected":
        // Breakdown (Selected) Pie Chart
        var chartData = [];

        for (var i = 0; i &lt; mResultsBreakdown.length; i++) {
          var item = mResultsBreakdown[i];
          var code = item[mBreakdownChartFieldId] || "";

          // Add/ locate record
          var record = null;
          for (var j = 0; j &lt; chartData.length; j++) {
            if (chartData[j].Code == code) {
              record = chartData[j];
              record.Value += 1;
              break;
            }
          }
          if (!record) {
            record = { Code: code, Value: 1 };
            chartData.push(record);
          }
        }

        C.divChartBreakdown.show();
        CreatePieChart(chartData, chartData, "chrtBreakdown", "Breakdown", "Value", -999);
        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 (either Count or Value based), optionally as a percentage
// ==========================================================================
function CreateBarChart(records, recordsFiltered, chartDivId, chartBasis, percentage) {
  // Initialise
  var chartKey = chartBasis + (percentage ? "Percent" : "");
  var chart = C["chrtOverall" + chartKey];
  var chartDiv = C["divChartOverall" + chartKey];
  var dt = [];

  // Create data table header row
  // NOTE: Assumes text column names match the key (once spaces are removed) which also matches the property on each data row
  var headerRow = [mBasisDescription];
  var dataKeys = [];
  var series = {};
  var seriesCounter = 0;

  for(var i = 0; i &lt; mColumns.length; i++) {
    var key = mColumns[i].replace(/\s+/g, "");
    var c = C.gridItems.GetColumnByKey(key);

    if (c &amp;&amp; key.endsWith(chartBasis) &amp; !key.startsWith("Overall")) {
      dataKeys.push(key);
      headerRow.push(c.captionChart);
      series[seriesCounter] = { color: c.colourChart };
      seriesCounter += 1;
    }
  }
  dt.push(headerRow);

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

    for (var i = 0; i &lt; dataKeys.length; i++) {
      var key = dataKeys[i];
      row.push(item[key]);
      rowTotal += item[key];
    }

    // Percentage (Google Material Charts do not currently natively support this)
    if (percentage) {
      var factor = 100.0 / rowTotal;
      var newTotal = 0;
      for(var i = 1; i &lt; row.length; i++) {
        row[i] *= factor;
        newTotal += row[i];
      }

      // Handle rounding issues
      if (newTotal != 100) {
        row[row.length - 1] += (newTotal - 100);
      }
    }

    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: (chartBasis == "Value" ? "decimal" : "#"), textStyle: {fontSize: 10}},
                  vAxes: { 0: { title: chartBasis + (percentage ? " (%)": ""), viewWindow: { }, textStyle: {fontSize: 10.5}}},
                };

  // Zoomed chart options
  if (mChartsZoomed) {
    var tabCaption = C.blChartActions.ButtonCaption(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["chrtOverall" + chartKey] = chart;
  chart.draw(data, google.charts.Bar.convertOptions(options));

  // Allow bar segment click to highlight record in main grid
  chart._listener = google.visualization.events.addListener(chart, "select", function () {
    var index = chart.getSelection()[0].row;

    if (index != null) {
      C.gridItems.ActiveDataRowListIndex(recordsFiltered[index]._listIndex);
    }
  });
}

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

  // Set selected action
  C.blActions.SelectedItemId(period);

  // 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();
}
&lt;/script&gt;

&lt;/body&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>aejN9wkjakOC14in8Zrprw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Promise Management Summary</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <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 Period and Sort Order.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DefaultPeriod" type="List">
            <BlankTip />
            <Caption>Default Period</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>Last Month</Value>
            <Visible>true</Visible>
            <List>(Auto),7 Days,4 Weeks,Last Month,This Month,3 Months,6 Months,This Year,Last Year,Forever</List>
            <LimitToList>true</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DefaultSortOrder" type="List">
            <BlankTip />
            <Caption>Default Sort Order</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>Overall Count</Value>
            <Visible>true</Visible>
            <List>Overall Count,Overall Value,Pending Count,Pending Value,Pass Count,Pass Value,Fail Count,Fail Value,Broken Count,Broken Value,Cancelled Count,Cancelled Value</List>
            <LimitToList>true</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</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 Columns to show.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <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>Overall Count,Overall Value,Pending Count,Pending Value,Pass Count,Pass Value,Fail Count,Fail Value,Broken Count,Broken Value,Cancelled Count,Cancelled Value</List>
            <GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton>
            <NoIndent>true</NoIndent>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>