<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-26T02:10:40.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-03-11T21:41:49.8800000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-26T02:10:23.4830000</UpdatedUtcDate>
    <ScriptId>PPSRUPDATE</ScriptId>
    <Description>PPSR NZ Update</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_PPSRNZUpdate
Option Explicit On
Option Strict On

' #################################################################
' PPSR NZ Update wizard
'
' Version: 1.04 (26/09/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.01  05/07/2021  ISS
'    1.02  08/12/2021  ISS      J027840   Spelling Correction
'          10/12/2021  ISS      J028022   Flicker issue when loading
'    1.03  29/09/2022  ISS      J029737   Implemented widget.UI.BuildBackgroundProcessProgress
'    1.04  26/09/2024  ISS      J034269   Updated Grid to be sortable
' #################################################################

' Constants
Private Const FORM_KEY As String = "PPSRNZUpdate"

' 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)

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

    Case "CancelBackgroundProcess"
      ' Cancel a Process
      Main = CancelBackgroundProcess(returnValue)

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

    Case "GetCurrentProcesses"
      ' Get Current Processes
      Main = GetCurrentProcesses(returnValue)

    Case "GetBackgroundProcessStatus"
      ' Get Background Process Status
      Main = GetBackgroundProcessStatus(returnValue)

    Case "GetUpdateItemPreview"
      ' Get the HTML Summary Page for the active row on the grid
      Main = GetUpdateItemPreview(returnValue)

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

    Case "GetUpdateItems"
      ' Get Update Items
      Main = GetUpdateItems(parametersJson, returnValue)

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

End Function

''' &lt;summary&gt;
'''  Request that a Background Process is Cancelled.
''' &lt;/summary&gt;
Private Function CancelBackgroundProcess(ByRef returnValue As String) As Boolean

  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ProcessId = mCombinedParameters.GetString("ProcessId")

  ' Request Cancel
  Success = finBL.HtmlWidgetUtilities.CancelBackgroundProcess(processId)

  Return Success

End Function

''' &lt;summary&gt;
'''  Create finSecurityRegistryPPSRNZ_Update object.
''' &lt;/summary&gt;
Private Function CreateSecurityRegistryPPSRNZ_Update(parameters As PPSRNZUpdateParameters,
                                                     ByRef securityRegistryPPSRNZ_Update As finSecurityRegistryPPSRNZ_Update) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  securityRegistryPPSRNZ_Update = finBL.SecurityRegistry.Service_PPSRNZ.CreateSecurityRegistryPPSRNZ_Update()

  ' Update
  With securityRegistryPPSRNZ_Update
    ' Update
    If Success AndAlso parameters IsNot Nothing Then
      ' General
      .IncludeAmendments = parameters.IncludeAmendments
      .IncludeAmendmentsCheckForChanges = parameters.IncludeAmendmentsCheckForChanges
      .IncludeDischarges = parameters.IncludeDischarges
      .IncludeDischargesToDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.IncludeDischargesToDate)
      .IncludeRegistrations = parameters.IncludeRegistrations
      .IncludeRegistrationsToDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.IncludeRegistrationsToDate)
      .IncludeRenewals = parameters.IncludeRenewals
      .IncludeRenewalsToDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.IncludeRenewalsToDate)

      ' Ranges
      .RangeBranches = parameters.RangeBranches
      .RangeEntities = parameters.RangeEntities
      .RangeSecuredPartyGroups = parameters.RangeSecuredPartyGroups
      .RangeSecurityStatementGroups = parameters.RangeSecurityStatementGroups
      .RangeSecurityStatementIds = parameters.RangeSecurityStatementIds
    End If
  End With

  Return Success

End Function

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

  Dim PPSRNZUpdateParameters As PPSRNZUpdateParameters
  Dim ProcessId As String
  Dim SecurityRegistryPPSRNZ_Update As finSecurityRegistryPPSRNZ_Update
  Dim SecurityRegistryPPSRNZ_UpdateItem As finSecurityRegistryPPSRNZ_UpdateItem
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Parse Parameters
  Success = GetPPSRNZUpdateParameters(parametersJson, PPSRNZUpdateParameters)

  ' Get PPSR NZ Update Object and refresh
  If Success Then
    If CreateSecurityRegistryPPSRNZ_Update(PPSRNZUpdateParameters, SecurityRegistryPPSRNZ_Update) Then
      Success = SecurityRegistryPPSRNZ_Update.Refresh()
    Else
      Success = False
    End If
  End If

  ' Update Included Items
  If Success Then
    For Each SecurityRegistryPPSRNZ_UpdateItem In SecurityRegistryPPSRNZ_Update
      With SecurityRegistryPPSRNZ_UpdateItem
        .Include = PPSRNZUpdateParameters.SecurityStmtPks.Contains(.SecurityStmtPk)
      End With
    Next

    ' Validate
    If SecurityRegistryPPSRNZ_Update.CountIncluded() = 0 Then
      Success = False
      finBL.Error.ErrorBegin("You must select at least one Financing Statement to update.")
    ElseIf SecurityRegistryPPSRNZ_Update.CountIncluded() &lt;&gt; PPSRNZUpdateParameters.SecurityStmtPks.Count() Then
      Success = False
      finBL.Error.ErrorBegin("Record mismatch. The collection may have changed since it was originally loaded. Please refresh the results and try again.")
    End If
  End If

  ' Queue Background Process
  If Success Then
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_PPSRNZUpdate(SecurityRegistryPPSRNZ_Update, ProcessId)
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Background Process Status.
''' &lt;/summary&gt;
Private Function GetBackgroundProcessStatus(ByRef returnValue As String) As Boolean

  Dim LastEventId As String
  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    LastEventId = .GetString("LastEventId")
    ProcessId = .GetString("ProcessId")
  End With

  ' Get Background Processes Status including Events
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessStatusIncludingEventsJson(processId, lastEventId, returnValue)

  Return Success

End Function

''' &lt;summary&gt;
'''  Get current and recent Background Processes that for this User (these  are also returned in GetInitialisationInfo).
''' &lt;/summary&gt;
Private Function GetCurrentProcesses(ByRef returnValue As String) As Boolean

  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get current and recent Background Processes that for this User
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_PPSRNZUpdate(True, ProcessStatuses)

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ProcessStatuses, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get the HTML Summary Page for the active row on the grid
''' &lt;/summary&gt;
Private Function GetUpdateItemPreview(ByRef returnValue As String) As Boolean

  Dim SecurityStmt As finSecurityStmt
  Dim SecurityStmtId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    SecurityStmtId = .GetString("SecurityStmtId")
  End With

  ' Initialise
  SecurityStmt = finBL.CreateSecurityStmt()

  ' Load Security Statement
  Success = SecurityStmt.Load(SecurityStmtId)

  ' Get Summary
  If Success Then
    returnValue = finBL.SummaryPageFunctions.PPSRNZUpdateSummary(False, SecurityStmt, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
  End If

  Return Success

End Function

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

  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim SecurityRegistryPPSRNZ_Update As finSecurityRegistryPPSRNZ_Update
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise

  ' Validate
  If Not finBL.Settings.AddOns.SecurityRegisterPPSR Then
    Success = False
    finBL.Error.ErrorBegin("You are not licensed for the Security Register Add-On.")
  ElseIf finBL.CountryCode &lt;&gt; "NZ" Then
    Success = False
    finBL.Error.ErrorBegin("PPSR NZ Service is only available in New Zealand.")
  ElseIf finBL.SecurityRegistry Is Nothing Then
    Success = False
    finBL.Error.ErrorBegin("Security Registry interface is not initialised.")
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  End If

  ' Get PPSR NZ Update Object
  If Success Then
    Success = CreateSecurityRegistryPPSRNZ_Update(Nothing, SecurityRegistryPPSRNZ_Update)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      .PPSRNZUpdateParameters = New PPSRNZUpdateParameters(SecurityRegistryPPSRNZ_Update)

      ' Lists

      ' Configuration
      .CostCentreWarnOnCharge = finBL.Settingsuser.CostCentreWarnOnCharge
      .TestMode = finBL.SettingsUser.CostCentreTestModeResolved

      ' Advanced Sections
      .ShowBranches = mCombinedParameters.GetString("ShowBranches") : If Len(.ShowBranches) = 0 Then .ShowBranches = "Advanced"
      .ShowEntities = mCombinedParameters.GetString("ShowEntities") : If Len(.ShowEntities) = 0 Then .ShowEntities = "Advanced"
      .ShowSecuredPartyGroups = mCombinedParameters.GetString("ShowSecuredPartyGroups") : If Len(.ShowSecuredPartyGroups) = 0 Then .ShowSecuredPartyGroups = "Advanced"
      .ShowSecurityStmtGroups = mCombinedParameters.GetString("ShowSecurityStmtGroups") : If Len(.ShowSecurityStmtGroups) = 0 Then .ShowSecurityStmtGroups = "Advanced"
      .ShowSecurityStmts = mCombinedParameters.GetString("ShowSecurityStmts") : If Len(.ShowSecurityStmts) = 0 Then .ShowSecurityStmts = "Advanced"
      .PageGeneralHasAdvanced = (.ShowSecuredPartyGroups = "Advanced" OrElse .ShowEntities = "Advanced" OrElse .ShowBranches = "Advanced" OrElse .ShowSecurityStmtGroups = "Advanced" OrElse .ShowSecurityStmts = "Advanced")

      ' Licence
      If Not finBL.Settings.AddOns.Branch Then .ShowBranches = "False"
      If Not finBL.Settings.AddOns.Entity Then .ShowEntities = "False"

      ' Heading
      If (.ShowSecuredPartyGroups = "Advanced" AndAlso .ShowEntities = "Advanced" AndAlso .ShowBranches = "Advanced" AndAlso .ShowSecurityStmtGroups = "Advanced" AndAlso .ShowSecurityStmts = "Advanced") Then
        ' All Advanced
        .ShowRangesHeading = "Advanced"
      Else If (.ShowSecuredPartyGroups = "False" AndAlso .ShowEntities = "False" AndAlso .ShowBranches = "False" AndAlso .ShowSecurityStmtGroups = "False" AndAlso .ShowSecurityStmts = "False") Then
        ' All Hidden
        .ShowRangesHeading = "False"
      Else If (.ShowSecuredPartyGroups &lt;&gt; "True" AndAlso .ShowEntities &lt;&gt; "True" AndAlso .ShowBranches &lt;&gt; "True" AndAlso .ShowSecurityStmtGroups &lt;&gt; "True" AndAlso .ShowSecurityStmts &lt;&gt; "True") AndAlso (.ShowSecuredPartyGroups = "Advanced" OrElse .ShowEntities = "Advanced" OrElse .ShowBranches = "Advanced" OrElse .ShowSecurityStmtGroups = "Advanced" OrElse .ShowSecurityStmts = "Advanced") Then
        ' Some Advanced
        .ShowRangesHeading = "Advanced"
      Else
        ' Some always displayed
        .ShowRangesHeading = "True"
      End If

      ' Form Heading
      .FormHeading = ScriptInfo.ScriptCaption
      If Len(.FormHeading) = 0 Then .FormHeading = "PPSR NZ Update"
      If .TestMode Then .FormHeading = .FormHeading &amp; " (Test Mode)"
    End With
  End If

  ' Get current and recent Background Processes that for this User
  If Success Then
    If finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_PPSRNZUpdate(True, ProcessStatuses) Then
      FormInitialisationInfo.CurrentProcesses = ProcessStatuses
    Else
      Success = False
    End If
  End If

  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get PPSR NZ Update Parameters.
''' &lt;/summary&gt;
Private Function GetPPSRNZUpdateParameters(parametersJson As String,
                                           ByRef PPSRNZUpdateParameters As PPSRNZUpdateParameters) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  PPSRNZUpdateParameters = Nothing

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Update Items.
''' &lt;/summary&gt;
Private Function GetUpdateItems(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim SecurityRegistryPPSRNZ_Update As finSecurityRegistryPPSRNZ_Update
  Dim SecurityRegistryPPSRNZ_UpdateItem As finSecurityRegistryPPSRNZ_UpdateItem
  Dim Success As Boolean
  Dim PPSRNZUpdateParameters As PPSRNZUpdateParameters
  Dim UpdateItems As List(Of UpdateItem)

  ' Assume Success
  Success = True

  ' Initialise
  UpdateItems = New List(Of UpdateItem)

  ' Parse Parameters
  Success = GetPPSRNZUpdateParameters(parametersJson, PPSRNZUpdateParameters)

  ' Get PPSR NZ Update Object and refresh
  If Success Then
    If CreateSecurityRegistryPPSRNZ_Update(PPSRNZUpdateParameters, SecurityRegistryPPSRNZ_Update) Then
      Success = SecurityRegistryPPSRNZ_Update.Refresh()
    Else
      Success = False
    End If
  End If

  ' Add to Collection
  If Success Then
    For Each SecurityRegistryPPSRNZ_UpdateItem In SecurityRegistryPPSRNZ_Update
      UpdateItems.Add(New UpdateItem(SecurityRegistryPPSRNZ_UpdateItem))
    Next
  End If

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

  Return Success

End Function



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

  ' Current Processes
  Public CurrentProcesses As New List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)

  ' Record
  Public PPSRNZUpdateParameters As PPSRNZUpdateParameters

  ' Lists

  ' Advanced
  Public PageGeneralHasAdvanced As Boolean
  Public ShowBranches As String
  Public ShowEntities As String
  Public ShowRangesHeading As String
  Public ShowSecuredPartyGroups As String
  Public ShowSecurityStmtGroups As String
  Public ShowSecurityStmts As String

  ' Configuration
  Public CostCentreWarnOnCharge As Boolean
  Public FormHeading As String
  Public TestMode As Boolean

End Class



''' &lt;summary&gt;
'''  PPSR NZ Update Parameters (also used for Initialisation and Finish).
''' &lt;/summary&gt;
Public Class PPSRNZUpdateParameters

  Public IncludeAmendments As Boolean
  Public IncludeAmendmentsCheckForChanges As Boolean
  Public IncludeDischarges As Boolean
  Public IncludeDischargesToDate As Date?
  Public IncludeRegistrations As Boolean
  Public IncludeRegistrationsToDate As Date?
  Public IncludeRenewals As Boolean
  Public IncludeRenewalsToDate As Date?

  Public RangeBranches As String
  Public RangeEntities As String
  Public RangeSecuredPartyGroups As String
  Public RangeSecurityStatementGroups As String
  Public RangeSecurityStatementIds As String

  Public SecurityStmtPks As New List(Of Integer)

  Public Sub New()
  End Sub

  Public Sub New(securityRegistryPPSRNZ_Update As finSecurityRegistryPPSRNZ_Update)

    With securityRegistryPPSRNZ_Update
      Me.IncludeAmendments = .IncludeAmendments
      Me.IncludeAmendmentsCheckForChanges = .IncludeAmendmentsCheckForChanges
      Me.IncludeDischarges = .IncludeDischarges
      Me.IncludeDischargesToDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.IncludeDischargesToDate)
      Me.IncludeRegistrations = .IncludeRegistrations
      Me.IncludeRegistrationsToDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.IncludeRegistrationsToDate)
      Me.IncludeRenewals = .IncludeRenewals
      Me.IncludeRenewalsToDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.IncludeRenewalsToDate)

      Me.RangeBranches = .RangeBranches
      Me.RangeEntities = .RangeEntities
      Me.RangeSecuredPartyGroups = .RangeSecuredPartyGroups
      Me.RangeSecurityStatementGroups = .RangeSecurityStatementGroups
      Me.RangeSecurityStatementIds = .RangeSecurityStatementIds
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Update Item.
''' &lt;/summary&gt;
Public Class UpdateItem

  Public CanInclude As Boolean
  Public DateExpiry As Date?
  Public DateRegistered As Date?
  Public Description As String
  Public FailedMessage As String
  Public FsId As String
  Public Icon As String
  Public Include As Boolean
  Public IsChargeable As Boolean
  Public RegisterAction As String
  Public RegisterActionStatus As String
  Public RegisterStatus As String
  Public SecurityStmtId As String
  Public SecurityStmtPk As Integer
  Public Warnings As String

  Public Sub New(securityRegistryPPSRNZ_UpdateItem As finSecurityRegistryPPSRNZ_UpdateItem)

    With securityRegistryPPSRNZ_UpdateItem
      Me.CanInclude = .CanInclude
      Me.DateExpiry = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(.DateExpiry)
      Me.DateRegistered = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(.DateRegistered)
      Me.Description = .Description
      Me.FailedMessage = .FailedMessage
      Me.FsId = .FsId

      If .CanInclude() AndAlso Len(.WarningsText) = 0 Then
        Me.Icon = "Blank"
      Else
        Me.Icon = "Warning"
      End If

      Me.Include = .Include
      Me.IsChargeable = .IsChargeable()
      Me.RegisterAction = "Action: " &amp; .RegisterActionText
      Me.RegisterActionStatus = .RegisterActionStatusText
      Me.RegisterStatus = .RegisterStatusText
      Me.SecurityStmtId = .SecurityStmtId
      Me.SecurityStmtPk = .SecurityStmtPk
      Me.Warnings = .WarningsText
    End With

  End Sub

End Class



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

  Public ProcessId As String

  Public Sub New(processId As String)

    Me.ProcessId = processId

  End Sub

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

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

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;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="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent PPSR NZ Updates you have run."&gt;Recent PPSR NZ Updates&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Select the criteria for Financing Statements to be updated."&gt;PPSR NZ Update&lt;/li&gt;
        &lt;li tabId="UpdateItems" tooltipText="Financing Statements to be updated."&gt;Update Items&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Current Processes --&gt;
    &lt;div id="pageCurrentProcesses"&gt;
      &lt;div id="gridCurrentProcesses"&gt;&lt;/div&gt;
    &lt;/div&gt;

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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRegisterNew"&gt;Do you want to Register New Financing Statements?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeRegistrations" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateIncludeRegistrationsToDate"&gt;Created:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateIncludeRegistrationsToDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAmend"&gt;Do you want to Amend Financing Statements?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeAmendments" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkIncludeAmendmentsCheckForChanges" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDischarge"&gt;Do you want to Discharge Financing Statements?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeDischarges" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateIncludeDischargesToDate"&gt;Closed:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateIncludeDischargesToDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRenew"&gt;Do you want to Renew Financing Statements?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeRenewals" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateIncludeRenewalsToDate"&gt;Expiry:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateIncludeRenewalsToDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr advancedId="Ranges"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRanges"&gt;Enter Ranges to filter information&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="SecuredPartyGroups"&gt;
          &lt;th&gt;&lt;label for="txtRangeSecuredPartyGroups"&gt;Secured&amp;nbsp;Party&amp;nbsp;Groups:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeSecuredPartyGroups" lookupCaption="Secured Party Groups" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Entities"&gt;
          &lt;th&gt;&lt;label for="txtRangeEntities"&gt;Entities:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeEntities" lookupCaption="Entities" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Branches"&gt;
          &lt;th&gt;&lt;label for="txtRangeBranches"&gt;Branches:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeBranches" lookupCaption="Branches" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="SecurityStmtGroups"&gt;
          &lt;th&gt;&lt;label for="txtRangeSecurityStmtGroups"&gt;Security&amp;nbsp;Statement&amp;nbsp;Groups:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeSecurityStmtGroups" lookupCaption="Security Statement Groups" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="SecurityStmts"&gt;
          &lt;th&gt;&lt;label for="txtRangeSecurityStmts"&gt;Security&amp;nbsp;Statements:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeSecurityStmts" lookupCaption="Security Statements" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Update Items --&gt;
    &lt;div id="pageUpdateItems"&gt;
      &lt;div class="is-dock-fill is-split-container split5050"&gt;
        &lt;div class="panel"&gt;
          &lt;div id="gridUpdateItems"&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="panel"&gt;
          &lt;div id="wbUpdateItemSummary" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Progress --&gt;
    &lt;div id="pageProgress" style="display:flex"&gt;
      &lt;div id="divProgress" class="progress-events"&gt;&lt;/div&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;Recent&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_PPSRNZUpdateParameters;
var mRecord_BackgroundProcessStatus;
var mRecord_CurrentProcesses;

var mFinancingStatements;

// Controls
var C = {
  //   Current Processes
  gridCurrentProcesses: null,

  //   General
  lblRegisterNew: null,
  chkIncludeRegistrations: null,
  dateIncludeRegistrationsToDate: null,

  lblAmend: null,
  chkIncludeAmendments: null,
  chkIncludeAmendmentsCheckForChanges: null,

  lblDischarge: null,
  chkIncludeDischarges: null,
  dateIncludeDischargesToDate: null,

  lblRenew: null,
  chkIncludeRenewals: null,
  dateIncludeRenewalsToDate: null,

  lblRanges: null,
  txtRangeSecuredPartyGroups: null,
  txtRangeEntities: null,
  txtRangeBranches: null,
  txtRangeSecurityStmtGroups: null,
  txtRangeSecurityStmts: null,

  //   Update Items
  gridUpdateItems: null,
  wbUpdateItemSummary: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;
var cmdAdvanced;

// Other
var mAdvancedVisible = false;
var mFromRecent = false;
var mMonitoringExisting = false;
var mProcessId;

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

  // Controls
  //   General
  C.lblRegisterNew = widget.UI.Label("lblRegisterNew", {});
  C.chkIncludeRegistrations = widget.UI.CheckBox("chkIncludeRegistrations", {
    caption: "Register new Financing Statements?",
    captionWrap: true,

    onChange: chkIncludeRegistrations_Change,
  });
  C.dateIncludeRegistrationsToDate = widget.UI.DateBox("dateIncludeRegistrationsToDate", {});

  C.lblAmend = widget.UI.Label("lblAmend", {});
  C.chkIncludeAmendments = widget.UI.CheckBox("chkIncludeAmendments", {
    caption: "Amend Financing Statements?",
    captionWrap: true,

    onChange: chkIncludeAmendments_Change,
  });
  C.chkIncludeAmendmentsCheckForChanges = widget.UI.CheckBox("chkIncludeAmendmentsCheckForChanges", {
    caption: "Check for Amended Security Statements?",
    captionWrap: true,
  });

  C.lblDischarge = widget.UI.Label("lblDischarge", {});
  C.chkIncludeDischarges = widget.UI.CheckBox("chkIncludeDischarges", {
    caption: "Discharge Financing Statements?",
    captionWrap: true,

    onChange: chkIncludeDischarges_Change,
  });
  C.dateIncludeDischargesToDate = widget.UI.DateBox("dateIncludeDischargesToDate", {});

  C.lblRenew = widget.UI.Label("lblRenew", {});
  C.chkIncludeRenewals = widget.UI.CheckBox("chkIncludeRenewals", {
    caption: "Renew Financing Statements?",
    captionWrap: true,

    onChange: chkIncludeRenewals_Change,
  });
  C.dateIncludeRenewalsToDate = widget.UI.DateBox("dateIncludeRenewalsToDate", {});

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

  //   Update Items
  C.wbUpdateItemSummary = widget.UI.PreviewPane("wbUpdateItemSummary", {
    formActionHandler: Widget_NotificationHandler,
  });

  //   Progress
  C.divProgress = $("#divProgress");

  // Ranges
  for(var k in C) {
    if (k.startsWith("txtRange")) {
      C[k] = widget.UI.TextBox(k, {
        maxLength: 255,
        onButtonClick: txtRange_ButtonClick,
      });
      var buttons = [];

      // Lookup button
      buttons.push({id: "Lookup", icon: "Find", tooltipText: "Lookup"});

      // Define buttons
      C[k].ButtonsDefine(buttons);
    }
  }

  // Grids
  C.gridCurrentProcesses = widget.UI.Grid("gridCurrentProcesses", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,

    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

  C.gridUpdateItems = widget.UI.Grid("gridUpdateItems", {
    allowCellSelect: false,
    allowMultiRowSelect: true,
    docked: true,
    groupByColumns: "RegisterAction",
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridUpdateItems_Action,
    onAfterRowActivate: gridUpdateItems_AfterRowActivate,
    onBeforeCellUpdate: gridUpdateItems_BeforeCellUpdate,
    onInitialiseRow: gridUpdateItems_InitialiseRow,
    onRowDrilldown: gridUpdateItems_RowDrilldown,
  });

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

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

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

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

  // Handle Notifications
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // 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_PPSRNZUpdateParameters = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mFinancingStatements = null;

  // Hide content
  frmMain.Visible(false);

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

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

      // Give Collections ability to lookup by code

      // Load Fields
      Fields_Load();

      // Notify if there are Current Processes
      var countCurrent = 0;
      for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
        switch (mRecord_CurrentProcesses[i].Status) {
          case "Pending":
          case "InProgress":
          case "InProgressCancelRequested":
            countCurrent += 1;
        }
      }
      if (countCurrent != 0) {
        tabWizard_Move(-1);
        widget.UI.MsgBoxInfo("There are existing PPSR NZ Updates that you have run that are not yet complete.\n\nReview and optionally monitor these or use the 'Next &gt;' button to run a new instance of PPSR NZ Update.", { heading: "PPSR NZ Update Still Running", icon: "MonitorCategory"} );
      }
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // Current Processes
    // NOTE: Bind here since this is the first page
    gridCurrentProcesses_Refresh();

    // General
    C.chkIncludeRegistrations.Value(mRecord_PPSRNZUpdateParameters.IncludeRegistrations);
    C.dateIncludeRegistrationsToDate.Value(mRecord_PPSRNZUpdateParameters.IncludeRegistrationsToDate);
    C.chkIncludeAmendments.Value(mRecord_PPSRNZUpdateParameters.IncludeAmendments);
    C.chkIncludeAmendmentsCheckForChanges.Value(mRecord_PPSRNZUpdateParameters.IncludeAmendmentsCheckForChanges);
    C.chkIncludeDischarges.Value(mRecord_PPSRNZUpdateParameters.IncludeDischarges);
    C.dateIncludeDischargesToDate.Value(mRecord_PPSRNZUpdateParameters.IncludeDischargesToDate);
    C.chkIncludeRenewals.Value(mRecord_PPSRNZUpdateParameters.IncludeRenewals);
    C.dateIncludeRenewalsToDate.Value(mRecord_PPSRNZUpdateParameters.IncludeRenewalsToDate);

    C.txtRangeSecuredPartyGroups.Text(mRecord_PPSRNZUpdateParameters.RangeSecuredPartyGroups);
    C.txtRangeEntities.Text(mRecord_PPSRNZUpdateParameters.RangeEntities);
    C.txtRangeBranches.Text(mRecord_PPSRNZUpdateParameters.RangeBranches);
    C.txtRangeSecurityStmtGroups.Text(mRecord_PPSRNZUpdateParameters.RangeSecurityStatementGroups);
    C.txtRangeSecurityStmts.Text(mRecord_PPSRNZUpdateParameters.RangeSecurityStatementIds);
  }

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

  // Update fields
  Fields_Update();

  // Update Controls

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  // Not used by this HTML Widget
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    widget.SetHeading(mRecord.FormHeading);
  }

  // Information Lists

  // Lists
  if (mRecord) {
  }

  // Controls
  if (mRecord) {
    chkIncludeRegistrations_Change();
    chkIncludeAmendments_Change();
    chkIncludeDischarges_Change();
    chkIncludeRenewals_Change();

    // Initialise Advanced
    AdvancedInitialise();
  }

  // Auto-format
  tabWizard.AutoFormatPage();

  // Update Buttons
  tabWizard_UpdateButtons();

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

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

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  // Executing?
  if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("PPSR NZ Update is still running.\n\nThis will continue to run and you can re-open this form at any time to check on its status.\n\n\Close this form?", {}, tabWizard_Cancel_Post);
  }
  else {
    tabWizard_Cancel_Post();
  }
}

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

function tabWizard_UpdateButtons() {
  var tabIndex = tabWizard.SelectedTabIndex();

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

  // Page Exceptions
  if (mRecord_BackgroundProcessStatus) {
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
    cmdBack.prop("disabled", true);
    cmdHistory.prop("disabled", true);

    switch(mRecord_BackgroundProcessStatus.Status) {
      case "Pending":
      case "InProgress":
        cmdFinish.text("Stop");
        cmdFinish.prop("disabled", false);
        cmdFinish.addClass("negative");
        break;

      default:
        cmdFinish.text("Process");
        cmdFinish.prop("disabled", true);
        cmdFinish.removeClass("negative");
    }
  }
  else {
    cmdFinish.text("Process");
    cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
    cmdHistory.prop("disabled", false);
  }

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

  // Recent Page exceptions
  if (mFromRecent) {
    cmdHistory.prop("disabled", false);

    cmdBack.prop("disabled", true);
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", true);
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // General
      for(var k in C) {
        if (k.startsWith("txtRange")) {
          C[k].WidthResizeFromParent();
        }
      }
      break;

    default:
      break;
  }
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

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

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

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

      default:
        break;
    }
  }

  // Always Refresh Current Processes, even when moving back
  if (newTab == 0) {
    if (!mRecord_CurrentProcesses) pageCurrentProcesses_Refresh();
  }

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "CurrentProcesses":
      // Reset from recent flag
      mFromRecent = false;
      break;

    default:
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    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":
        // General
        if (!C.chkIncludeRegistrations.Value() &amp;&amp; !C.chkIncludeAmendments.Value() &amp;&amp; !C.chkIncludeDischarges.Value() &amp;&amp; !C.chkIncludeRenewals.Value()) {
          Ok = false;
          widget.UI.MsgBoxAlert("At least one action (Register, Amend, Discharge or Renew) must be selected to continue.");
        }
        break;

      case "UpdateItems":
        // Update Items
        var securityStmtPks = CreateFinishParameters_SelectedItems();
        if (securityStmtPks.length == 0) {
          Ok = false;
          widget.UI.MsgBoxAlert("There are no pending Financing Statements selected to update.");
        }
        break;

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

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

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

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

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

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

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

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

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

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

    case "RECENT":
      // Recent
      tabWizard_Refresh(0);
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  if (cmdFinish.text() == "Stop") {
    // Stop Process?
    widget.UI.MsgBoxConfirm("Are you sure you want to stop this process?\n\nNOTE: This may not take affect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
  }
  else {
    // Validate
    tabWizard_Validate(function () {
      // Confirmation Message
      var message = "";
      var hasChargeableItem = false;

      // Determine if there is at least one chargable item included
      for(var i = 0; i &lt; mFinancingStatements.length; i++) {
        var item = mFinancingStatements[i];

        if(item.Include &amp;&amp; item.CanInclude &amp;&amp; item.IsChargeable) {
          hasChargeableItem = true;
          break;
        }
      }

      // Build Message
      if (mRecord.CostCentreWarnOnCharge &amp;&amp; hasChargeableItem) {
        message += "WARNING: one or more updates will incur a fee.\n\n";
      }
      message += "Send Financing Statement updates to the PPSR";

      // Test Mode
      if (mRecord.TestMode) {
        message += " (Test Mode)?";
      }
      else {
        message += "?";
      }

      // Background Process
      message += "\n\nNOTE: You can close this form and any time and open it again to monitor the status of this process.";

      // Confirm
      var options = {
        heading: "Process PPSR Updates?",
        icon: "PPSR_NZ_Amend",
      }
      widget.UI.MsgBoxConfirm(message, options, function () { Form_ExecuteAction_FinishPost(); }, null);
    });
  }
}

function Form_ExecuteAction_FinishPost() {
  // Running new process
  mMonitoringExisting = false;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting PPSR NZ Update, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();

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

      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();

      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },

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

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

function Form_ExecuteAction_FinishStop() {
  // Continue
  widget.GetString("CancelBackgroundProcess", { processId: mProcessId },
    function (data) {
      widget.UI.MsgBoxInfo("The process has been requested to stop.");
    },

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  // Continue
  widget.GetString("GetBackgroundProcessStatus", { processId: mProcessId, lastEventId: mLastEventId },
    function (data) {
      data = JSON.parse(data);

      // Update Status
      mRecord_BackgroundProcessStatus = data;

      // Refresh Progress
      pageProgress_Refresh();

      // Status
      var Status = mRecord_BackgroundProcessStatus.Status;

      // Handle Status
      switch(Status) {
        case "Cancelled":
          // Cancelled
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("PPSR NZ Update was successfully cancelled.");
          break;

        case "Complete":
        case "CompleteWithErrors":
        case "CompleteWithWarnings":
          // Complete
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("PPSR NZ Update is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          break;

        case "Failed":
          // Failed
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("PPSR NZ Update failed to complete.");
          break;

        default:
          // Continue Polling
          window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 2500);

          // Prevent finPOWER Connect Cloud UI signing the User out
          widget.NotifyBusy();
      }
    },

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

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();
    }
  );
}

// ====================
// pageCurrentProcesses
// ====================
function pageCurrentProcesses_Refresh() {
  // Block UI
  widget.UI.Block("Refreshing Recent PPSR NZ Updates, please wait...");

  // Fetch
  widget.GetString("GetCurrentProcesses", {},
    function (data) {
      // Parse
      mRecord_CurrentProcesses = JSON.parse(data);

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

    function (error) {
      // Unblock UI
      widget.UI.Unblock();

      // Show Error
      widget.UI.MsgBoxAlert(error);
    }
  );
}

// ===============
// pageUpdateItems
// ===============
function pageUpdateItems_Refresh() {
  // Hide content
  frmMain.Visible(false);

  // Block UI
  widget.UI.Block("Getting Financing Statements, please wait...")

  // Parameters
  var params = CreateFinishParameters();

  // Get Financing Statements
  widget.GetString("GetUpdateItems", params,
    // Success
    function(data) {
      // Parse
      mFinancingStatements = JSON.parse(data);

      // Unblock
      widget.UI.Unblock();

      // Show content
      frmMain.Visible(true);

      // Refresh Grid
      gridUpdateItems_Refresh();
    },

    // Fail
    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();

      // Cancel
      tabWizard_Move(-1);

      // Show content
      frmMain.Visible(true);

      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );
}

/// ============
// pageProgress
// ============
function pageProgress_Refresh(clear) {
  if (clear) {    
    mLastProcessStatus = "";
    mLastEventId = "";
    mRecord_BackgroundProcessStatus = null;
    mRecord_CurrentProcesses = null;
  }
  else if (mRecord_BackgroundProcessStatus) {
    // Retrieve Last Process Status
    mLastProcessStatus = mRecord_BackgroundProcessStatus.StatusText;
  }

  // Build Progress
  mLastEventId = widget.UI.BuildBackgroundProcessProgress(C.divProgress, clear, mRecord_BackgroundProcessStatus);

  // Stop button valid?
  tabWizard_UpdateButtons()

  // Update Heading
  if (tabWizard.SelectedTabId() == "Progress") {
    if (mLastProcessStatus &amp;&amp; mLastProcessStatus.length != 0) {
      frmMain.RefreshHeading(mLastProcessStatus, "Processing progress.");
    }
    else {
      frmMain.RefreshHeading("Progress", "Processing progress.");
    }
  }
}

// ====================
// gridCurrentProcesses
// ====================
function gridCurrentProcesses_Refresh() {
  // Add Columns
  if (C.gridCurrentProcesses.ColumnCount() == 0) {
    C.gridCurrentProcesses.AddColumnDrilldown();
    C.gridCurrentProcesses.AddColumnString("StatusText", { caption: "Status" });
    C.gridCurrentProcesses.AddColumnDateTime("CreatedDate", { caption: "Started" });
  }

  // Refresh
  C.gridCurrentProcesses.VirtualDataRefresh(mRecord_CurrentProcesses);

  // Activate no rows
  C.gridCurrentProcesses.ActiveDataRowIndex(-1);
}

function gridCurrentProcesses_InitialiseRow(e) {
  var item = mRecord_CurrentProcesses[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Styles
  switch(item.Status) {
    case "Complete":
      e.row.cells.StatusText.colour = "green";
      break;

    case "CompleteWithErrors":
      e.row.cells.StatusText.colour = "darkred";
      break;

    case "CompleteWithWarnings":
      e.row.cells.StatusText.colour = "orange";
      break;

    case "Failed":
      e.row.cells.StatusText.colour = "red";
      break;

    case "Pending":
    case "InProgress":
    case "InProgressCancelRequested":
      e.row.bold = true;
      break;
  }
}

function gridCurrentProcesses_RowDrilldown(e) {
  var item = mRecord_CurrentProcesses[e.row.listIndex];

  // Switch to Progress Page
  mFromRecent = true;
  mMonitoringExisting = true;
  mProcessId = item.ProcessId;
  tabWizard_Refresh(3);
  pageProgress_Refresh(true);

  // Start monitoring
  Form_ExecuteAction_GetBackgroundProcessStatus();
}

// ===============
// gridUpdateItems
// ===============
function gridUpdateItems_Refresh() {
  var showWarnings = false;

  // Show / Hide Columns
  for (var i = 0; i &lt; mFinancingStatements.length; i++) {
    var item = mFinancingStatements[i];

    // Warnings
    if (item.Warnings) showWarnings = true;
  }

  // Add Columns
  C.gridUpdateItems.ClearColumns();
  C.gridUpdateItems.AddColumnIcon("Icon", { caption: "" });
  C.gridUpdateItems.AddColumnBoolean("Include", { caption: "Include", allowEdit: true, sortable: true });
  C.gridUpdateItems.AddColumnCode("SecurityStmtId", { caption: "Id", sortable: true });
  C.gridUpdateItems.AddColumnString("Description", { caption: "Description", sortable: true });
  C.gridUpdateItems.AddColumnString("RegisterStatus", { caption: "Status", sortable: true });
  C.gridUpdateItems.AddColumnString("RegisterAction", { caption: "Action", visible: false, sortable: true });
  C.gridUpdateItems.AddColumnString("RegisterActionStatus", { caption: "Action Status", sortable: true });
  C.gridUpdateItems.AddColumnString("FsId", { caption: "Registration Number", sortable: true });
  C.gridUpdateItems.AddColumnDate("DateRegistered", { caption: "Registered", sortable: true });
  C.gridUpdateItems.AddColumnDate("DateExpiry", { caption: "Expiry", sortable: true });
  C.gridUpdateItems.AddColumnString("Warnings", { caption: "Warnings / Errors", visible: showWarnings, sortable: true });

  // Actions
  C.gridUpdateItems.Actions().Define([{ actionId: "Refresh", tooltipText:"Refresh", icon: "Refresh" },
                                      {},
                                      { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                      { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },
                                      { actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                      { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                      { actionId: "SelectChecked", tooltipText: "Select all rows that are checked to include", icon: "Select_Checked" },
                                      { actionId: "SelectUnchecked", tooltipText: "Select all rows that are not checked to include", icon: "Select_Unchecked" },
                                      {},
                                      { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                      { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
                                     ]);

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mFinancingStatements.GetCacheKey = function (index) {
    var item = mFinancingStatements[index];
    return item.SecurityStmtId;
  };
  mFinancingStatements.GetPreviewFetchParameters = function (index) {
    var item = mFinancingStatements[index];
    var o = {};

    o.securityStmtId = item.SecurityStmtId;

    return o;
  };

  // Refresh
  C.gridUpdateItems.VirtualDataRefresh(mFinancingStatements);

  // Select first row
  C.gridUpdateItems.ActivateFirstDataRow();
}

function gridUpdateItems_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "REFRESH":
      pageUpdateItems_Refresh();
      break;

    case "SELECTUP":
      // Select Up
      // NOTE: Because this grid is sortable, we use ActiveDataRowIndex rather than ActiveDataRowListIndex
      var indexes = [];
      for (var i = C.gridUpdateItems.ActiveDataRowIndex(); i &gt;= 0; i--) {
        indexes.push(i);
      }
      
      // NOTE: Because this grid is sortable, we use SetSelectedRowIndexesForSortableGrid rather than SetSelectedRowIndexes
      C.gridUpdateItems.SetSelectedRowIndexesForSortableGrid(indexes, true);
      indexes = null;
      break;
    
    case "SELECTDOWN":
      // Select Down
      // NOTE: Because this grid is sortable, we use ActiveDataRowIndex rather than ActiveDataRowListIndex
      var indexes = [];
      for (var i = C.gridUpdateItems.ActiveDataRowIndex(); i &lt; mFinancingStatements.length; i++) {
        indexes.push(i);
      }
      
      // NOTE: Because this grid is sortable, we use SetSelectedRowIndexesForSortableGrid rather than SetSelectedRowIndexes
      C.gridUpdateItems.SetSelectedRowIndexesForSortableGrid(indexes, true);
      indexes = null;
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mFinancingStatements.length; i++) {
        var item = mFinancingStatements[i];
        if (item.CanInclude) indexes.push(i);
      }
      break;

    case "SELECTNONE":
      var indexes = [];
      break;

    case "SELECTCHECKED":
    case "SELECTUNCHECKED":
      var indexes = [];

      for(var i = 0; i &lt; mFinancingStatements.length; i++) {
        var item = mFinancingStatements[i];

        if(item.CanInclude) {
          if(actionId.toUpperCase() == "SELECTCHECKED" &amp;&amp; item.Include) {
            indexes.push(i);
          }
          else if(actionId.toUpperCase() == "SELECTUNCHECKED" &amp;&amp; !item.Include) {
            indexes.push(i);
          }
        }
      }
      break;

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

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mFinancingStatements[selectedItems[i]];
        if(item.CanInclude) item.Include = (actionId.toUpperCase() == "CHECK");
      }
      C.gridUpdateItems.VirtualDataRefresh(mFinancingStatements, true, { retainSelectedRows: true });
      break;

    default:
      break;
  }

  // Set Indexes
  if(indexes) {
    C.gridUpdateItems.SetSelectedVirtualDataRowIndexesForSortableGrid(indexes, true);
  }
}

function gridUpdateItems_AfterRowActivate(e) {
  // Preview
  wbUpdateItemSummary_Preview();
}

function gridUpdateItems_BeforeCellUpdate(e) {
  var item = mFinancingStatements[e.row.listIndex];

  switch(e.columnKey) {
    case "Include":
      item.Include = e.newValue;
      break;
  }
}

function gridUpdateItems_InitialiseRow(e) {
  var item = mFinancingStatements[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Invalid rows cannot be edited
  e.row.readOnly = !item.CanInclude;
  e.row.cells.Include.readOnly = !item.CanInclude;

  // Hyperlinks
  e.row.cells.SecurityStmtId.hyperlink = "app://FormShow?form=SecurityStmt&amp;id=" + widget.UI.HtmlEncode(item.SecurityStmtId);
}

function gridUpdateItems_RowDrilldown(e) {

}

// =======================
// chkIncludeRegistrations
// =======================
function chkIncludeRegistrations_Change(sender, e) {
  C.dateIncludeRegistrationsToDate.VisibleRow(C.chkIncludeRegistrations.Value());
}

// ====================
// chkIncludeAmendments
// ====================
function chkIncludeAmendments_Change(sender, e) {
  C.chkIncludeAmendmentsCheckForChanges.VisibleRow(C.chkIncludeAmendments.Value());
}

// ====================
// chkIncludeDischarges
// ====================
function chkIncludeDischarges_Change(sender, e) {
  C.dateIncludeDischargesToDate.VisibleRow(C.chkIncludeDischarges.Value());
}

// ==================
// chkIncludeRenewals
// ==================
function chkIncludeRenewals_Change(sender, e) {
  C.dateIncludeRenewalsToDate.VisibleRow(C.chkIncludeRenewals.Value());
}

// ========
// txtRange
// ========
function txtRange_ButtonClick(sender, e) {
  if (e.id == "Lookup") {
    var caption = sender.Element().attr("lookupCaption");
    var range = sender.Element().attr("id");

    range = range.substr(8);
    if(range.startsWith("Payee")) range = "ExternalParties" + range.substr(5);

    widget.UI.Forms.ShowRangeLookupFromStandardRange(range, sender.Text(), { caption: "Lookup " + caption},
      function (newRange) {
        sender.Text(newRange);
        sender.Focus();
      }
    );
  }
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params;

  // Parameters
  params = {
    includeAmendments: C.chkIncludeAmendments.Value(),
    includeAmendmentsCheckForChanges: C.chkIncludeAmendmentsCheckForChanges.Value(),
    includeDischarges: C.chkIncludeDischarges.Value(),
    includeDischargesToDate: C.dateIncludeDischargesToDate.Value(),
    includeRegistrations: C.chkIncludeRegistrations.Value(),
    includeRegistrationsToDate: C.dateIncludeRegistrationsToDate.Value(),
    includeRenewals: C.chkIncludeRenewals.Value(),
    includeRenewalsToDate: C.dateIncludeRenewalsToDate.Value(),

    rangeBranches: C.txtRangeBranches.Text(),
    rangeEntities: C.txtRangeEntities.Text(),
    rangeSecuredPartyGroups: C.txtRangeSecuredPartyGroups.Text(),
    rangeSecurityStatementGroups: C.txtRangeSecurityStmtGroups.Text(),
    rangeSecurityStatementIds: C.txtRangeSecurityStmts.Text(),

    securityStmtPks: CreateFinishParameters_SelectedItems(),
  }


  return params;
}

// ==============================
// Get Selected Security Stmt Pks
// ==============================
function CreateFinishParameters_SelectedItems() {
  var records = [];

  if (mFinancingStatements) {
    for(var i = 0; i &lt; mFinancingStatements.length; i++) {
      var item = mFinancingStatements[i];

      if(item.Include &amp;&amp; item.CanInclude) {
        records.push(item.SecurityStmtPk);
      }
    }
  }

  return records;
}

// =================
// Advanced handling
// =================
function AdvancedInitialise() {
  // Tweaks

  // General
  AdvancedInitialiseSection("Ranges", mRecord.ShowRangesHeading);
  AdvancedInitialiseSection("SecuredPartyGroups", mRecord.ShowSecuredPartyGroups);
  AdvancedInitialiseSection("Entities", mRecord.ShowEntities);
  AdvancedInitialiseSection("Branches", mRecord.ShowBranches);
  AdvancedInitialiseSection("SecurityStmtGroups", mRecord.ShowSecurityStmtGroups);
  AdvancedInitialiseSection("SecurityStmts", mRecord.ShowSecurityStmts);
}

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

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

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

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

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

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

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

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

// ===================
// wbUpdateItemSummary
// ===================
function wbUpdateItemSummary_Preview() {
  C.wbUpdateItemSummary.PreviewFromGridCollection(C.gridUpdateItems, mFinancingStatements, "GetUpdateItemPreview");
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "FORMCLOSE":
      // Closing Form
      if (mRecord &amp;&amp; mRecord.WorkflowId &amp;&amp; !mSearchResult) {
        widget.UI.MsgBoxConfirm("Closing this form without performing a Search will not action the Workflow Item.\n\nAre you sure you want to close this form?", {}, tabWizard_Cancel);
      }
      else {
        tabWizard_Cancel();
      }
      break;

    case "ITEMSHOW":
      // Show a Security Item in read-only mode
      // NOTE: When following a FormAction Application Shortcut, data will always be a URL String
      widget.ExecuteApplicationShortcutUrl("FormShow?form=SecurityStmtItem&amp;" + data + "&amp;readonly=true");
      break;

    default:
      break;
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>u4Ci2KJ+tUGDoH2xTthKiA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>PPSR_NZ_Amend</Icon>
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>If you do not specify a Default Transaction Type, the Transaction Type selection will be shown regardless of the settings specified below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowSecuredPartyGroups" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowEntities" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowBranches" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowSecurityStmtGroups" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowSecurityStmts" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>