<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-03-24T02:57:41.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-07-19T20:59:55.1430000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-03-24T02:56:06.9630000</UpdatedUtcDate>
    <ScriptId>APPMONCATCHANGE</ScriptId>
    <Description>Account Application Monitor Category Change</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' HtmlWidget_AccountAppMonitorCategoryChange
Option Explicit On
Option Strict On

' #################################################################
' Account Application Monitor Category Change wizard HTML Widget
'
' Version: 1.07 (24/03/2022)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.06  24/08/2021  ISS                Updated
'    1.07  24/03/2022  ISS      J026428   Final message no longer hidden behind block
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountAppMonitorCategoryChange"

' Common Parameters
Private mAccountAppId As String
Private mAccountMonitorCategory As isefinAccountMonitorCategory
Private mAccountMonitorCategoryText As String
Private mClear As Boolean
Private mShowHistory As Boolean

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

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

  ' Assume Success
  Main = True

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

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

  ' Get Common Parameters
  With mCombinedParameters
    mAccountAppId = .GetString("AccountAppId")
    If Len(mAccountAppId) = 0 Then mAccountAppId = .GetString("Id") ' Compatibility with finPOWER Connect desktop parameters
    mClear = .GetBoolean("Clear")
    mShowHistory = .GetBoolean("ShowHistory")
    mAccountMonitorCategoryText = .GetString("AccountMonitorCategory")
    Select Case UCase(mAccountMonitorCategoryText)
      Case "A": mAccountMonitorCategory = isefinAccountMonitorCategory.CategoryA
      Case "B": mAccountMonitorCategory = isefinAccountMonitorCategory.CategoryB
      Case "C": mAccountMonitorCategory = isefinAccountMonitorCategory.CategoryC
    End Select
  End With

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

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

    Case "Form_DateEffective_Change"
      ' Get updated form information based on Date Effective change
      Main = Form_DateEffective_Change(returnValue)

    Case "GetHistory"
      ' Get History records
      Main = GetHistory(returnValue)

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

    Case "HistoryItem_Cancel"
      ' Cancel a History Item
      Main = HistoryItem_Cancel(returnValue)

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

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

End Function

''' &lt;summary&gt;
'''  Get updated form information based on Date Effective change.
''' &lt;/summary&gt;
Public Function Form_DateEffective_Change(ByRef response As String) As Boolean

  Dim AccountAppMonitorCategoryChange As finAccountAppMonitorCategoryChange
  Dim DateEffective As Date
  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    DateEffective = .GetDatabaseDateFromJsonUtcDate("date")
  End With

  ' Create AccountApp Monitor Category Change object
  If Success Then
    Success = CreateAccountAppMonitorCategoryChange(Nothing, AccountAppMonitorCategoryChange)
  End If

  ' Get Monitor Categories
  If Success Then
    Success =  AccountAppMonitorCategoryChange.GetMonitorCategories(DateEffective)
  End If

  ' Create Response
  If Success Then
    obj = New With {
      .MonitorCategoryAId = AccountAppMonitorCategoryChange.MonitorCategoryAId,
      .MonitorCategoryAFutureChange = AccountAppMonitorCategoryChange.MonitorCategoryAFutureChange,
      .MonitorCategoryBId = AccountAppMonitorCategoryChange.MonitorCategoryBId,
      .MonitorCategoryBFutureChange = AccountAppMonitorCategoryChange.MonitorCategoryBFutureChange,
      .MonitorCategoryCId = AccountAppMonitorCategoryChange.MonitorCategoryCId,
      .MonitorCategoryCFutureChange = AccountAppMonitorCategoryChange.MonitorCategoryCFutureChange
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get History records.
''' &lt;/summary&gt;
Public Function GetHistory(ByRef response As String) As Boolean

  Dim AccountApp As finAccountApp
  Dim AccountAppHistoryItem As finAccountAppHistoryItem
  Dim HistoryItems As List(Of HistoryItem)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  HistoryItems = New List(Of HistoryItem)

  ' Load Account
  If Success Then
    AccountApp = finBL.CreateAccountApp()
    Success = AccountApp.Load(mAccountAppId)
  End If

  ' Get History Items
  If Success Then
    For Each AccountAppHistoryItem In AccountApp.HistoryItems.GetItemsByHistoryType(isefinAccountAppHistoryType.MonitorCategoryChange)
      HistoryItems.Add(New HistoryItem(finBL, AccountAppHistoryItem))
    Next

    ' Sort (so grid automatically groups by Category and then Date)
    HistoryItems.Sort(AddressOf HistoryItems_SortComparer)
  End If

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

  Return Success

End Function

Private Function HistoryItems_SortComparer(x As HistoryItem,
                                           y As HistoryItem) As Integer

  If x.Category &gt; y.Category Then
    Return 1
  ElseIf x.Category &lt; y.Category Then
    Return -1
  Else
    If x.Date = y.Date Then
      If x.Pk &lt; y.Pk Then
        Return -1
      ElseIf x.Pk &gt; y.Pk Then
        Return 1
      Else
        Return 0
      End If
    Else
      Return Date.Compare(x.Date, y.Date)
    End If
  End If

End Function

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

  Dim AccountAppMonitorCategoryChange As finAccountAppMonitorCategoryChange
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If Len(mAccountAppId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account App Id not specified.")
  ElseIf finBL.CurrentUserInformation.IsAccountAppFilteredOut(mAccountAppId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this record.")
  ElseIf Not finBL.Settings.MonitorCategoriesUsedAccountApp Then
    Success = False
    finBL.Error.ErrorBegin("Monitor Categories are not used by Account Applications.")
  End If

  ' Validate Monitor Category
  If Success Then
    Select Case UCase(mAccountMonitorCategoryText)
      Case "A", "B", "C"
        ' Ok

      Case ""
        Success = False
        finBL.Error.ErrorBegin("Monitor Category not specified.")

      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Invalid Monitor Category '{0}'.", mAccountMonitorCategoryText)
    End Select
  End If

  ' Validate Categories in use
  If Success Then
    Select Case mAccountMonitorCategory
      Case isefinAccountMonitorCategory.CategoryA
        If Not finBL.Settings.MonitorCategoryAUseAccountApp Then
          Success = False
          finBL.Error.ErrorBegin("Monitor Category A is not used by Account Applications.")
        End If

      Case isefinAccountMonitorCategory.CategoryB
        If Not finBL.Settings.MonitorCategoryBUseAccountApp Then
          Success = False
          finBL.Error.ErrorBegin("Monitor Category B is not used by Account Applications.")
        End If

      Case isefinAccountMonitorCategory.CategoryC
        If Not finBL.Settings.MonitorCategoryCUseAccountApp Then
          Success = False
          finBL.Error.ErrorBegin("Monitor Category C is not used by Account Applications.")
        End If
    End Select
  End If

  ' Create AccountApp Monitor Category Change object
  If Success Then
    Success = CreateAccountAppMonitorCategoryChange(Nothing, AccountAppMonitorCategoryChange)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      .RecordId = AccountAppMonitorCategoryChange.AccountApp.AccountAppId
      .RecordDescription = AccountAppMonitorCategoryChange.AccountApp.Name

      ' General
      .DateEffective = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountAppMonitorCategoryChange.DateEffective)

      .MonitorCategoryAFutureChange = AccountAppMonitorCategoryChange.MonitorCategoryAFutureChange
      .MonitorCategoryAId = AccountAppMonitorCategoryChange.MonitorCategoryAId
      .MonitorCategoryAUpdate = (mAccountMonitorCategory = isefinAccountMonitorCategory.CategoryA)
      .MonitorCategoryAUse = finBL.Settings.MonitorCategoryAUseAccountApp

      .MonitorCategoryBFutureChange = AccountAppMonitorCategoryChange.MonitorCategoryBFutureChange
      .MonitorCategoryBId = AccountAppMonitorCategoryChange.MonitorCategoryBId
      .MonitorCategoryBUpdate = (mAccountMonitorCategory = isefinAccountMonitorCategory.CategoryB)
      .MonitorCategoryBUse = finBL.Settings.MonitorCategoryBUseAccountApp

      .MonitorCategoryCFutureChange = AccountAppMonitorCategoryChange.MonitorCategoryCFutureChange
      .MonitorCategoryCId = AccountAppMonitorCategoryChange.MonitorCategoryCId
      .MonitorCategoryCUpdate = (mAccountMonitorCategory = isefinAccountMonitorCategory.CategoryC)
      .MonitorCategoryCUse = finBL.Settings.MonitorCategoryCUseAccountApp

      ' Clear?
      If mClear Then
        .Clear = True

        Select Case mAccountMonitorCategory
          Case isefinAccountMonitorCategory.CategoryA
            .MonitorCategoryAId = ""
            .ClearDescription = finBL.Settings.MonitorCategoryADescriptionResolved

          Case isefinAccountMonitorCategory.CategoryB
            .MonitorCategoryBId = ""
            .ClearDescription = finBL.Settings.MonitorCategoryBDescriptionResolved

          Case isefinAccountMonitorCategory.CategoryC
            .MonitorCategoryCId = ""
            .ClearDescription = finBL.Settings.MonitorCategoryCDescriptionResolved
        End Select
      End If

      ' Account Summary
      .AccountAppSummaryHtml = finBL.Utilities.GetHtmlFromSummaryTables(finBL.SummaryPageStandardBlocks().AccountApp_Monitoring(ScriptInfo, AccountAppMonitorCategoryChange.AccountApp, False, False, Nothing), "", False, "", ScriptInfo.Target, "Existing Monitor Categories")

      ' Lists

      ' Other
      .MonitorCategoryADescription = finBL.Settings.MonitorCategoryADescriptionResolved
      .MonitorCategoryBDescription = finBL.Settings.MonitorCategoryBDescriptionResolved
      .MonitorCategoryCDescription = finBL.Settings.MonitorCategoryCDescriptionResolved

      ' Configuration
      .AlwaysShowAdvanced = mCombinedParameters.GetBoolean("AlwaysShowAdvanced", False)
      .CanRevise = Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryRevise") AndAlso (finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryAUpdate") OrElse finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryBUpdate") OrElse finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryCUpdate"))
      .CanViewHistory = finBL.CurrentUser.Permissions.Allow("AccountApp.Form.Page.Status") ' NOTE: This is as per the Summary Page standard block and is not standard
      .MonitorCategoryACanUpdate = .CanRevise AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryAUpdate")
      .MonitorCategoryBCanUpdate = .CanRevise AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryBUpdate")
      .MonitorCategoryCCanUpdate = .CanRevise AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryCUpdate")
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      If .CanRevise Then
        .ShowHistory = mShowHistory
      Else
        .ShowHistory = True
      End If

      ' Validate
      If Not(.CanRevise OrElse .CanViewHistory) Then
        Success = False
        finBL.Error.ErrorBegin("You do not have permission to either view or change Account Application Monitor Category details.")
      End If
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Cancel a History Item.
''' &lt;/summary&gt;
Public Function HistoryItem_Cancel(ByRef response As String) As Boolean

  Dim AccountApp As finAccountApp
  Dim HistoryItems As List(Of HistoryItem)
  Dim Pk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  HistoryItems = New List(Of HistoryItem)

  ' Get Parameters
  With mCombinedParameters
    Pk = .GetInteger("pk")
  End With

  ' Load Account
  If Success Then
    AccountApp = finBL.CreateAccountApp()
    Success = AccountApp.Load(mAccountAppId)
  End If

  ' Cancel
  If Success Then
    Success = finBL.AccountAppFunctions.HistoryMonitorCategoryCancel(AccountApp.Pk, Pk)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create Context Data for Scripts.
''' &lt;/summary&gt;
Private Function CreateScriptContextData() As ISKeyValueList

  CreateScriptContextData = finBL.CreateKeyValueList()
  With CreateScriptContextData
    .SetObject("Target", ScriptInfo.Target)
    .SetBoolean("HighDpi", finBL.HighDpi)
    .SetString("FormKey", FORM_KEY)
    .SetString("FormRecordMode", iseFormRecordMode.Loaded.ToString())
  End With

End Function

''' &lt;summary&gt;
'''  Create a finAccountAppMonitorCategoryChange object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountAppMonitorCategoryChange(parameters As WizardFinishParameters,
                                                       ByRef accountAppMonitorCategoryChange As finAccountAppMonitorCategoryChange) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountAppMonitorCategoryChange = finBL.CreateAccountAppMonitorCategoryChange()

  ' Update
  With accountAppMonitorCategoryChange
    ' Load Account
    Success = .AccountAppLoad(mAccountAppId)

    ' Update
    If Success AndAlso parameters IsNot Nothing Then
      ' General
      .DateEffective = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateEffective)
      .MonitorCategoryAUpdate = parameters.MonitorCategoryAUpdate
      .MonitorCategoryAId = parameters.MonitorCategoryAId
      .MonitorCategoryBUpdate = parameters.MonitorCategoryBUpdate
      .MonitorCategoryBId = parameters.MonitorCategoryBId
      .MonitorCategoryCUpdate = parameters.MonitorCategoryCUpdate
      .MonitorCategoryCId = parameters.MonitorCategoryCId
      .Notes = parameters.Notes
      .Reference = parameters.Reference
    End If
  End With

  Return Success

End Function

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

  Dim AccountAppMonitorCategoryChange As finAccountAppMonitorCategoryChange
  Dim obj As Object
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create AccountApp Monitor Category Change object
  If Success Then
    Success = CreateAccountAppMonitorCategoryChange(WizardFinishParameters, AccountAppMonitorCategoryChange)
  End If

  ' Execute
  If Success Then
    Success = AccountAppMonitorCategoryChange.ExecuteCommit(Warning)
  End If

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

  Return Success

End Function


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

  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate Page
  Select Case PageId
  End Select

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

  Return Success

End Function



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

  ' Record
  Public RecordId As String
  Public RecordDescription As String

  ' Details
  Public DateEffective As Date

  Public MonitorCategoryAFutureChange As Boolean
  Public MonitorCategoryAId As String
  Public MonitorCategoryAUpdate As Boolean
  Public MonitorCategoryAUse As Boolean

  Public MonitorCategoryBFutureChange As Boolean
  Public MonitorCategoryBId As String
  Public MonitorCategoryBUpdate As Boolean
  Public MonitorCategoryBUse As Boolean

  Public MonitorCategoryCFutureChange As Boolean
  Public MonitorCategoryCId As String
  Public MonitorCategoryCUpdate As Boolean
  Public MonitorCategoryCUse As Boolean

  ' Account Summary
  Public AccountAppSummaryHtml As String

  ' Lists

  ' Configuration
  Public AlwaysShowAdvanced As Boolean
  Public CanRevise As Boolean
  Public CanViewHistory As Boolean
  Public Clear As Boolean
  Public ClearDescription As String
  Public MonitorCategoryACanUpdate As Boolean
  Public MonitorCategoryBCanUpdate As Boolean
  Public MonitorCategoryCCanUpdate As Boolean
  Public MonitorCategoryADescription As String
  Public MonitorCategoryBDescription As String
  Public MonitorCategoryCDescription As String
  Public PromptOnCommit As Boolean
  Public ShowHistory As Boolean

End Class


''' &lt;summary&gt;
'''  History item.
''' &lt;/summary&gt;
Public Class HistoryItem

  Public CanCancel As Boolean
  Public Cancelled As Boolean
  Public Category As String
  Public Colour As String
  Public [Date] As Date
  Public Description As String
  Public Notes As String
  Public Pk As Integer
  Public Reference As String
  Public UserId As String

  Public Sub New (finBL As ISfinSupport,
                  accountAppHistoryItem As finAccountAppHistoryItem)

    With accountAppHistoryItem
      Me.CanCancel = .CanCancel()
      Me.Cancelled = (.Status = isefinAccountAppHistoryStatus.Cancelled)
      Me.Date = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.Date)
      Me.Description = .MonitorCategoryId
      Me.Notes = .Notes
      Me.Pk = .Pk
      Me.Reference = .Reference
      Me.UserId = .CreatedUserId

      ' Account Monitor Category
      Select Case .AccountMonitorCategory
        Case isefinAccountMonitorCategory.CategoryA: Me.Category = "A"
        Case isefinAccountMonitorCategory.CategoryB: Me.Category = "B"
        Case isefinAccountMonitorCategory.CategoryC: Me.Category = "C"
      End Select

      ' Description
      Me.Description = .MonitorCategoryId

      ' Colour
      If finBL.MonitorCategories.ExistsPk(accountAppHistoryItem.MonitorCategoryPk) Then
        Me.Colour = finBL.MonitorCategories.ItemByPk(accountAppHistoryItem.MonitorCategoryPk).ColourBackground
      End If
    End With

  End Sub

End Class


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

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

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

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

  End Sub

End Class


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

  ' General
  Public DateEffective As Date?
  Public MonitorCategoryAUpdate As Boolean
  Public MonitorCategoryAId As String
  Public MonitorCategoryBUpdate As Boolean
  Public MonitorCategoryBId As String
  Public MonitorCategoryCUpdate As Boolean
  Public MonitorCategoryCId As String
  Public Notes As String
  Public Reference As String

End Class


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

  ' General
  Public Warning As String

  Public Sub New(warning As String)

    Me.Warning = warning

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountAppMonitorCategoryChange".</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="History"&gt;Monitor Category Change History&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Specify new Monitor Category details for the Account Application."&gt;Monitor Category Details&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- History --&gt;
    &lt;div id="pageHistory"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="gridHistory" style="height:100%"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col style="width:100em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="3"&gt;&lt;label id="lblAccountApp"&gt;Account Application&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRecord"&gt;Application:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="cboRecord" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="3"&gt;&lt;label id="lblEffective"&gt;Enter the Effective date and a Reference for the change&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateEffective"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="dateEffective"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="txtReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="txtNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="3"&gt;&lt;label id="lblMonitorCategoryDetails"&gt;Specify Monitor Category changes&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;

        &lt;tr class="advanced"&gt;
          &lt;th colspan="3"&gt;&lt;input id="chkMonitorCategoryAUpdate" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr style="vertical-align:top" class="advanced"&gt;
          &lt;th class="indent1"&gt;&lt;button id="cmdClearA" class="is-button icon small" icon="Clear"&gt;Clear&lt;/button&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="cboMonitorCategoryA" /&gt;&lt;div id="divWarningA" class="is-info-text warning small" style="display:none; padding-left:4px;"&gt;WARNING: Future changes exist&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr class="advanced"&gt;
          &lt;th colspan="3"&gt;&lt;input id="chkMonitorCategoryBUpdate" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr style="vertical-align:top" class="advanced"&gt;
          &lt;th class="indent1"&gt;&lt;button id="cmdClearB" class="is-button icon small" icon="Clear"&gt;Clear&lt;/button&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="cboMonitorCategoryB" /&gt;&lt;div id="divWarningB" class="is-info-text warning small" style="display:none; padding-left:4px;"&gt;WARNING: Future changes exist&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr class="advanced"&gt;
          &lt;th colspan="3"&gt;&lt;input id="chkMonitorCategoryCUpdate" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr style="vertical-align:top" class="advanced"&gt;
          &lt;th class="indent1"&gt;&lt;button id="cmdClearC" class="is-button icon small" icon="Clear"&gt;Clear&lt;/button&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="cboMonitorCategoryC" /&gt;&lt;div id="divWarningC" class="is-info-text warning small" style="display:none; padding-left:4px;"&gt;WARNING: Future changes exist&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr style="height:100%"&gt;
          &lt;th colspan="3" style="height:100%; padding-top:8px"&gt;&lt;div id="wbAccountAppSummary" class="is-dock-fill"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdHistory" class="is-button" style="float:left"&gt;History&lt;/button&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

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

&lt;/div&gt;



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

// Controls
var C = {
  //   History
  gridHistory: null,

  //   General
  lblAccountApp: null,
  cboRecord: null,

  lblEffective: null,
  dateEffective: null,
  txtReference: null,
  txtNotes: null,

  lblMonitorCategoryDetails: null,
  chkMonitorCategoryAUpdate: null,
  cboMonitorCategoryA: null,
  divWarningA: null,
  chkMonitorCategoryBUpdate: null,
  cboMonitorCategoryB: null,
  divWarningB: null,
  chkMonitorCategoryCUpdate: null,
  cboMonitorCategoryC: null,
  divWarningC: null,

  wbAccountAppSummary: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;
var cmdAdvanced;
var cmdClearA;
var cmdClearB;
var cmdClearC;

// Other
var mAdvancedVisible = false;
var mHasAdvancedOptions = false;
var mRefreshRequired = false;

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

  // --------
  // Controls
  // --------
  //   General
  C.lblAccountApp = widget.UI.Label("lblAccountApp", {});
  C.cboRecord = widget.UI.DBCombo("cboRecord", {
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10
  });

  C.lblEffective = widget.UI.Label("lblEffective", {});
  C.dateEffective = widget.UI.DateBox("dateEffective", {
    allowBlank: false,
    onChange: dateEffective_Change,
  });
  C.txtReference = widget.UI.TextBox("txtReference", {
    maxLength: 20
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 3,
  });

  C.lblMonitorCategoryDetails = widget.UI.Label("lblMonitorCategoryDetails", {});
  C.chkMonitorCategoryAUpdate = widget.UI.CheckBox("chkMonitorCategoryAUpdate", {
    caption: "Update A?",
    onChange: chkMonitorCategoryAUpdate_Change,
  });
  C.cboMonitorCategoryA = widget.UI.DBCombo("cboMonitorCategoryA", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.divWarningA = $("#divWarningA");

  C.chkMonitorCategoryBUpdate = widget.UI.CheckBox("chkMonitorCategoryBUpdate", {
    caption: "Update B?",
    onChange: chkMonitorCategoryBUpdate_Change,
  });
  C.cboMonitorCategoryB = widget.UI.DBCombo("cboMonitorCategoryB", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.divWarningB = $("#divWarningB");

  C.chkMonitorCategoryCUpdate = widget.UI.CheckBox("chkMonitorCategoryCUpdate", {
    caption: "Update C?",
    onChange: chkMonitorCategoryCUpdate_Change,
  });
  C.cboMonitorCategoryC = widget.UI.DBCombo("cboMonitorCategoryC", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.divWarningC = $("#divWarningC");

  C.wbAccountAppSummary = widget.UI.PreviewPane("wbAccountAppSummary", {});

  // Grids
  C.gridHistory = widget.UI.Grid("gridHistory", {
    stickyHeader: true,
    groupByColumns: "Category",
    onInitialiseRow: gridHistory_InitialiseRow,
    onAfterRowActivate: gridHistory_AfterRowActivate,
    onAction: gridHistory_Action,
  });

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

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

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

  cmdHistory = $("#cmdHistory");
  cmdHistory.click(function() { Form_ExecuteAction("History"); });

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

  cmdClearA = $("#cmdClearA");
  cmdClearA.click(function() { C.cboMonitorCategoryA.Text(""); C.chkMonitorCategoryAUpdate.Value(true); chkMonitorCategoryAUpdate_Change(); });
  cmdClearB = $("#cmdClearB");
  cmdClearB.click(function() { C.cboMonitorCategoryB.Text(""); C.chkMonitorCategoryBUpdate.Value(true); chkMonitorCategoryBUpdate_Change(); });
  cmdClearC = $("#cmdClearC");
  cmdClearC.click(function() { C.cboMonitorCategoryC.Text(""); C.chkMonitorCategoryCUpdate.Value(true); chkMonitorCategoryCUpdate_Change(); });

  // Reset
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

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

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

      // Clear
      if (mRecord.Clear) {
        var message = "Are you sure you want to clear '" + mRecord.ClearDescription + "' Monitoring for this Account Application?\n\nNOTE: Click 'Cancel' to enter notes or other information prior to clearing.";
        widget.UI.MsgBoxConfirm(message, { heading: "Clear Monitor Category" }, Form_ExecuteAction_FinishPost, null);
      }
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboRecord.RefreshUnbound(mRecord.RecordId, mRecord.RecordDescription);

    C.dateEffective.Value(mRecord.DateEffective);

    C.chkMonitorCategoryAUpdate.Value(mRecord.MonitorCategoryAUpdate);
    C.cboMonitorCategoryA.Text(mRecord.MonitorCategoryAId);

    C.chkMonitorCategoryBUpdate.Value(mRecord.MonitorCategoryBUpdate);
    C.cboMonitorCategoryB.Text(mRecord.MonitorCategoryBId);

    C.chkMonitorCategoryCUpdate.Value(mRecord.MonitorCategoryCUpdate);
    C.cboMonitorCategoryC.Text(mRecord.MonitorCategoryCId);

    C.wbAccountAppSummary.SetContent(mRecord.AccountAppSummaryHtml, false);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Not used by this wizard since there is no concept of updating an object behind the wizard
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Information Lists

  // Lists
  if (mRecord) {
    C.cboMonitorCategoryA.RefreshFromStandardRange("MonitorCategoriesAccountAppsA");
    C.cboMonitorCategoryB.RefreshFromStandardRange("MonitorCategoriesAccountAppsB");
    C.cboMonitorCategoryC.RefreshFromStandardRange("MonitorCategoriesAccountAppsC");
  }

  // Controls
  if (mRecord) {
    dateEffective_Change_Done();

    // Show/ hide Advanced
    mAdvancedVisible = mRecord.AlwaysShowAdvanced;
    mHasAdvancedOptions = !mRecord.AlwaysShowAdvanced;
    pageGeneral_Refresh();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Show History
  if (mRecord) {
    if (mRecord.CanViewHistory &amp;&amp; mRecord.ShowHistory) {
      Form_ExecuteAction("History");
    }
  }

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

function tabWizard_UpdateButtons() {
  var VisibleTabCount = tabWizard.TabCount();
  if (mRecord) {
    if (!mRecord.CanViewHistory) VisibleTabCount -= 1;
    if (!mRecord.CanRevise) VisibleTabCount -= 1;
  }

  // History Button
  var tabIndex = tabWizard.SelectedTabIndex();
  if (tabIndex == 0 || (mRecord &amp;&amp; !mRecord.CanViewHistory)) {
    cmdHistory.hide();
  }
  else {
    cmdHistory.show();
  }

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

  // Finish Button
  if (mRecord &amp;&amp; !mRecord.CanRevise) {
    cmdCancel.hide();
    cmdFinish.text("Close");
  }
  else {
    if (VisibleTabCount != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
  }

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "History":
      break;

    case "General":
      C.txtReference.WidthResizeFromParent();
      C.txtNotes.WidthResizeFromParent(true);
      C.wbAccountAppSummary.ResizeFromParent();
      break;

    default:
      break;
  }
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

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

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

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

        // Refresh (e.g., history item cancelled)
        if (mRefreshRequired) {
          dateEffective_Change();
        }
        break;

      default:
        break;
    }
  }

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "History":
      // Load History (we move back to this page, not forward!)
      if (!mRecord_History) {
        gridHistory_Refresh();
      }
      else {
        // Refresh (e.g., to show hidden rows)
        C.gridHistory.VirtualDataRefresh(mRecord_History);

        // Activate Last Row
        C.gridHistory.ActivateLastDataRow();
      }
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "History":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Monitor Category Change History for Account Application '" + mRecord.RecordId + "', " + mRecord.RecordDescription + ".");
      break;

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

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

  // Resize Wizard
  tabWizard_Resize();

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

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (!C.chkMonitorCategoryAUpdate.Value() &amp;&amp;
            !C.chkMonitorCategoryBUpdate.Value() &amp;&amp;
            !C.chkMonitorCategoryCUpdate.Value()) {
          Ok = false;
          widget.UI.MsgBoxAlert("You must select a Monitor Category to update.");
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
    }

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

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

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

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

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

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      if (mRecord.CanRevise) {
        Form_ExecuteAction_Finish();
      }
      else {
        tabWizard_Cancel();
      }
      break;

    case "HISTORY":
      // Show History page
      tabWizard_Refresh(0);
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mRecord.PromptOnCommit) {
      // Confirm
      var heading;
      var message;
      var count = 0;

      if (C.chkMonitorCategoryAUpdate.Value()) count += 1;
      if (C.chkMonitorCategoryBUpdate.Value()) count += 1;
      if (C.chkMonitorCategoryCUpdate.Value()) count += 1;

      if (count == 1) {
        heading = "Update Monitor Category";
      }
      else {
        heading = "Update Monitor Categories";
      }
      message = "Are you sure you want to update Monitoring for this Account Application?";

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

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

  // Create Parameters
  var params = {
    // General
    MonitorCategoryAUpdate: C.chkMonitorCategoryAUpdate.Value(),
    MonitorCategoryAId: C.cboMonitorCategoryA.Text(),

    MonitorCategoryBUpdate: C.chkMonitorCategoryBUpdate.Value(),
    MonitorCategoryBId: C.cboMonitorCategoryB.Text(),

    MonitorCategoryCUpdate: C.chkMonitorCategoryCUpdate.Value(),
    MonitorCategoryCId: C.cboMonitorCategoryC.Text(),

    DateEffective: C.dateEffective.Value(),
    Reference: C.txtReference.Text(),
    Notes: C.txtNotes.Text(),
  };

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

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

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

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

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

function Form_ExecuteAction_FinishPost_Finalise() {
  // Close Form
  widget.Close();

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

// ===========
// gridHistory
// ===========
function gridHistory_Refresh() {
  // Add Columns
  C.gridHistory.ClearColumns();
  C.gridHistory.AddColumnString("Category", { caption: "Category", visible: false});
  C.gridHistory.AddColumnIcon("Icon", { caption: "!", width: "8px"});
  C.gridHistory.AddColumnDate("Date", { caption: "Date"});
  C.gridHistory.AddColumnCode("UserId", { caption: "User", width: "2em"});
  C.gridHistory.AddColumnString("Reference", { caption: "Reference", width: "5em"});
  C.gridHistory.AddColumnHtml("Description", { caption: "Category", width: "2em"});
  C.gridHistory.AddColumnString("Notes", { caption: "Notes"});

  // Grid Actions
  C.gridHistory.Actions().Define([{ actionId: "Cancel", tooltipText: "Cancel Monitor Category change", icon: "Trash" },
                                 ]);

  // Fetch data
  widget.GetString("GetHistory", {},
  function (data) {
    // Parse Data
    mRecord_History = JSON.parse(data);

    // Refresh Grid
    C.gridHistory.VirtualDataRefresh(mRecord_History);

    // Activate Last Row
    C.gridHistory.ActivateLastDataRow();
  },

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

function gridHistory_InitialiseRow(e) {
  var item = mRecord_History[e.row.listIndex];

  // Update cells
  e.row.cells.Date.value = item.Date;
  e.row.cells.Reference.value = item.Reference;
  e.row.cells.Notes.value = item.Notes;
  e.row.cells.UserId.value = item.UserId;

  // Description
  if (item.Description) {
    e.row.cells.Description.value = widget.UI.HtmlEncode(item.Description);
  }
  else {
    e.row.cells.Description.value = "&lt;span style='background-color:rgba(0,0,0,0.05);border-radius:4px; padding:0 4px 0 4px; border:1px solid rgba(0,0,0,0.075); font-size:10px'&gt;&lt;i&gt;Cleared&lt;/i&gt;&lt;/span&gt;";
  }

  // Category
  switch(item.Category) {
    case "A":
      e.row.cells.Category.value = mRecord.MonitorCategoryADescription;
      break;

    case "B":
      e.row.cells.Category.value = mRecord.MonitorCategoryBDescription;
      break;

    case "C":
      e.row.cells.Category.value = mRecord.MonitorCategoryCDescription;
      break;
  }

  // Icon
  if (item.Colour) {
    e.row.cells.Icon.value = "Colour[" + item.Colour + "]";
  }

  // Cancelled
  if (item.Cancelled) {
    e.row.inactive = true;
    e.row.strike = true;
  }

  // Hide all but current category
  if (!mAdvancedVisible) {
    if (mRecord.MonitorCategoryAUpdate &amp;&amp; item.Category != "A") {
      e.row.hidden = true;
    }
    else if (mRecord.MonitorCategoryBUpdate &amp;&amp; item.Category != "B") {
      e.row.hidden = true;
    }
    else if (mRecord.MonitorCategoryCUpdate &amp;&amp; item.Category != "C") {
      e.row.hidden = true;
    }
  }

  // Hide?
  if (e.row.inactive) e.row.hidden = true;
}

function gridHistory_Action(actionId) {
  var item = mRecord_History[C.gridHistory.ActiveDataRowListIndex()];

  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      widget.UI.MsgBoxConfirm("Are you sure you want to CANCEL the selected item dated " + widget.FormatDate(item.Date) + "?", {}, function() { gridHistory_Action_Cancel(item); });
      break;

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

function gridHistory_Action_Cancel(item) {
  // Block UI
  widget.UI.Block("Cancelling, please wait...");

  // Cancel
  var params = { pk: item.Pk };
  widget.GetString("HistoryItem_Cancel", params,
    // Success
    function (data) {
      // Unblock UI
      widget.UI.Unblock();

      // Refresh grid
      item.Cancelled = true;
      item.CanCancel = false;
      C.gridHistory.RefreshRow(C.gridHistory.ActiveDataRowListIndex());
      gridHistory_RefreshButtons();

      // Flag as needing to reload details
      mRefreshRequired = true;

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

    // Fail
    function (message) {
      widget.UI.MsgBoxAlert(message);

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

function gridHistory_AfterRowActivate(e) {
  // Refresh Buttons
  gridHistory_RefreshButtons();
}

function gridHistory_RefreshButtons() {
  if (C.gridHistory.ActiveDataRowListIndex() == -1) {
    C.gridHistory.Actions().SetEnabled("Cancel", false);
  }
  else {
    var item = mRecord_History[C.gridHistory.ActiveDataRowListIndex()];
    C.gridHistory.Actions().SetEnabled("Cancel", !item.Cancelled &amp;&amp; item.CanCancel);
  }

  C.gridHistory.RefreshButtons();
}

// =============
// dateEffective
// =============
function dateEffective_Change(sender, e) {
  if (C.dateEffective.Value()) {
    widget.GetString("Form_DateEffective_Change", { date: C.dateEffective.Value() }, dateEffective_Change_Done, dateEffective_Change_Fail);
  }
}

function dateEffective_Change_Done(data) {
  if (data) {
    // Parse
    var o = JSON.parse(data);

    // Update Record
    mRecord.MonitorCategoryAFutureChange = o.MonitorCategoryAFutureChange;
    mRecord.MonitorCategoryBFutureChange = o.MonitorCategoryBFutureChange;
    mRecord.MonitorCategoryCFutureChange = o.MonitorCategoryCFutureChange;

    mRecord.MonitorCategoryAId = o.MonitorCategoryAId;
    mRecord.MonitorCategoryBId = o.MonitorCategoryBId;
    mRecord.MonitorCategoryCId = o.MonitorCategoryCId;
  }

  // Load Fields
  C.cboMonitorCategoryA.Text(mRecord.MonitorCategoryAId);
  C.cboMonitorCategoryB.Text(mRecord.MonitorCategoryBId);
  C.cboMonitorCategoryC.Text(mRecord.MonitorCategoryCId);

  // Update Controls
  if (mRecord.MonitorCategoryAFutureChange) C.divWarningA.show(); else C.divWarningA.hide();
  if (mRecord.MonitorCategoryBFutureChange) C.divWarningB.show(); else C.divWarningB.hide();
  if (mRecord.MonitorCategoryCFutureChange) C.divWarningC.show(); else C.divWarningC.hide();

  // Finalise
  mRefreshRequired = false;
}

function dateEffective_Change_Fail(data) {
  widget.UI.MsgBoxAlert(data);
}

// =========================
// chkMonitorCategoryAUpdate
// =========================
function chkMonitorCategoryAUpdate_Change(sender, e) {
  C.cboMonitorCategoryA.ReadOnly(!C.chkMonitorCategoryAUpdate.Value() || C.chkMonitorCategoryAUpdate.ReadOnly());
}

// =========================
// chkMonitorCategoryBUpdate
// =========================
function chkMonitorCategoryBUpdate_Change(sender, e) {
  C.cboMonitorCategoryB.ReadOnly(!C.chkMonitorCategoryBUpdate.Value() || C.chkMonitorCategoryBUpdate.ReadOnly());
}

// =========================
// chkMonitorCategoryCUpdate
// =========================
function chkMonitorCategoryCUpdate_Change(sender, e) {
  C.cboMonitorCategoryC.ReadOnly(!C.chkMonitorCategoryCUpdate.Value() || C.chkMonitorCategoryCUpdate.ReadOnly());
}

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

    // Remove advanced section styling for everything
    $("tr").removeClass("advanced");
  }

  // Controls
  C.chkMonitorCategoryAUpdate.Caption("Update " + mRecord.MonitorCategoryADescription + "?");
  C.chkMonitorCategoryAUpdate.VisibleRow(mRecord.MonitorCategoryAUse);
  C.cboMonitorCategoryA.VisibleRow(mRecord.MonitorCategoryAUse);
  if (!mRecord.MonitorCategoryACanUpdate) {
    C.chkMonitorCategoryAUpdate.ReadOnly(true);
    C.cboMonitorCategoryA.ReadOnly(true);
    cmdClearA.prop("disabled", true);
  }
  chkMonitorCategoryAUpdate_Change();

  C.chkMonitorCategoryBUpdate.Caption("Update " + mRecord.MonitorCategoryBDescription + "?");
  C.chkMonitorCategoryBUpdate.VisibleRow(mRecord.MonitorCategoryBUse);
  C.cboMonitorCategoryB.VisibleRow(mRecord.MonitorCategoryBUse);
  if (!mRecord.MonitorCategoryBCanUpdate) {
    C.chkMonitorCategoryBUpdate.ReadOnly(true);
    C.cboMonitorCategoryB.ReadOnly(true);
    cmdClearB.prop("disabled", true);
  }
  chkMonitorCategoryBUpdate_Change();

  C.chkMonitorCategoryCUpdate.Caption("Update " + mRecord.MonitorCategoryCDescription + "?");
  C.chkMonitorCategoryCUpdate.VisibleRow(mRecord.MonitorCategoryCUse);
  C.cboMonitorCategoryC.VisibleRow(mRecord.MonitorCategoryCUse);
  if (!mRecord.MonitorCategoryCCanUpdate) {
    C.chkMonitorCategoryCUpdate.ReadOnly(true);
    C.cboMonitorCategoryC.ReadOnly(true);
    cmdClearC.prop("disabled", true);
  }
  chkMonitorCategoryCUpdate_Change();

  // Show/ hide Advanced
  if (mRecord) {
    if (mAdvancedVisible) {
      // Showing
      cmdAdvanced.attr("showing", true);
      $("body").addClass("advanced-visible");

      C.lblMonitorCategoryDetails.Text("Specify Monitor Category changes");

      $(".fakeindent").removeClass("fakeindent").addClass("indent1");
    }
    else {
      // Not showing
      cmdAdvanced.attr("showing", false);
      $("body").removeClass("advanced-visible");

      $(".indent1").removeClass("indent1").addClass("fakeindent");

      if (mRecord.MonitorCategoryAUpdate &amp;&amp; mRecord.MonitorCategoryAUse) {
        C.lblMonitorCategoryDetails.Text("Specify " + mRecord.MonitorCategoryADescription + " change");

        C.cboMonitorCategoryA.VisibleRow(true);
        C.chkMonitorCategoryAUpdate.Value(true);

        // Not an advanced row
        widget.UI.GetControlRow(C.cboMonitorCategoryA).removeClass("advanced");
      }
      else if (mRecord.MonitorCategoryBUpdate &amp;&amp; mRecord.MonitorCategoryBUse) {
        C.lblMonitorCategoryDetails.Text("Specify " + mRecord.MonitorCategoryBDescription + " change");

        C.cboMonitorCategoryB.VisibleRow(true);
        C.chkMonitorCategoryBUpdate.Value(true);

        // Not an advanced row
        widget.UI.GetControlRow(C.cboMonitorCategoryB).removeClass("advanced");
      }
      else if (mRecord.MonitorCategoryCUpdate &amp;&amp; mRecord.MonitorCategoryAUse) {
        C.lblMonitorCategoryDetails.Text("Specify " + mRecord.MonitorCategoryCDescription + " change");

        C.cboMonitorCategoryC.VisibleRow(true);
        C.chkMonitorCategoryCUpdate.Value(true);

        // Not an advanced row
        widget.UI.GetControlRow(C.cboMonitorCategoryC).removeClass("advanced");
      }
      else {
        // Should never get here!
      }
    }

    chkMonitorCategoryAUpdate_Change();
    chkMonitorCategoryBUpdate_Change();
    chkMonitorCategoryCUpdate_Change();
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>wi+iUOjKq0qVCZAVCD87Pw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>800</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AlwaysShowAdvanced" type="Boolean">
            <BlankTip />
            <Caption>Always show "Advanced" details?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AccountAppId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.AccountApps</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountMonitorCategory" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>A,B,C</List>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowHistory" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="Clear" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>