<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-03-17T03:49:29.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-02-28T20:57:36.2830000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-03-17T03:48:53.8070000</UpdatedUtcDate>
    <ScriptId>PPSRSEARCH</ScriptId>
    <Description>PPSR NZ Search</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' HtmlWidget_PPSRNZSearch
Option Explicit On
Option Strict On

' #################################################################
' PPSR NZ Search wizard
'
' Version: 1.03 (17/03/2022)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.02  02/08/2021  ISS                Updated
'    1.03  17/03/2021  ISS      J028448   Fixed Nullable Date of Birth
' #################################################################

' Common Parameters
Private mAccountAppId As String
Private mAccountAppApplicantPk As Integer
Private mAccountAppCollateralPk As Integer
Private mClientId As String
Private mSecurityStmtId As String
Private mSecurityStmtItemPk As Integer
Private mWorkflowPk As Integer
Private mWorkflowItemPk As Integer

' 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

  Dim AccountAppApplicantPk As Integer
  Dim AccountAppId As String
  Dim ClientId As String

  ' 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")
    mAccountAppApplicantPk = .GetInteger("AccountAppApplicantPk")
    mAccountAppCollateralPk = .GetInteger("AccountAppCollateralPk")
    mClientId = .GetString("ClientId")
    mSecurityStmtId = .GetString("SecurityStmtId")
    mSecurityStmtItemPk = .GetInteger("SecurityStmtItemPk")
    mWorkflowPk = .GetInteger("WorkflowPk")
    mWorkflowItemPk = .GetInteger("WorkflowItemPk")
  End With

  ' Update Parameters from Workflow
  If mWorkflowPk &lt;&gt; 0 AndAlso mWorkflowItemPk &lt;&gt; 0 Then
    If finBL.HtmlWidgetUtilities.GetSourceObjectDetailsFromWorkflowItem(mWorkflowPk, mWorkflowItemPk, ClientId, "", AccountAppId, AccountAppApplicantPk) Then
      If mAccountAppApplicantPk = 0 Then mAccountAppApplicantPk = AccountAppApplicantPk
      If Len(mAccountAppId) = 0 Then mAccountAppId = AccountAppId
      If Len(mClientId) = 0 Then mClientId = ClientId
    End If
  End If

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

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

    Case "GetPreviousSearches"
      ' Get Previous PPSR NZ Searches
      Main = GetPreviousSearches(returnValue)

    Case "GetSearchResultHtml"
      ' Get Search Result HTML
      Main = GetSearchResultHtml(returnValue)

    Case "PerformSearch"
      ' Perform PPSR NZ Search
      Main = PerformSearch(parametersJson, returnValue)

    Case "UpdatePendingSearch"
      ' Update Pending Search
      Main = UpdatePendingSearch(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 Account Application.
''' &lt;/summary&gt;
Private Function GetAccountApp(ByRef accountApp As finAccountApp,
                               collateralItemDescription As String) As Boolean

  Dim AccountAppCollateralItem As finAccountAppCollateralItem
  Dim Client As finClient
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  accountApp = Nothing

  ' Initialise
  accountApp = finBL.CreateAccountApp()

  ' Load and Validate
  If accountApp.Load(mAccountAppId) Then
    If accountApp.IsNew Then
      Success = False
      finBL.Error.ErrorBegin("Invalid AccountAppId.")
    ElseIf mAccountAppApplicantPk &lt;&gt; 0 AndAlso Not accountApp.Applicants.ExistsPk(mAccountAppApplicantPk) Then
      Success = False
      finBL.Error.ErrorBegin("Invalid AccountAppApplicantPk.")
    ElseIf mAccountAppCollateralPk &lt;&gt; 0 AndAlso Not accountApp.CollateralItems.ExistsPk(mAccountAppCollateralPk) Then
      Success = False
      finBL.Error.ErrorBegin("Invalid AccountAppCollateralPk.")
    End If

    ' Get Account Applicant Applicant
    If Success AndAlso mAccountAppApplicantPk &lt;&gt; 0 Then
      If accountApp.Applicants.ItemByPk(mAccountAppApplicantPk).CreateClient(False, Client) Then
        mClientId = Client.ClientId
      Else
        Success = False
      End If
    End If

    ' Find Collateral Item from Description
    If Success AndAlso Len(collateralItemDescription) &lt;&gt; 0 Then
      For Each AccountAppCollateralItem In accountApp.CollateralItems
        If Len(AccountAppCollateralItem.Description) &lt;&gt; 0 Then
          If StrComp(AccountAppCollateralItem.Description, collateralItemDescription, CompareMethod.Text) = 0 Then
            mAccountAppCollateralPk = AccountAppCollateralItem.Pk
            Exit For
          End If
        End If
      Next
    End If

    ' Ensure Collateral is Aircraft or Motor Vehicle
    If Success AndAlso mAccountAppCollateralPk &lt;&gt; 0 Then
      Select Case accountApp.CollateralItems.ItemByPk(mAccountAppCollateralPk).SecurityBaseType
        Case isefinSecurityBaseType.Aircraft, isefinSecurityBaseType.MotorVehicle
          ' Ok
        Case Else
          Success = False
          finBL.Error.ErrorBegin("Invalid Account Application Collateral Base Type.")
      End Select
    End If
  Else
    Success = False
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Client Akas for PPSR use.
''' &lt;/summary&gt;
Private Function GetClientAkas(client As finClient) As List(Of ClientAka)

  Dim ClientAka As finClientAka
  Dim ClientAkas As List(Of ClientAka)
  Dim DefaultCompanyName As Boolean

  ' Initialise
  ClientAkas = New List(Of ClientAka)

  ' Add Akas
  If client.IsIndividualOrSoleTrader Then
    ' Client Name
    With client
      ClientAkas.Add(New ClientAka(.Title, .FirstName, .MiddleNames, .LastName, .Notes, .DateOfBirth, False, False))
    End With

    ' AKAs
    For Each ClientAka In client.Akas
      With ClientAka
        ClientAkas.Add(New ClientAka(.Title, .FirstName, .MiddleNames, .LastName, .Notes, .DateOfBirthResolved, False, False))
      End With
    Next
  Else
    ' Determine if the AKA Name should be defaulted for companies (only if there is no NZBN or Company Number)
    DefaultCompanyName = (Len(client.BusinessNumber) = 0 AndAlso Len(client.OrganisationNumber) = 0)

    ' Legal and Company Names
    If Len(client.LegalName) &lt;&gt; 0 Then
      ClientAkas.Add(New ClientAka("", client.LegalName, "", "", "", Nothing, DefaultCompanyName, True))
    End If
    ClientAkas.Add(New ClientAka("", client.Name, "", "", "", Nothing, DefaultCompanyName, True))

    ' AKAs
    For Each ClientAka In client.Akas
      ClientAkas.Add(New ClientAka("", ClientAka.Name, "", "", "", Nothing, DefaultCompanyName, True))
    Next
  End If

  Return ClientAkas

End Function

''' &lt;summary&gt;
'''  Get Collateral Type Codes from their Descriptions.
''' &lt;/summary&gt;
Private Function GetCollateralTypeCodesFromDescriptions(descriptions As String) As String

  Dim DescriptionsList As ISList
  Dim List As ISList
  Dim Request As ISSecurityRegistryRequest_PPSRNZ_Search
  Dim strTemp As String

  ' Initialise
  DescriptionsList = finBL.Runtime.CreateList()
  List = finBL.Runtime.CreateList()
  Request = finBL.SecurityRegistry.Service_PPSRNZ.CreateRequest_Search()

  ' Descriptions List
  DescriptionsList.FromCsvString(descriptions)

  ' Convert Descriptions to Code
  For Each strTemp In DescriptionsList
    List.Add(Request.Service.CodeDescriptionTable_CollateralTypes.GetCodeFromDescription(strTemp))
  Next

  Return List.ToCsvString()

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 AccountApp As finAccountApp
  Dim AccountAppCollateralItem As finAccountAppCollateralItem
  Dim AddressDetails As ISAddressDetails
  Dim Client As finClient
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim List As ISList
  Dim Request As ISSecurityRegistryRequest_PPSRNZ_Search
  Dim SecurityStmt As finSecurityStmt
  Dim SecurityStmtItemBase As finSecurityStmtItemBase
  Dim Success As Boolean
  Dim SearchByList As ISCodeDescriptionList

  ' Assume Success
  Success = True

  ' Initialise
  List = New ISList()
  Request = finBL.SecurityRegistry.Service_PPSRNZ.CreateRequest_Search()
  SearchByList = finBL.Runtime.CreateCodeDescriptionList()

  ' Validate
  If Request Is Nothing Then
    Success = False
    finBL.Error.ErrorBegin("This service is not availble.")
  ElseIf Len(mAccountAppId) = 0 AndAlso (mAccountAppApplicantPk &lt;&gt; 0 OrElse mAccountAppCollateralPk &lt;&gt; 0) Then
    Success = False
    finBL.Error.ErrorBegin("An AccountAppId must be specified if an Applicant or AccountAppCollateralPk has been supplied.")
  ElseIf Len(mSecurityStmtId) = 0 AndAlso mSecurityStmtItemPk &lt;&gt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("A SecurityStmtId must be specified if a SecurityStmtItemPk has been supplied.")
  ElseIf mAccountAppApplicantPk &lt;&gt; 0 AndAlso mAccountAppCollateralPk &lt;&gt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("An Applicant or Collateral can only be specified.")
  ElseIf mWorkflowPk &lt;&gt; 0 AndAlso Len(mSecurityStmtId) &lt;&gt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("Security Statements do not support Workflow integration.")
  ElseIf mWorkflowPk = 0 AndAlso mWorkflowItemPk &lt;&gt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("You must also specify the WorkflowPk if a Workflow Item has been specified.")
  ElseIf mWorkflowPk &lt;&gt; 0 AndAlso mWorkflowItemPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("You must also specify the WorkflowItemPk of the Workflow Item to Action if a Workflow has been specified.")
  End If

  ' Validate Id entry
  If Success Then
    If Len(mAccountAppId) &lt;&gt; 0 Then List.Add(mAccountAppId)
    If Len(mClientId) &lt;&gt; 0 Then List.Add(mClientId)
    If Len(mSecurityStmtId) &lt;&gt; 0 Then List.Add(mSecurityStmtId)

    If List.Count &gt; 1 Then
      Success = False
      finBL.Error.ErrorBegin("Only one of 'Account Application', 'Client' or 'Security Statement' can be specified.")
    End If
  End If

  ' Get Account Application
  If Success AndAlso Len(mAccountAppId) &lt;&gt; 0 Then
    Success = GetAccountApp(AccountApp, "")
  End If

  ' Get Client
  If Success AndAlso Len(mClientId) &lt;&gt; 0 Then
    Client = finBL.CreateClient()
    Success = Client.Load(mClientId)
  End If

  ' Get Security Statement
  If Success AndAlso Len(mSecurityStmtId) &lt;&gt; 0 Then
    Success = GetSecurityStmt(SecurityStmt, "")
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      ' -------------------
      ' Account Application
      ' -------------------
      If AccountApp IsNot Nothing Then
        .AccountAppId = AccountApp.AccountAppId
        .AccountAppName = AccountApp.Name

        If mAccountAppApplicantPk = 0 Then
          ' No Applicant specified - assume Collateral
          If mAccountAppCollateralPk = 0 Then
            ' No Collateral Item specified, preload all Aircraft &amp; Motor Vehicles
            For Each AccountAppCollateralItem In AccountApp.CollateralItems
              Select Case AccountAppCollateralItem.SecurityBaseType
                Case isefinSecurityBaseType.Aircraft, isefinSecurityBaseType.MotorVehicle
                  If Len(AccountAppCollateralItem.Description) &lt;&gt; 0 Then
                    .SecurityItems.Add(New SecurityItem(AccountAppCollateralItem))
                  End If
              End Select
            Next
          Else
            ' Security Item specified, only load the single item
            If AccountApp.CollateralItems.ExistsPk(mAccountAppCollateralPk) Then
              .AccountAppCollateralItemPk = mAccountAppCollateralPk
              .SecurityItems.Add(New SecurityItem(AccountApp.CollateralItems.ItemByPk(mAccountAppCollateralPk)))
            Else
              Success = False
              finBL.Error.ErrorBegin("Invalid Collateral Item.")
            End If
          End If

          ' Valid Search Types
          SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.PreviousSearch.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.PreviousSearch))
          SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.Aircraft.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.Aircraft))
          SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle))
        Else
          .AccountAppApplicantPk = mAccountAppApplicantPk

          ' Applicant Specified
          If AccountApp.Applicants.ItemByPk(mAccountAppApplicantPk).CreateClient(False, Client) Then
            ' Set Defaults
            If Len(Client.ClientId) = 0 Then
              Client.ClientId = "[NEW]"
            End If
          Else
            Success = False
          End If
        End If
      End If

      ' ------
      ' Client
      ' ------
      If Client IsNot Nothing Then
        .ClientAkas = GetClientAkas(Client)
        .ClientId = Client.ClientId
        .ClientName = Client.Name

        ' Address
        If finBL.Settings.WebServices.PPSRNZSearchIncludeCity AndAlso Len(Client.BusinessNumber) = 0 AndAlso Len(Client.OrganisationNumber) = 0 Then
          AddressDetails = Client.ContactAddresses.GetCurrentPhysicalAddress()
          If AddressDetails.HasValue Then
            If AddressDetails.HasValue Then
              .ClientTownCity = AddressDetails.City
            End If
          Else
            ' Try Postal
            AddressDetails = Client.ContactAddresses.GetCurrentPostalAddress()
            If AddressDetails.HasValue Then
              .ClientTownCity = AddressDetails.City
            End If
          End If
        End If

        ' Allow Previous Search
        SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.PreviousSearch.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.PreviousSearch))

        ' Individual / Organisation
        .ClientIsOrganisation = Client.IsOrganisation
        If .ClientIsOrganisation Then
          SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.DebtorOrganisation.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.DebtorOrganisation))

          .ClientNzbn = Client.BusinessNumber

          ' Only show Organisation Number if there is no NZBN
          If Len(.ClientNzbn) = 0 Then
            .ClientOrganisationNumber = Client.OrganisationNumber
          End If
        Else
          SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.DebtorPerson.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.DebtorPerson))
        End If
      End If

      ' ------------------
      ' Security Statement
      ' ------------------
      If SecurityStmt IsNot Nothing Then
        .SecurityStmtId = SecurityStmt.SecurityStmtId
        .SecurityStmtDescription = SecurityStmt.Description

        If mSecurityStmtItemPk = 0 Then
          ' No Security Item specified, preload all Aircraft &amp; Motor Vehicles
          For Each SecurityStmtItemBase In SecurityStmt.SecurityItems
            Select Case SecurityStmtItemBase.BaseType
              Case isefinSecurityBaseType.Aircraft, isefinSecurityBaseType.MotorVehicle
                .SecurityItems.Add(New SecurityItem(SecurityStmtItemBase))
            End Select
          Next
        Else
          ' Security Item specified, only load the single item
          .SecurityStmtItemPk = mSecurityStmtItemPk
          .SecurityItems.Add(New SecurityItem(SecurityStmt.SecurityItems.ItemByPk(mSecurityStmtItemPk)))
        End If

        ' Valid Search Types
        SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.PreviousSearch.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.PreviousSearch))
        SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.Aircraft.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.Aircraft))
        SearchByList.Add(iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle.ToString(), finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle))
      End If

      ' Workflow
      If mWorkflowPk &lt;&gt; 0 Then
        .WorkflowDescription = finBL.WorkflowFunctions.GetRecordCodeDescription(mWorkflowPk, .WorkflowId)
      End If

      ' Lists
      .CollateralTypes = Request.Service.CodeDescriptionTable_CollateralTypes.GetDescriptionsList().ToCsvString()
      If SearchByList.Count = 0 Then SearchByList = finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToCodeDescriptionList()
      .SearchByTypes = SearchByList.ToJsonObject()

      ' Configuration
      .CanViewServiceLog = finBL.CurrentUser.Permissions.Allow("ServiceLogs.View")
      .IsAdministrator = finBL.CurrentUser.IsAdministrator
      .TestMode = finBL.SettingsUser.CostCentreTestModeResolved

      ' Other
      .SearchFromDefaultDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get previous PPSR NZ Searches.
''' &lt;/summary&gt;
Private Function GetPreviousSearches(ByRef returnValue As String) As Boolean

  Dim DateFrom As Date
  Dim DateTo As Date
  Dim IncludeAllUsers As Boolean
  Dim IncludeFailed As Boolean
  Dim IncludePending As Boolean
  Dim PreviousSearchResults As List(Of PreviousSearchResult)
  Dim SecurityItemDescription As String
  Dim SecurityRegistryPreviousSearch As finSecurityRegistryPreviousSearch
  Dim SecurityRegistryPreviousSearches As finSecurityRegistryPreviousSearches
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    DateFrom = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateFrom"))
    DateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateTo"))
    IncludeAllUsers = .GetBoolean("IncludeAllUsers")
    IncludeFailed = .GetBoolean("IncludeFailed")
    IncludePending = .GetBoolean("IncludePending")
    SecurityItemDescription = .GetString("SecurityItemDescription")
  End With

  ' Initialise
  PreviousSearchResults = New List(Of PreviousSearchResult)
  SecurityRegistryPreviousSearches = finBL.SecurityRegistry.CreatePreviousSearches()

  ' Get Searches
  With SecurityRegistryPreviousSearches
    ' Update Items if required
    If Len(mAccountAppId) &lt;&gt; 0 AndAlso Len(SecurityItemDescription) &lt;&gt; 0 Then
      Success = GetAccountApp(Nothing, SecurityItemDescription)
    ElseIf Len(SecurityItemDescription) &lt;&gt; 0 Then
      Success = GetSecurityStmt(Nothing, SecurityItemDescription)
    End If

    ' Load Previous Searches
    If Len(mAccountAppId) &lt;&gt; 0 Then
      ' Account Application
      Success = .LoadAccountApp(mAccountAppId, DateFrom, DateTo, mAccountAppApplicantPk, mAccountAppCollateralPk, IncludeAllUsers, IncludePending, IncludeFailed)
    ElseIf Len(mClientId) &lt;&gt; 0 Then
      ' Client
      Success = .LoadClient(mClientId, DateFrom, DateTo, IncludeAllUsers, IncludePending, IncludeFailed)
    ElseIf Len(mSecurityStmtId) &lt;&gt; 0 Then
      ' Security Statement
      Success = .LoadSecurityStmt(mSecurityStmtId, DateFrom, DateTo, mSecurityStmtItemPk, IncludeAllUsers, IncludePending, IncludeFailed)
    Else
      ' Load all
      Success = .Load(DateFrom, DateTo, IncludeAllUsers, IncludePending, IncludeFailed)
    End If
  End With

  ' Add
  If Success Then
    For Each SecurityRegistryPreviousSearch In SecurityRegistryPreviousSearches
      PreviousSearchResults.Add(New PreviousSearchResult(SecurityRegistryPreviousSearch))
    Next
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get PPSR details about a Search Result.
''' &lt;/summary&gt;
Private Function GetSearchResultHtml(ByRef returnValue As String) As Boolean

  Dim ServiceLog As ISServiceLog
  Dim ServiceLogPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Service Log
  Success = finBL.Database.GetServiceLog(ServiceLogPk, ServiceLog)

  ' Get Result HTML
  If Success Then
    Success = finBL.SecurityRegistry.GetSecurityRegistryHtmlFromServiceLog(ServiceLog, "", False, False, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Security Statement.
''' &lt;/summary&gt;
Private Function GetSecurityStmt(ByRef securityStmt As finSecurityStmt,
                                 securityItemDescription As String) As Boolean

  Dim SecurityStmtItemBase As finSecurityStmtItemBase
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  securityStmt = Nothing

  ' Load and Validate
  If Len(mSecurityStmtId) &lt;&gt; 0 Then
    securityStmt = finBL.CreateSecurityStmt()

    If securityStmt.Load(mSecurityStmtId) Then
      If securityStmt.IsNew Then
        Success = False
        finBL.Error.ErrorBegin("Invalid SecurityStmtId.")
      ElseIf mSecurityStmtItemPk &lt;&gt; 0 AndAlso Not securityStmt.SecurityItems.ExistsPk(mSecurityStmtItemPk) Then
        Success = False
        finBL.Error.ErrorBegin("Invalid SecurityStmtItemPk.")
      End If

      ' Set Item
      If Success AndAlso Len(securityItemDescription) &lt;&gt; 0 Then
        For Each SecurityStmtItemBase In securityStmt.SecurityItems
          If StrComp(SecurityStmtItemBase.Description, securityItemDescription, CompareMethod.Text) = 0 Then
            mSecurityStmtItemPk = SecurityStmtItemBase.Pk
            Exit For
          End If
        Next
      End If

      ' Ensure Security Item is Aircraft or Motor Vehicle
      If Success AndAlso mSecurityStmtItemPk &lt;&gt; 0 Then
        Select Case securityStmt.SecurityItems.ItemByPk(mSecurityStmtItemPk).BaseType
          Case isefinSecurityBaseType.Aircraft, isefinSecurityBaseType.MotorVehicle
            ' Ok
          Case Else
            Success = False
            finBL.Error.ErrorBegin("Invalid Security Statement Item Base Type.")
        End Select
      End If
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Wizard Finish Parameters from JSON string.
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef wizardFinishParameters As WizardFinishParameters) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  wizardFinishParameters = Nothing

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Perform PPSR NZ Search.
''' &lt;/summary&gt;
Private Function PerformSearch(parametersJson As String,
                               ByRef returnValue As String) As Boolean

  Dim AccountAppLog As finAccountAppLog
  Dim ClientLog As finClientLog
  Dim Data As Object
  Dim Html As String
  Dim Request As ISSecurityRegistryRequest_PPSRNZ_Search
  Dim Response As ISSecurityRegistryResponse_PPSRNZ_Search
  Dim SecurityStmtLog As finSecurityStmtLog
  Dim SecurityStmtItemLog As finSecurityStmtItemLog
  Dim ServiceLog As ISServiceLog
  Dim ServiceLogCreateDetails As ISServiceLogCreateDetails
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise
  Request = finBL.SecurityRegistry.Service_PPSRNZ.CreateRequest_Search()

  ' Get Wizard Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Update Account Application Information if required
  If Success AndAlso Len(mAccountAppId) &lt;&gt; 0 Then
    Success = GetAccountApp(Nothing, WizardFinishParameters.SecurityItemDescription)
  End If

  ' Update Security Item if required
  If Success AndAlso Len(mSecurityStmtId) &lt;&gt; 0 Then
    Success = GetSecurityStmt(Nothing, WizardFinishParameters.SecurityItemDescription)
  End If

  ' Build Search
  If Success Then
    With Request
      ' Search
      .SearchByText = WizardFinishParameters.SearchBy
      .LegitimateSearchReason = WizardFinishParameters.LegitimateSearchReason

      Select Case .SearchBy
        Case iseSecurityRegistry_PPSRNZ_SearchBy.Aircraft
          ' Aircraft
          With .SearchByAircraft
            .RegistrationMark = WizardFinishParameters.AircraftRegistration
            .ManufacturerSerial = WizardFinishParameters.AircraftManufacturer
          End With

        Case iseSecurityRegistry_PPSRNZ_SearchBy.DebtorOrganisation
          ' Debtor Organisation
          With .SearchByDebtorOrganisation
            .ClientId = mClientId
            .OrganisationName = WizardFinishParameters.OrganisationName
            .NZBN = WizardFinishParameters.Nzbn
            .IncorporationNumber = WizardFinishParameters.CompanyNumber
            .CityTown = WizardFinishParameters.City
            .CollateralTypes = GetCollateralTypeCodesFromDescriptions(WizardFinishParameters.CollateralTypes)
          End With

        Case iseSecurityRegistry_PPSRNZ_SearchBy.DebtorPerson
          ' Debtor Person
          With .SearchByDebtorPerson
            .ClientId = mClientId
            .FirstName = WizardFinishParameters.FirstName
            .MiddleNames = WizardFinishParameters.MiddleNames
            .LastName = WizardFinishParameters.LastName
            .DateOfBirth = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.DateOfBirth)
            .CityTown = WizardFinishParameters.City
            .CollateralTypes = GetCollateralTypeCodesFromDescriptions(WizardFinishParameters.CollateralTypes)
          End With

        Case iseSecurityRegistry_PPSRNZ_SearchBy.FinancingStatements
          ' Financing Statements
          With .SearchByFinancingStatements
            .RegistrationNumbers = WizardFinishParameters.FinancingStatementRegistrationNumber
          End With

        Case iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle
          ' Motor Vehicle
          With .SearchByMotorVehicle
            .VIN = WizardFinishParameters.MotorVehicleVin
            .RegistrationPlate = WizardFinishParameters.MotorVehicleRegistration
            .Chassis = WizardFinishParameters.MotorVehicleChassis
          End With

        Case Else
          Success = False
          finBL.Error.ErrorBeginFormat("Unhandled Search By '{0}'.", .SearchByText)
      End Select
    End With
  End If

  ' Perform Search
  If Success Then
    If finBL.SecurityRegistry.Service_PPSRNZ.ExecuteSearch(Request, Response, ServiceLogCreateDetails) Then
      ' Get Service Log
      Success = finBL.Database.GetServiceLog(ServiceLogCreateDetails.ServiceLogPk, ServiceLog)
    Else
      Success = False
    End If
  End If

  ' Create Log
  If Success Then
    Select Case Request.SearchBy
      Case iseSecurityRegistry_PPSRNZ_SearchBy.Aircraft, iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle
        ' Aircraft / Motor Vehicle - Security Statement / Item Log
        If Len(mAccountAppId) &lt;&gt; 0 Then
          ' Account Application
          AccountAppLog = finBL.CreateAccountAppLog()
          With AccountAppLog
            ' Set Properties
            .AccountAppId = mAccountAppId
            .AccountAppApplicantPk = mAccountAppApplicantPk
            .AccountAppCollateralItemPk = mAccountAppCollateralPk
            .LogType = isefinLogType.Service
            .SourceSet(isefinLogSource.UserInterface)
            .Subject = "PPSR Search - " &amp; Request.SearchByText
            .Notes = Request.SearchByDescription
            .ServiceLogPk = ServiceLogCreateDetails.ServiceLogPk

            ' Workflow
            .WorkflowPk = mWorkflowPk
            .WorkflowItemPk = mWorkflowItemPk

            ' Save
            Success = .Save()
          End With
        ElseIf mSecurityStmtItemPk &lt;&gt; 0 Then
          ' Security Statement Item Log
          SecurityStmtItemLog = finBL.CreateSecurityStmtItemLog()
          With SecurityStmtItemLog
            ' Set Properties
            .SecurityStmtItemPk = mSecurityStmtItemPk
            .LogType = isefinLogType.Service
            .SourceSet(isefinLogSource.UserInterface)
            .Subject = "PPSR Search - " &amp; Request.SearchByText
            .Notes = Request.SearchByDescription
            .ServiceLogPk = ServiceLogCreateDetails.ServiceLogPk

            ' Workflow
            .WorkflowPk = mWorkflowPk
            .WorkflowItemPk = mWorkflowItemPk

            ' Save
            Success = .Save()
          End With
        ElseIf Len(mSecurityStmtId) &lt;&gt; 0 Then
          ' Security Statement Log
          SecurityStmtLog = finBL.CreateSecurityStmtLog()
          With SecurityStmtLog
            ' Set Properties
            .SecurityStmtId = mSecurityStmtId
            .LogType = isefinLogType.Service
            .SourceSet(isefinLogSource.UserInterface)
            .Subject = "PPSR Search - " &amp; Request.SearchByText
            .Notes = Request.SearchByDescription
            .ServiceLogPk = ServiceLogCreateDetails.ServiceLogPk

            ' Workflow
            .WorkflowPk = mWorkflowPk
            .WorkflowItemPk = mWorkflowItemPk

            ' Save
            Success = .Save()
          End With
        End If

      Case iseSecurityRegistry_PPSRNZ_SearchBy.DebtorOrganisation, iseSecurityRegistry_PPSRNZ_SearchBy.DebtorPerson
        If Len(mAccountAppId) &lt;&gt; 0 Then
          ' Account Application
          AccountAppLog = finBL.CreateAccountAppLog()
          With AccountAppLog
            ' Set Properties
            .AccountAppId = mAccountAppId
            .AccountAppApplicantPk = mAccountAppApplicantPk
            .AccountAppCollateralItemPk = mAccountAppCollateralPk
            .LogType = isefinLogType.Service
            .SourceSet(isefinLogSource.UserInterface)
            .Subject = "PPSR Search - " &amp; Request.SearchByText
            .Notes = Request.SearchByDescription
            .ServiceLogPk = ServiceLogCreateDetails.ServiceLogPk

            ' Workflow
            .WorkflowPk = mWorkflowPk
            .WorkflowItemPk = mWorkflowItemPk

            ' Save
            Success = .Save()
          End With
        End If

        ' Client
        If Len(mClientId) &lt;&gt; 0 Then
          ClientLog = finBL.CreateClientLog()
          With ClientLog
            ' Set Properties
            .ClientId = mClientId
            .LogType = isefinLogType.Service
            .SourceSet(isefinLogSource.UserInterface)
            .Subject = "PPSR Search - " &amp; Request.SearchByText
            .Notes = Request.SearchByDescription
            .ServiceLogPk = ServiceLogCreateDetails.ServiceLogPk

            ' Workflow
            .WorkflowPk = mWorkflowPk
            .WorkflowItemPk = mWorkflowItemPk

            ' Save
            Success = .Save()
          End With
        End If
    End Select
  End If

  ' Get Summary
  If Success Then
    Success = finBL.SecurityRegistry.GetSecurityRegistryHtmlFromServiceLog(ServiceLog, Nothing, False, False, Html)
  End If

  ' Action Workflow Item
  If Success AndAlso mWorkflowPk &lt;&gt; 0 Then
    finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, Warning)

    If Len(Warning) &lt;&gt; 0 Then
      Warning = "The PPSR NZ Search completed successfully, however the Workflow Item could not be actioned due to the following error:" &amp; vbNewLine &amp; vbNewLine &amp; Warning
    End If
  End If

  ' Response
  If Success Then
    Data = New With {
      .ServiceLogPk = ServiceLogCreateDetails.ServiceLogPk,
      .Html = Html,
      .Warning = Warning
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Update Pending PPSR NZ Search.
''' &lt;/summary&gt;
Private Function UpdatePendingSearch(ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim SearchSuccessful As Boolean
  Dim ServiceLogPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Update
  Success = finBL.SecurityRegistry.Service_PPSRNZ.UpdatePendingSearch(ServiceLogPk, SearchSuccessful)

  ' Response
  If Success Then
    Data = New With {
      .SearchSuccessful = SearchSuccessful
    }
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, 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 ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim strTemp As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' 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

  ' Initialise
  ConfirmList = New List(Of String)

  ' Validate Page
  Select Case PageId
    Case "General"
      ' Deserialise
      Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

      ' Search By
      If Success Then
        Select Case finBL.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_FromString(WizardFinishParameters.SearchBy)
          Case iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle
            ' Motor Vehicle
            If Not finBL.CurrentCountry.ValidateVIN(WizardFinishParameters.MotorVehicleVin, "", strTemp) Then
              ConfirmList.Add(strTemp)
            End If
        End Select
      End If

      Data = ConfirmList
  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;
'''  Client AKA.
''' &lt;/summary&gt;
Public Class ClientAka

  Public DateOfBirth As Date?
  Public DateOfBirthDefault As Date?
  Public DefaultCompanyNumber As String
  Public DefaultNzbn As String
  Public FirstName As String
  Public FirstNameDefault As String
  Public LastName As String
  Public LastNameDefault As String
  Public MiddleNames As String
  Public MiddleNamesDefault As String
  Public Notes As String
  Public Pk As Integer
  Public Title As String

  Public Sub New(title As String,
                 firstName As String,
                 middleNames As String,
                 lastName As String,
                 notes As String,
                 dateOfBirth As Date,
                 defaultCompanyName As Boolean,
                 isOrganisation As Boolean)

    Me.DateOfBirth = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(dateOfBirth)
    Me.FirstName = firstName
    Me.LastName = lastName
    Me.MiddleNames = middleNames
    Me.Notes = notes
    Me.Title = title

    ' Default Values for Search
    If isOrganisation Then
      If defaultCompanyName Then
        If finBLShared.Settings.WebServices.PPSRNZSearchUseNameWildcards Then
          Me.FirstNameDefault = Trim(Left(Me.FirstName, 6)) &amp; "*"
        Else
          Me.FirstNameDefault = Me.FirstName
        End If
      End If
    Else
      ' First Names
      If finBLShared.Settings.WebServices.PPSRNZSearchUseNameWildcards Then
        Me.FirstNameDefault = Trim(Left(Me.FirstName, 2)) &amp; "*"
        Me.LastNameDefault = Trim(Left(Me.LastName, 4)) &amp; "*"
      Else
        Me.FirstNameDefault = Me.FirstName
        Me.LastNameDefault = Me.LastName
      End If

      ' Middle Names
      If finBLShared.Settings.WebServices.PPSRNZSearchIncludeMiddleNames Then
        Me.MiddleNamesDefault = Me.MiddleNames
      End If

      ' Date of Birth
      If finBLShared.Settings.WebServices.PPSRNZSearchIncludeDateOfBirth Then
        Me.DateOfBirthDefault = Me.DateOfBirth
      End If
    End If

  End Sub

End Class



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

  ' Record
  Public AccountAppId As String
  Public AccountAppName As String
  Public AccountAppApplicantPk As Integer
  Public AccountAppCollateralItemPk As Integer
  Public ClientAkas As List(Of ClientAka)
  Public ClientId As String
  Public ClientIsOrganisation As Boolean
  Public ClientName As String
  Public ClientNzbn As String
  Public ClientOrganisationNumber As String
  Public ClientTownCity As String
  Public SearchFromDefaultDate As Date
  Public SecurityStmtDescription As String
  Public SecurityStmtId As String
  Public SecurityStmtItemPk As Integer
  Public WorkflowId As String
  Public WorkflowDescription As String

  ' Lists
  Public CollateralTypes As String
  Public SearchByTypes As Object
  Public SecurityItems As New List(Of SecurityItem)

  ' Configuration
  Public CanViewServiceLog As Boolean
  Public FormHeading As String
  Public IsAdministrator As Boolean
  Public TestMode As Boolean

End Class



''' &lt;summary&gt;
'''  Previous Search Result.
''' &lt;/summary&gt;
Public Class PreviousSearchResult

  Public [Date] As Date
  Public Request As String
  Public Results As Integer
  Public SearchBy As String
  Public ServiceLogPk As Integer
  Public Status As String
  Public UserId As String

  Public Sub New(securityRegistryPreviousSearch As finSecurityRegistryPreviousSearch)

    With securityRegistryPreviousSearch
      Me.Request = .GetFriendlyRequestText()

      With .ServiceLogs(0)
        Me.Date = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(.CreatedDate)
        If TypeName(.ExResponse) = "ISSecurityRegistryResponse_PPSRNZ_Search" Then
          Me.Results = DirectCast(.ExResponse, ISSecurityRegistryResponse_PPSRNZ_Search).TotalItems
        End If
        Me.SearchBy = .ProductOptions
        Me.ServiceLogPk = .Pk
        Me.Status = .RequestStatusText
        Me.UserId = finBLShared.Users.ItemByPkSafe(.CreatedUserPk).UserId
      End With
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Security Item.
''' &lt;/summary&gt;
Public Class SecurityItem

  Public AircraftManufacturer As String
  Public AircraftRegistration As String
  Public Description As String
  Public MotorVehicleChassis As String
  Public MotorVehicleRegistration As String
  Public MotorVehicleVin As String
  Public SearchBy As String

  ''' &lt;summary&gt;
	'''  Account Application Collateral Item.
	''' &lt;/summary&gt;
  Public Sub New(collateralItem As finAccountAppCollateralItem)

    Me.Description = collateralItem.Description

    Select Case collateralItem.SecurityType.BaseType
      Case isefinSecurityBaseType.Aircraft
        Me.SearchBy = finBLShared.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.Aircraft)
        With collateralItem
          Me.AircraftManufacturer = .ManufacturerSerialNumber
          Me.AircraftRegistration = .RegistrationMark
        End With

      Case isefinSecurityBaseType.MotorVehicle
        Me.SearchBy = finBLShared.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle)
        With collateralItem
          Me.MotorVehicleChassis = .Chassis
          Me.MotorVehicleRegistration = .RegistrationNumber
          Me.MotorVehicleVin = .VIN
        End With
    End Select

  End Sub

  ''' &lt;summary&gt;
	'''  Security Statement Item
	''' &lt;/summary&gt;
  Public Sub New(securityStmtItemBase As finSecurityStmtItemBase)

    Me.Description = securityStmtItemBase.Description

    Select Case securityStmtItemBase.SecurityType.BaseType
      Case isefinSecurityBaseType.Aircraft
        Me.SearchBy = finBLShared.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.Aircraft)
        With securityStmtItemBase.ItemAsAircraft
          Me.AircraftManufacturer = .ManufacturerSerialNumber
          Me.AircraftRegistration = .RegistrationMark
        End With

      Case isefinSecurityBaseType.MotorVehicle
        Me.SearchBy = finBLShared.SecurityRegistry.Enums.iseSecurityRegistry_PPSRNZ_SearchBy_ToString(iseSecurityRegistry_PPSRNZ_SearchBy.MotorVehicle)
        With securityStmtItemBase.ItemAsMotorVehicle
          Me.MotorVehicleChassis = .Chassis
          Me.MotorVehicleRegistration = .RegistrationNumber
          Me.MotorVehicleVin = .VIN
        End With
    End Select

  End Sub

End Class



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

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

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

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

  End Sub

End Class



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

  ' General
  Public City As String
  Public CollateralTypes As String
  Public LegitimateSearchReason As Boolean
  Public SearchBy As String
  Public SecurityItemDescription As String

  ' Aircraft
  Public AircraftRegistration As String
  Public AircraftManufacturer As String

  ' Debtor Organisation
  Public CompanyNumber As String
  Public NZBN As String
  Public OrganisationName As String

  ' Debtor Person
  Public DateOfBirth As Date?
  Public FirstName As String
  Public LastName As String
  Public MiddleNames As String

  ' Financing Statement
  Public FinancingStatementRegistrationNumber As String

  ' Motor Vehicle
  Public MotorVehicleChassis As String
  Public MotorVehicleRegistration As String
  Public MotorVehicleVin As String

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

Used as a finPOWER Connect Cloud compatible version of the "PPSRNZSearch" form.</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="General" tooltipText="Select the type of search to perform."&gt;PPSR NZ Search&lt;/li&gt;
        &lt;li tabId="PreviousSearch" tooltipText="Load Previous Searches."&gt;Previous Search&lt;/li&gt;
        &lt;li tabId="DebtorSearch" tooltipText="Enter Client Details."&gt;Debtor Search&lt;/li&gt;
        &lt;li tabId="SearchResults" tooltipText="Search Results."&gt;Summary&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- General --&gt;
    &lt;div id="pageGeneral" style="display:flex;flex-direction:column;"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;!-- Workflow --&gt;
        &lt;tbody id="tbWorkflow"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblWorkflow"&gt;Workflow details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboWorkflow"&gt;Workflow:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboWorkflow" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Client --&gt;
        &lt;tbody id="tbClient"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblClient"&gt;Client details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboClient"&gt;Client:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboClient" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Security Statement --&gt;
        &lt;tbody id="tbSecurityStmt"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblSecurityStmt"&gt;Security details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboSecurityStmt"&gt;Security:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboSecurityStmt" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboSecurityStmtItem"&gt;Item:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboSecurityStmtItem" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Search Type --&gt;
        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblSearchType"&gt;Select the type of Search to perform&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboSearchBy"&gt;Search By:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboSearchBy" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Declaration --&gt;
        &lt;tbody id="tbDeclaration"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblDeclaration"&gt;Declaration&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;td colspan="2"&gt;&lt;label id="lblDeclarationText"&gt;I am aware of the requirements of S173 of the Personal Property Securities Act 1993 and declare that I am conducting this search for legitimate purposes only.&lt;/label&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkDeclaration" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Aircraft --&gt;
        &lt;tbody id="tbAircraft"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAircraft"&gt;Enter Aircraft details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtRegistrationMark"&gt;Registration&amp;nbsp;Mark:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtRegistrationMark" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtManufacturerNumber"&gt;Manufacturer&amp;nbsp;No.:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtManufacturerNumber" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Financing Statement --&gt;
        &lt;tbody id="tbFinancingStatement"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblFinancingStatement"&gt;Enter Financing Statement Registration Number&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtFinancingStatement"&gt;Registration&amp;nbsp;No.:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtFinancingStatement" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Motor Vehicle --&gt;
        &lt;tbody id="tbMotorVehicle"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblMotorVehicle"&gt;Enter Motor Vehicle details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtVin"&gt;VIN:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtVin" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtChassis"&gt;Chassis:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtChassis" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtRegistration"&gt;Registration:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtRegistration" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Client AKAs --&gt;
        &lt;tbody id="tbClientAka"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblClientAka"&gt;Also Known As&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;

      &lt;!-- Client AKAs --&gt;
      &lt;div style="flex-grow:1;position:relative;margin-top:8px;"&gt;
        &lt;div id="gridClientAka" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Previous Search --&gt;
    &lt;div id="pagePreviousSearch" style="display:flex;flex-direction:column;"&gt;
      &lt;!-- Filters --&gt;
      &lt;div&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;
            &lt;th&gt;&lt;label id="lblSearchDates"&gt;Select the Search dates for filtering&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;
              From:&amp;nbsp;&lt;input id="dateSearchFrom" /&gt;
              &amp;nbsp;to:&amp;nbsp;&lt;input id="dateSearchTo" /&gt;
            &lt;/th&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th&gt;&lt;label id="lblOtherOptions"&gt;Other Options&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;input id="chkOptionsAllUsers" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;input id="chkOptionsPendingSearches" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;input id="chkOptionsFailedSearches" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;button id="cmdLoadPreviousSearches" class="is-button ok"&gt;Load&lt;/button&gt; &lt;div id="divSearchInformation" class="is-info-text info small" style="display:none"&gt;&lt;/div&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;!-- Previous Searches --&gt;
      &lt;div style="flex-grow:1;position:relative;margin-top:8px;"&gt;
        &lt;div id="gridPreviousSearches" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Debtor Search --&gt;
    &lt;div id="pageDebtorSearch"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;!-- Individual --&gt;
        &lt;tbody id="tbIndividualClient"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblPersonsDetails"&gt;Persons Details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtFirstName"&gt;First Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtFirstName" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtMiddleNames"&gt;Middle Names:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtMiddleNames" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtLastName"&gt;Last Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtLastName" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateDateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateDateOfBirth" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Organisation --&gt;
        &lt;tbody id="tbOrganisationClient"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblOrganisationDetails"&gt;Organisation's Details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtOrganisationName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtOrganisationName" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtNzbn"&gt;NZBN:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNzbn" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtCompanyNumber"&gt;Company Number:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtCompanyNumber" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtCity"&gt;City or Town:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtCity" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblCollateralTypes"&gt;Collateral Types.&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="clCollateralTypes"&gt;Collateral Types:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="clCollateralTypes" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Search Results --&gt;
    &lt;div id="pageSearchResults"&gt;
      &lt;div id="wbSearchResults" class="is-dock-fill"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&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_ClientAkas;
var mRecord_SecurityItems;

var mSearchBy;
var mSearchResult;
var mPreviousSearchResults;
var mPreviousSearchServiceLogPk;

// Controls
var C = {
  //   General
  tbWorkflow: null,
  lblWorkflow: null,
  cboWorkflow: null,

  tbClient: null,
  lblClient: null,
  cboClient: null,

  tbSecurityStmt: null,
  lblSecurityStmt: null,
  cboSecurityStmt: null,
  cboSecurityStmtItem: null,

  lblSearchType: null,
  cboSearchBy: null,

  tbDeclaration: null,
  lblDeclaration: null,
  lblDeclarationText: null,
  chkDeclaration: null,

  tbAircraft: null,
  lblAircraft: null,
  txtRegistrationMark: null,
  txtManufacturerNumber: null,

  tbFinancingStatement: null,
  lblFinancingStatement: null,
  txtFinancingStatement: null,

  tbMotorVehicle: null,
  lblMotorVehicle: null,
  txtVin: null,
  txtChassis: null,
  txtRegistration: null,

  tbClientAka: null,
  lblClientAka: null,
  gridClientAka: null,

  //   Previous Searches
  lblSearchDates: null,
  dateSearchFrom: null,
  dateSearchTo: null,

  lblOtherOptions: null,
  chkOptionsAllUsers: null,
  chkOptionsPendingSearches: null,
  chkOptionsFailedSearches: null,

  divSearchInformation: null,

  gridPreviousSearches: null,

  //   Debtor Search
  tbIndividualClient: null,
  lblPersonsDetails: null,
  txtFirstName: null,
  txtMiddleNames: null,
  txtLastName: null,
  dateDateOfBirth: null,

  tbOrganisationClient: null,
  lblOrganisationDetails: null,
  txtOrganisationName: null,
  txtNzbn: null,
  txtCompanyNumber: null,

  txtCity: null,

  lblCollateralTypes: null,
  clCollateralTypes: null,

  //   Search Results
  wbSearchResults: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdLoadPreviousSearches;

// Other
var mDeclarationVisible = true;
var mLastFinishParametersJson = "";

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

  // Controls
  //   General
  C.tbWorkflow = $("#tbWorkflow");
  C.lblWorkflow = widget.UI.Label("lblWorkflow", {});
  C.cboWorkflow = widget.UI.DBCombo("cboWorkflow", {
    readOnly: true,
    showDropdown: false,
  });

  C.tbClient = $("#tbClient");
  C.lblClient = widget.UI.Label("lblClient", {});
  C.cboClient = widget.UI.DBCombo("cboClient", {
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.tbSecurityStmt = $("#tbSecurityStmt");
  C.lblSecurityStmt = widget.UI.Label("lblSecurityStmt", {});
  C.cboSecurityStmt = widget.UI.DBCombo("cboSecurityStmt", {
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.cboSecurityStmtItem = widget.UI.ComboBox("cboSecurityStmtItem", {
    limitToList: true,
    maxLength: 50,

    onChange: cboSecurityStmtItem_Change,
  });

  C.lblSearchType = widget.UI.Label("lblSearchType", {});
  C.cboSearchBy = widget.UI.ComboBox("cboSearchBy", {
    allowBlank: false,

    onChange: cboSearchBy_Change,
  });

  C.tbDeclaration = $("#tbDeclaration");
  C.lblDeclaration = widget.UI.Label("lblDeclaration", {});
  C.lblDeclarationText = widget.UI.Label("lblDeclarationText", {
    style: "normal"
  });
  C.chkDeclaration = widget.UI.CheckBox("chkDeclaration", {
    caption: "I agree",
    captionWrap: true,

    onChange: chkDeclaration_Change,
  });

  C.tbAircraft = $("#tbAircraft");
  C.lblAircraft = widget.UI.Label("lblAircraft", {});
  C.txtRegistrationMark = widget.UI.TextBox("txtRegistrationMark", {
    maxLength: 30,
  });
  C.txtManufacturerNumber = widget.UI.TextBox("txtManufacturerNumber", {
    maxLength: 30,
  });

  C.tbFinancingStatement = $("#tbFinancingStatement");
  C.lblFinancingStatement = widget.UI.Label("lblFinancingStatement", {});
  C.txtFinancingStatement = widget.UI.TextBox("txtFinancingStatement", {
    allowBlank: false,
    maxLength: 16,
  });

  C.tbMotorVehicle = $("#tbMotorVehicle");
  C.lblMotorVehicle = widget.UI.Label("lblMotorVehicle", {});
  C.txtVin = widget.UI.TextBox("txtVin", {
    maxLength: 30,
  });
  C.txtChassis = widget.UI.TextBox("txtChassis", {
    maxLength: 30,
  });
  C.txtRegistration = widget.UI.TextBox("txtRegistration", {
    maxLength: 10,
  });

  C.tbClientAka = $("#tbClientAka");
  C.lblClientAka = widget.UI.Label("lblClientAka", {
    tooltipText: "Select a row below to prepopulate details on the next page."
  });

  //   Previous Searches
  C.lblSearchDates = widget.UI.Label("lblSearchDates", {});
  C.dateSearchFrom = widget.UI.DateBox("dateSearchFrom", {});
  C.dateSearchTo = widget.UI.DateBox("dateSearchTo", {});

  C.lblOtherOptions = widget.UI.Label("lblOtherOptions", {});
  C.chkOptionsAllUsers = widget.UI.CheckBox("chkOptionsAllUsers", {
    caption: "Return Searches from all Users?",
    captionWrap: true,
  });
  C.chkOptionsPendingSearches = widget.UI.CheckBox("chkOptionsPendingSearches", {
    caption: "Include Pending Searches?",
    captionWrap: true,
  });
  C.chkOptionsFailedSearches = widget.UI.CheckBox("chkOptionsFailedSearches", {
    caption: "Include Failed Searches?",
    captionWrap: true,
  });

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

  //   Debtor Search
  C.tbIndividualClient = $("#tbIndividualClient");
  C.lblPersonsDetails = widget.UI.Label("lblPersonsDetails", {});
  C.txtFirstName = widget.UI.TextBox("txtFirstName", {
    allowBlank: false,
    maxLength: 50,
  });
  C.txtMiddleNames = widget.UI.TextBox("txtMiddleNames", {
    maxLength: 50,
  });
  C.txtLastName = widget.UI.TextBox("txtLastName", {
    allowBlank: false,
    maxLength: 50,
  });
  C.dateDateOfBirth = widget.UI.DateBox("dateDateOfBirth", {
    historic: true,
  });

  C.tbOrganisationClient = $("#tbOrganisationClient");
  C.lblOrganisationDetails = widget.UI.Label("lblOrganisationDetails", {});
  C.txtOrganisationName = widget.UI.TextBox("txtOrganisationName", {
    maxLength: 50,
  });
  C.txtNzbn = widget.UI.TextBox("txtNzbn", {
    maxLength: 20,
  });
  C.txtCompanyNumber = widget.UI.TextBox("txtCompanyNumber", {
    maxLength: 20,
  });

  C.txtCity = widget.UI.TextBox("txtCity", {
    maxLength: 50,
  });

  C.lblCollateralTypes = widget.UI.Label("lblCollateralTypes", {});
  C.clCollateralTypes = widget.UI.CheckList("clCollateralTypes", {});

  //   Search Results
  C.wbSearchResults = widget.UI.PreviewPane("wbSearchResults", {});

  // Grids
  C.gridClientAka = widget.UI.Grid("gridClientAka", {
    stickyHeader: true,

    onInitialiseRow: gridClientAka_InitialiseRow,
    onRowDrilldown: gridClientAka_RowDrilldown,
  });
  C.gridPreviousSearches = widget.UI.Grid("gridPreviousSearches", {
    stickyHeader: true,

    onInitialiseRow: gridPreviousSearches_InitialiseRow,
    onRowDrilldown: gridPreviousSearches_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"); });

  cmdLoadPreviousSearches = $("#cmdLoadPreviousSearches");
  cmdLoadPreviousSearches.click(GetPreviousSearches);

  // 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_ClientAkas = null;
  mRecord_SecurityItems = null;

  mSearchResult = null;
  mPreviousSearchResults = [];
  mPreviousSearchServiceLogPk = 0;

  // 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_ClientAkas = mRecord.ClientAkas;
      mRecord_SecurityItems = mRecord.SecurityItems;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mRecord.SearchByTypes, "Description");

      // Load Fields
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboWorkflow.RefreshUnbound(mRecord.WorkflowId, mRecord.WorkflowDescription);
    C.cboClient.RefreshUnbound(mRecord.ClientId, mRecord.ClientName);
    C.cboSearchBy.Text(mRecord.SearchByDefault);

    // Account Application or Security Statement
    if (mRecord.SecurityStmtId) {
      C.cboSecurityStmt.RefreshUnbound(mRecord.SecurityStmtId, mRecord.SecurityStmtDescription);
    }
    else if (mRecord.AccountAppId) {
      C.cboSecurityStmt.RefreshUnbound(mRecord.AccountAppId, mRecord.AccountAppName);
    }

    C.txtRegistrationMark.Text(mRecord.AircraftRegistration);
    C.txtManufacturerNumber.Text(mRecord.AircraftManufacturer);

    C.txtVin.Text(mRecord.MotorVehicleVin);
    C.txtChassis.Text(mRecord.MotorVehicleChassis);
    C.txtRegistration.Text(mRecord.MotorVehicleRegistration);

    // Previous Searches
    C.dateSearchFrom.Value(mRecord.SearchFromDefaultDate);
  }

  // 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) {
    // cboSecurityStmtItem
    C.cboSecurityStmtItem.ListFromCollection(mRecord_SecurityItems, "Description");
    if (mRecord_SecurityItems.length == 1) C.cboSecurityStmtItem.ListIndex(0);

    // cboSearchBy
    C.cboSearchBy.ListFromCodeDescriptionList(mRecord.SearchByTypes);
    if (mRecord.SearchByTypes.length == 1) {
      C.cboSearchBy.ListIndex(0);
      C.cboSearchBy.ReadOnly(true);
    }

    // Other
    C.clCollateralTypes.ListFromCsvString(mRecord.CollateralTypes);
  }

  // Controls
  if (mRecord) {
    if (!mRecord.WorkflowId) C.tbWorkflow.hide();

    if (mRecord.ClientId) {
      gridClientAka_Refresh();
    }
    else {
      C.tbClient.hide();
    }

    if ((!mRecord.SecurityStmtId &amp;&amp; !mRecord.AccountAppId) || mRecord.AccountAppApplicantPk) C.tbSecurityStmt.hide();
    if (mRecord.AccountAppId) C.cboSecurityStmt.Caption("Application:")

    C.cboSecurityStmtItem.ReadOnly(mRecord.SecurityStmtItemPk != 0 || mRecord.AccountAppCollateralItemPk != 0);

    if (!mRecord.IsAdministrator) C.chkOptionsAllUsers.VisibleRow(false);
    C.chkOptionsPendingSearches.Value(true);

    // Change Events
    cboSecurityStmtItem_Change();
    cboSearchBy_Change();
  }

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

  // Exceptions
  cmdCancel.hide();
  cmdFinish.text("Close");

  // Page Exceptions
  switch (tabWizard.SelectedTabId()) {
    case "PreviousSearch":
      cmdNext.prop("disabled", true);
      break;
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // General
      C.cboWorkflow.WidthResizeFromParent();
      C.cboClient.WidthResizeFromParent();
      C.cboSecurityStmt.WidthResizeFromParent();
      C.cboSecurityStmtItem.WidthResizeFromParent();

      C.txtRegistrationMark.WidthResizeFromParent();
      C.txtManufacturerNumber.WidthResizeFromParent();

      C.txtFinancingStatement.WidthResizeFromParent();

      C.txtVin.WidthResizeFromParent();
      C.txtChassis.WidthResizeFromParent();
      C.txtRegistration.WidthResizeFromParent();
      break;

    case "DebtorSearch":
      // Debtor Search
      C.txtFirstName.WidthResizeFromParent();
      C.txtMiddleNames.WidthResizeFromParent();
      C.txtLastName.WidthResizeFromParent();

      C.txtOrganisationName.WidthResizeFromParent();
      C.txtNzbn.WidthResizeFromParent();
      C.txtCompanyNumber.WidthResizeFromParent();

      C.txtCity.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)) {
        case "PreviousSearch":
          found = (mSearchBy.Code == "PreviousSearch");
          break;

        case "DebtorSearch":
          found = (mSearchBy.Code == "DebtorPerson" || mSearchBy.Code == "DebtorOrganisation");
          break;

        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 "PreviousSearch":
        pagePreviousSearch_Refresh();
        break;

      case "DebtorSearch":
        pageDebtorSearch_Refresh();
        break;

      case "SearchResults":
        pageSearchResults_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    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":
        // Declaration
        if (mDeclarationVisible &amp;&amp; !C.chkDeclaration.Value()) {
          Ok = false;
          widget.UI.MsgBoxAlert("You must agree to the declaration before continuing.");
        }

        // Search By Validation
        if (Ok) {
          switch (mSearchBy.Code) {
            case "Aircraft":
              if (C.txtRegistrationMark.Text().length == 0 &amp;&amp; C.txtManufacturerNumber.Text().length == 0) {
                Ok = false;
                widget.UI.MsgBoxAlert("Registration Mark or Manufacturer Serial Number must be entered.");
              }
              break;

            case "MotorVehicle":
              if (C.txtVin.Text().length == 0 &amp;&amp; C.txtChassis.Text().length == 0 &amp;&amp; C.txtRegistration.Text().length == 0) {
                Ok = false;
                widget.UI.MsgBoxAlert("VIN, Chassis Number or Registration must be entered.");
              }
              break;
          }
        }
        break;

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

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

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

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

// ==================
// pagePreviousSearch
// ==================
function pagePreviousSearch_Refresh() {
  // Refresh Grid
  gridPreviousSearches_Refresh();

  // Populate Search Information if required
  var message = "";
  if (mRecord.ClientId) {
    // Client Id
    message = "Search results are limited to Client &lt;b&gt;" + widget.UI.HtmlEncode(mRecord.ClientId) + "&lt;/b&gt;, '" + widget.UI.HtmlEncode(mRecord.ClientName) + "'";

    // Account Application
    if (mRecord.AccountAppId) {
      message += " in the context of Account Application &lt;b&gt;" + widget.UI.HtmlEncode(mRecord.AccountAppId) + "&lt;/b&gt;, '" + widget.UI.HtmlEncode(mRecord.AccountAppName) + "'.";
    }
    else {
      message += ".";
    }
  }
  else if (mRecord.SecurityStmtId) {
    // Security Statement
    if (C.cboSecurityStmtItem.Text()) {
      message = "Search results are limited to Security Item &lt;b&gt;" + widget.UI.HtmlEncode(C.cboSecurityStmtItem.Text()) + "&lt;/b&gt; for Security Statement &lt;b&gt;" + widget.UI.HtmlEncode(mRecord.SecurityStmtId) + "&lt;/b&gt;, '" + widget.UI.HtmlEncode(mRecord.SecurityStmtDescription) + "'.";
    }
    else {
      message = "Search results are limited to Security Statement &lt;b&gt;" + widget.UI.HtmlEncode(mRecord.SecurityStmtId) + "&lt;/b&gt;, '" + widget.UI.HtmlEncode(mRecord.SecurityStmtDescription) + "'.";
    }
  }
  else if (mRecord.AccountAppId) {
    // Account Application
    if (C.cboSecurityStmtItem.Text()) {
      message = "Search results are limited to Collateral Item &lt;b&gt;" + widget.UI.HtmlEncode(C.cboSecurityStmtItem.Text()) + "&lt;/b&gt; for Account Application &lt;b&gt;" + widget.UI.HtmlEncode(mRecord.AccountAppId) + "&lt;/b&gt;, '" + widget.UI.HtmlEncode(mRecord.AccountAppName) + "'.";
    }
    else {
      message = "Search results are limited to Account Application &lt;b&gt;" + widget.UI.HtmlEncode(mRecord.AccountAppId) + "&lt;/b&gt;, '" + widget.UI.HtmlEncode(mRecord.AccountAppName) + "'.";
    }
  }

  // Show
  if (message) {
    C.divSearchInformation.html(message);
    C.divSearchInformation.show();
  }
  else {
    C.divSearchInformation.hide();
  }
}

// ================
// pageDebtorSearch
// ================
function pageDebtorSearch_Refresh() {
  var clientDetails;

  // Initialise
  C.tbIndividualClient.hide();
  C.tbOrganisationClient.hide();

  if (mRecord_ClientAkas) {
    // Get Client Details from loaded Client
    if (C.gridClientAka.ActiveDataRowIndex() == -1) {
      clientDetails = mRecord_ClientAkas[0];
    }
    else {
      clientDetails = mRecord_ClientAkas[C.gridClientAka.ActiveDataRowIndex()];
    }

    // Load Fields
    if (mRecord.ClientIsOrganisation) {
      // Organisation
      C.txtOrganisationName.Text(clientDetails.FirstNameDefault);
      C.txtNzbn.Text(mRecord.ClientNzbn);
      C.txtCompanyNumber.Text(mRecord.ClientOrganisationNumber);

      C.tbOrganisationClient.show();
    }
    else {
      // Individual
      C.txtFirstName.Text(clientDetails.FirstNameDefault);
      C.txtMiddleNames.Text(clientDetails.MiddleNamesDefault);
      C.txtLastName.Text(clientDetails.LastNameDefault);
      C.dateDateOfBirth.Value(clientDetails.DateOfBirthDefault);

      C.tbIndividualClient.show();
    }

    // Shared Fields
    C.txtCity.Text(mRecord.ClientTownCity);
  }
  else {
    // No Client Loaded
    if (mSearchBy.Code == "DebtorPerson") {
      C.tbIndividualClient.show();
    }
    else {
      C.tbOrganisationClient.show();
    }
  }
}

// =================
// pageSearchResults
// =================
function pageSearchResults_Refresh() {
  if (mLastFinishParametersJson != JSON.stringify(CreateFinishParameters())) {
    // Hide content
    frmMain.Visible(false);

    // Confirmation Message
    var message = "WARNING: This function incurs a cost.\n\nFor more information please refer to the Terms and Conditions of your Agreement with this Service provider.\n\nAre you sure you want to continue";
    if (mRecord.TestMode) {
      message += " (Test Mode)?";
    }
    else {
      message += "?";
    }

    // Search
    widget.UI.MsgBoxConfirm(message, { heading: "Perform PPSR NZ Search" }, PerformSearch, function() {
      // Cancel
      tabWizard_Move(-1);

      // Show content
      frmMain.Visible(true);
    });
  }
}

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

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

// =================
// Finish Parameters
// =================
function CreateFinishParameters() {
  var params = {
    SearchBy: mSearchBy.Description,
    LegitimateSearchReason: C.chkDeclaration.Value(),
  }

  // Search By
  switch (mSearchBy.Code) {
    case "Aircraft":
      params.AircraftRegistration = C.txtRegistrationMark.Text();
      params.AircraftManufacturer = C.txtManufacturerNumber.Text();
      params.SecurityItemDescription = C.cboSecurityStmtItem.Text();
      break;

    case "DebtorOrganisation":
      params.OrganisationName = C.txtOrganisationName.Text();
      params.Nzbn = C.txtNzbn.Text();
      params.CompanyNumber = C.txtCompanyNumber.Text();
      params.City = C.txtCity.Text();
      params.CollateralTypes = C.clCollateralTypes.Text();
      break;

    case "DebtorPerson":
      params.FirstName = C.txtFirstName.Text();
      params.MiddleNames = C.txtMiddleNames.Text();
      params.LastName = C.txtLastName.Text();
      params.DateOfBirth = C.dateDateOfBirth.Value();
      params.City = C.txtCity.Text();
      params.CollateralTypes = C.clCollateralTypes.Text();
      break;

    case "FinancingStatements":
      params.FinancingStatementRegistrationNumber = C.txtFinancingStatement.Text();
      break;

    case "MotorVehicle":
      params.MotorVehicleChassis = C.txtChassis.Text();
      params.MotorVehicleRegistration = C.txtRegistration.Text();
      params.MotorVehicleVin = C.txtVin.Text();
      params.SecurityItemDescription = C.cboSecurityStmtItem.Text();
      break;

    case "PreviousSearch":
      break;

    default:
      window.alert("Unhandled SearchBy '" + mSearchBy.Description + "'.");
      break;
  }

  return params;
}

// ======================
// Perform PPSR NZ Search
// ======================
function PerformSearch() {
  // Block UI
  widget.UI.Block("Performing Search, please wait...");

  // Params
  var params = CreateFinishParameters();

  // Search
  widget.GetString("PerformSearch", params, PerformSearch_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();

    // Cancel
    tabWizard_Move(-1);

    // Show content
    frmMain.Visible(true);

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

function PerformSearch_Done(data) {
  // Parse
  mSearchResult = JSON.parse(data);

  // Refresh Summary
  wbSearchResults_Refresh(mSearchResult.Html);

  // Last Parameters
  mLastFinishParametersJson = JSON.stringify(CreateFinishParameters());

  // Unblock
  widget.UI.Unblock();

  // Show content
  frmMain.Visible(true);
  
  // Refresh Parent if actioning a Workflow Item
  if (mRecord.WorkflowItemPk != 0) {
    widget.RefreshParent();
  }

  // Warning
  if (mSearchResult.Warning) {
    widget.UI.MsgBoxAlert(mSearchResult.Warning);
  }
}

// ===========
// cboSearchBy
// ===========
function cboSearchBy_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Show / Hide Declaration
  mDeclarationVisible = true;
  mSearchBy = mRecord.SearchByTypes.GetItem(C.cboSearchBy.Text());
  if (mSearchBy) {
    mDeclarationVisible = (mSearchBy.Code != "PreviousSearch");
  }

  if (mDeclarationVisible) {
    C.tbDeclaration.show();
  }
  else {
    C.tbDeclaration.hide();
  }

  // Update Controls
  chkDeclaration_Change();
}

// ===================
// cboSecurityStmtItem
// ===================
function cboSecurityStmtItem_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Reset
  C.txtRegistrationMark.Text("");
  C.txtManufacturerNumber.Text("");

  C.txtVin.Text("");
  C.txtChassis.Text("");
  C.txtRegistration.Text("");

  // Find item and update item defaults
  for (var i = 0; i &lt; mRecord_SecurityItems.length; i++) {
    var item = mRecord_SecurityItems[i];

    if (item.Description == C.cboSecurityStmtItem.Text()) {
      C.cboSearchBy.Text(item.SearchBy);

      C.txtRegistrationMark.Text(item.AircraftRegistration);
      C.txtManufacturerNumber.Text(item.AircraftManufacturer);

      C.txtVin.Text(item.MotorVehicleVin);
      C.txtChassis.Text(item.MotorVehicleChassis);
      C.txtRegistration.Text(item.MotorVehicleRegistration);
      break;
    }
  }

  // Update Controls
  cboSearchBy_Change();
}

// ==============
// chkDeclaration
// ==============
function chkDeclaration_Change(sender, e) {
  // Initialise
  C.tbAircraft.hide();
  C.tbFinancingStatement.hide();
  C.tbMotorVehicle.hide();
  C.tbClientAka.hide();
  C.gridClientAka.Visible(false);

  // Determine which controls to show
  if (mSearchBy) {
    if (!mDeclarationVisible || (mDeclarationVisible &amp;&amp; C.chkDeclaration.Value())) {
      switch (mSearchBy.Code) {
        case "Aircraft":
          C.tbAircraft.show();
          break;

        case "DebtorPerson":
        case "DebtorOrganisation":
          if (mRecord.ClientId) {
            if (mRecord_ClientAkas.length &gt; 1) {
              C.tbClientAka.show();
              C.gridClientAka.Visible(true);
            }
          }
          break;

        case "FinancingStatements":
          C.tbFinancingStatement.show();
          break;

        case "MotorVehicle":
          C.tbMotorVehicle.show();
          break;
      }
    }
  }
}

// ===================
// GetPreviousSearches
// ===================
function GetPreviousSearches() {
  // Block UI
  widget.UI.Block("Performing Search, please wait...");

  // Params
  var params = {
    dateFrom: C.dateSearchFrom.Value(),
    dateTo: C.dateSearchTo.Value(),
    includeAllUsers: C.chkOptionsAllUsers.Value(),
    includeFailed: C.chkOptionsFailedSearches.Value(),
    includePending: C.chkOptionsPendingSearches.Value(),
    securityItemDescription: C.cboSecurityStmtItem.Text(),
  }

  // Search
  widget.GetString("GetPreviousSearches", params, GetPreviousSearches_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();

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

function GetPreviousSearches_Done(data) {
  mPreviousSearchResults = JSON.parse(data);

  // Refresh
  C.gridPreviousSearches.VirtualDataRefresh(mPreviousSearchResults);

  // Select item in Grid
  if (mPreviousSearchServiceLogPk != 0) {
    for (var i = 0; i &lt; mPreviousSearchResults.length; i++) {
      var item = mPreviousSearchResults[i];

      if (item.ServiceLogPk == mPreviousSearchServiceLogPk) {
        C.gridPreviousSearches.ActiveDataRowListIndex(i);
        break;
      }
    }
  }

  // Unblock
  widget.UI.Unblock();

  // Show previously selected log
  if (mPreviousSearchServiceLogPk != 0) {
    // Show updated log
    ViewServiceLog(mPreviousSearchServiceLogPk);

    // Reset
    mPreviousSearchServiceLogPk = 0;
  }
}

// =============
// gridClientAka
// =============
function gridClientAka_Refresh() {
  // Name caption
  var NameCaption = mRecord.ClientIsOrganisation ? "Name" : "First Name";

  // Add Columns
  C.gridClientAka.ClearColumns();
  C.gridClientAka.AddColumnString("Title", { caption: "Title", visible: !mRecord.ClientIsOrganisation });
  C.gridClientAka.AddColumnString("FirstName", { caption: NameCaption });
  C.gridClientAka.AddColumnString("MiddleNames", { caption: "Middle Names", visible: !mRecord.ClientIsOrganisation });
  C.gridClientAka.AddColumnString("LastName", { caption: "Last Name", visible: !mRecord.ClientIsOrganisation });
  C.gridClientAka.AddColumnString("Notes", { caption: "Notes" });

  // Actions

  // Refresh
  C.gridClientAka.VirtualDataRefresh(mRecord_ClientAkas);

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

function gridClientAka_InitialiseRow(e) {
  var item = mRecord_ClientAkas[e.row.listIndex];

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

function gridClientAka_RowDrilldown(e) {
  tabWizard_Move(1);
}

// ====================
// gridPreviousSearches
// ====================
function gridPreviousSearches_Refresh() {
  // Add Columns
  C.gridPreviousSearches.ClearColumns();
  C.gridPreviousSearches.AddColumnDrilldown();
  C.gridPreviousSearches.AddColumnDateTime("Date", { caption: "Date" });
  C.gridPreviousSearches.AddColumnString("UserId", { caption: "User" });
  C.gridPreviousSearches.AddColumnString("Status", { caption: "Status", width: "5em" });
  C.gridPreviousSearches.AddColumnInteger("Results", { caption: "Results" });
  C.gridPreviousSearches.AddColumnString("SearchBy", { caption: "Search By", width: "12em" });
  C.gridPreviousSearches.AddColumnString("Request", { caption: "Request" });

  // Actions

  // Refresh
  C.gridPreviousSearches.VirtualDataRefresh(mPreviousSearchResults);
}

function gridPreviousSearches_InitialiseRow(e) {
  var item = mPreviousSearchResults[e.row.listIndex];

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

function gridPreviousSearches_RowDrilldown(e) {
  var item = mPreviousSearchResults[e.row.listIndex];

  if (item.Status == "Pending") {
    widget.UI.MsgBoxConfirm("Retrieve the original Search's status from the PPSR?", {}, function() { UpdatePendingSearch(item.ServiceLogPk); });
  }
  else {
    ViewServiceLog(item.ServiceLogPk);
  }
}

// ==============================
// Update a Pending Search Status
// ==============================
function UpdatePendingSearch(pk) {
  // Block UI
  widget.UI.Block("Getting Status, please wait...");

  // Params
  var params = {
    serviceLogPk: pk
  }

  // Take note of selected Pk to default later
  mPreviousSearchServiceLogPk = pk;

  // Update Search
  widget.GetString("UpdatePendingSearch", params, UpdatePendingSearch_Done, function(errorMessage) {
    // Reset
    mPreviousSearchServiceLogPk = 0;

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

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

function UpdatePendingSearch_Done(data) {
  // Parse
  data = JSON.parse(data);

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

  // Message
  var message = "";
  if (data.SearchSuccessful) {
    message = "Search was successful, results will now be refreshed to display the updated search details.";
  }
  else {
    message = "Search FAILED, results will now be refreshed to display the updated details.";

    // Ensure failed result is included in search
    C.chkOptionsFailedSearches.Value(true);
  }

  // Refresh Previous Searches
  widget.UI.MsgBoxInfo(message, {}, GetPreviousSearches);
}

// ========================
// View PPSR NZ Service Log
// ========================
function ViewServiceLog(pk) {
  if (mRecord.CanViewServiceLog) {
    widget.ExecuteApplicationShortcutUrl("FormShow?form=ServiceLog&amp;page=PPSR*&amp;id=" + pk);
  }
  else {
    widget.ExecuteApplicationShortcutUrl("HtmlShowFunction?function=ServiceReport&amp;ServiceLogPk=" + pk);
  }
}

// ===============
// wbSearchResults
// ===============
function wbSearchResults_Refresh(html) {
  if (html) {
    // Set Content
    C.wbSearchResults.SetContent(html, false);
  }
  else if(mSearchResult) {
    // Get Html from Service Log
    var params = {
      ServiceLogPk: mSearchResult.ServiceLogPk,
    }

    // Get HTML
    widget.GetString("GetSearchResultHtml", params,
      // Success
      function(data) {
        wbSearchResults_Refresh(data);
      },

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

// ====================
// 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 "SECURITYREGISTRY.REFRESH":
      // Search Results Refresh
      wbSearchResults_Refresh(null);
      break;

    default:
      break;
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>120</TimeoutSeconds>
    <UniqueId>m-sQ2hHTnUK+xVLuKuAUHA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon>PPSR_NZ_Search</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>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="AccountAppApplicantPk" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="AccountAppCollateralPk" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="ClientId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Clients</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="SecurityStmtId" 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.SecurityStmts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="SecurityStmtItemPk" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="WorkflowPk" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="WorkflowItemPk" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>