<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-18T03:55:17.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-09-18T03:40:11.1550000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-18T03:44:25.0670000</UpdatedUtcDate>
    <ScriptId>HWNZGOVORGE</ScriptId>
    <Description>NZ Government (NZBN) Organisation Enquiry</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_NZGovernment_Organisation
Option Explicit On
Option Strict On

' ####################################################################
' New Zealand Government (NZBN) Enquiry wizard HTML Widget
'
' Copyright (C) Intersoft Systems Limited 2022
'
' Version: 1.08 (18/09/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.04  11/07/2022  ISS      J028905   Show readonly cost centre information
'    1.05  22/07/2022  ISS      J026867   Implement supported products
'          15/08/2022  ISS      J029337   Fixed issue where Cost Centre validation was skipped for "NZCO Entity Role Search" Product
'    1.06  16/03/2023  ISS      J030537   Default product update
'    1.07  28/05/2024  ISS      J033598   Added Print button
'    1.08  18/09/2024  ISS      J029950   Changed the Workflow Executor to the finBL.HtmlWidgetUtilities.WorkflowItemComplete function
' #################################################################

' Constants
Private Const CHARGEABLE_DEFAULT As Boolean = False
Private Const FORM_KEY As String = "NZGovernment_Organisation"
Private Const SERVICE_ID As String = "NZGovernment"
Private Const SUPPORTED_PRODUCTS As String = "NZBN Entity Details v4, NZCO Entity Role Search"

' Common Parameters
Private mAccountAppId As String
Private mAccountAppApplicantPk As Integer
Private mBranchId As String
Private mClientId As String
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

  ' 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")
    mBranchId = .GetString("BranchId")
    mClientId = .GetString("ClientId")
    mWorkflowPk = .GetInteger("WorkflowPk")
    mWorkflowItemPk = .GetInteger("WorkflowItemPk")
  End With

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

    Case "GetBranchDefaults"
      ' Get Branch Defaults
      Main = GetBranchDefaults(returnValue)

    Case "GetClientSummary"
      ' Get Client Summary
      Main = GetClientSummary(parametersJson, returnValue)

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

    Case "GetOptions"
      ' Get Options
      Main = GetOptions(parametersJson, returnValue)

    Case "GetServiceReport"
      ' Get Service Report
      Main = GetServiceReport(parametersJson, returnValue)

    Case "PerformEnquiry"
      ' Perform Enquiry
      Main = PerformEnquiry(parametersJson, 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 Branch Defaults
''' &lt;/summary&gt;
Private Function GetBranchDefaults(ByRef returnValue As String) As Boolean

  Dim BranchId As String
  Dim CostCentreResolved_NZGovernment As finCostCentreResolved_NZGovernment
  Dim Data As Object
  Dim DefaultProduct As String
  Dim Success As Boolean
  Dim SupportedProducts As ISList

  ' Assume Success
  Success = True

  ' Initialise
  SupportedProducts = New ISList(SUPPORTED_PRODUCTS)

  ' Parameters
  With mCombinedParameters
    BranchId = .GetString("BranchId")
  End With

  ' Get Cost Centre
  CostCentreResolved_NZGovernment = finBL.CostCentresResolved.ItemByBranchId(BranchId).NZGovernment

  ' Get Default Product
  DefaultProduct = ""
  If Len(DefaultProduct) = 0 Then
    DefaultProduct = finBL.CreditBureau.GetServiceDefaultEnquiryProduct(SERVICE_ID, iseProductTarget.Company, BranchId)
  End If

  ' Check Default Product is supported
  If SupportedProducts.Count = 0 Then
    DefaultProduct = ""
  ElseIf Not SupportedProducts.Exists(DefaultProduct, True) Then
    DefaultProduct = SupportedProducts(0)
  End If

  ' Create Response
  Data = New With {
    .DefaultProduct = DefaultProduct
  }
  
  ' Serialise
  Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)

  Return Success

End Function

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

  Dim AccountApp As finAccountApp
  Dim AccountAppApplicant As finAccountAppApplicant
  Dim BranchRO As finBranchRO
  Dim Client As finClient
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim List As ISListReadOnly
  Dim strTemp As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If Len(mClientId) = 0 AndAlso (Len(mAccountAppId) = 0 OrElse mAccountAppApplicantPk = 0) Then
    Success = False
    finBL.Error.ErrorBegin("Client Id or Account Application Applicant details not specified.")
  ElseIf Len(mClientId) &lt;&gt; 0 AndAlso finBL.CurrentUserInformation.IsClientFilteredOut(mClientId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Client.")
  ElseIf Len(mAccountAppId) &lt;&gt; 0 AndAlso finBL.CurrentUserInformation.IsAccountAppFilteredOut(mAccountAppId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Account Application.")
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  End If

  ' Get Client or Applicant objects
  If Success Then
    Success = GetClientOrApplicant(Client, AccountApp, AccountAppApplicant)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()

    ' Other Properties
    With FormInitialisationInfo
      ' General
      If Client IsNot Nothing Then
        .BranchId = Client.BranchId
        .ClientId = Client.ClientId
        .ClientName = Client.Name
      End If
      If accountApp IsNot Nothing Then
        .AccountAppId = AccountApp.AccountAppId
        .AccountAppName = AccountApp.Name
        .AccountAppApplicantPk = AccountAppApplicant.Pk
        .AccountAppApplicantName = AccountAppApplicant.Name
      End If
      .WorkflowPk = mWorkflowPk

      ' Branch
      .BranchId = mBranchId
      If Len(.BranchId) = 0 AndAlso AccountApp IsNot Nothing Then .BranchId = AccountApp.BranchId
      If Len(.BranchId) = 0 AndAlso Client IsNot Nothing Then .BranchId = Client.BranchId

      ' Client Summary
      If GetClientSummary("", strTemp) Then
        .ClientSummary = strTemp
      End If

      ' Lists
      For Each BranchRO In finBL.Branches
        .Branches.Add(New BranchInfo(BranchRO, SERVICE_ID))
      Next
      'List = finBL.CreditBureau.GetServiceProductIdsList(SERVICE_ID, iseProductClass.CreditEnquiry, iseProductTarget.Company, False)
      List = finBL.Runtime.CreateListReadOnly(SUPPORTED_PRODUCTS)
      .ProductsList = List.ToCsvString()

      ' Defaults
      If List.Count = 1 Then
        .DefaultProduct = List(0)
      Else
        .DefaultProduct = finBL.CreditBureau.GetServiceDefaultEnquiryProduct(SERVICE_ID, iseProductTarget.Company, .BranchId)
        If Not List.Exists(.DefaultProduct) Then
          finBL.Trace.WriteWarning(String.Format("Default product {0} not supported by this HTML Widget.", .DefaultProduct))
          .DefaultProduct = List(0)
        End If
      End If

      ' Configuration
      .AllowBranch = Len(mBranchId) &lt;&gt; 0
      .ShowBranch = finBL.Settings.AddOns.CostCentre
      .ChargeableDefault = CHARGEABLE_DEFAULT
      .ServiceName = finBL.CreditBureau.GetServiceName(SERVICE_ID)
      .TestMode = finBL.SettingsUser.CostCentreTestModeResolved
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Creates a Credit Enquiry Request for a Client
''' &lt;/summary&gt;
Private Function CreateCreditEnquiryRequestForClient(branchId As String,
                                                     product As String,
                                                     ByRef creditEnquiryRequest As ISCreditEnquiryRequest) As Boolean

  Dim Client As finClient
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Client or Applicant objects
  Success = GetClientOrApplicant(Client, Nothing, Nothing)

  ' Create Request
  If Success Then
    creditEnquiryRequest = finBL.CreditBureau.CreateCreditEnquiryRequest(SERVICE_ID, iseProductClass.CreditEnquiry, product, branchId)
    If creditEnquiryRequest Is Nothing Then
      Success = False
      finBL.Error.ErrorBeginFormat("Unhandled Product '{0}'.", product)
    End If
  End If

  ' Update
  If Success Then
    If finBL.CreditBureau.UpdateCreditEnquiryRequestOptions(creditEnquiryRequest, Client) Then
      Success = finBL.CreditBureau.UpdateCreditEnquiryRequestFromClient(creditEnquiryRequest, Client, False)
    Else
      Success = False
    End If
  End If

  ' Update with specified Branch
  If Success Then
    If Len(branchId) &lt;&gt; 0 AndAlso finBL.Branches.Exists(branchId) Then
      creditEnquiryRequest.BranchPk = finBL.Branches(branchId).Pk
    Else
      creditEnquiryRequest.BranchPk = Client.BranchPk
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get a finClient and, optionally, a finAccountAppApplicant object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function GetClientOrApplicant(ByRef client As finClient,
                                      ByRef accountApp As finAccountApp,
                                      ByRef accountAppApplicant As finAccountAppApplicant) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  client = Nothing
  accountApp = Nothing
  accountAppApplicant = Nothing

  ' Initialise
  If Len(mClientId) = 0 Then
    ' Applicant
    accountApp = finBL.CreateAccountApp()
    If accountApp.Load(mAccountAppId) Then
      If accountApp.Applicants.ExistsPk(mAccountAppApplicantPk) Then
        accountAppApplicant = accountApp.Applicants.ItemByPk(mAccountAppApplicantPk)

        ' Create Client from Applicant
        Success = accountAppApplicant.CreateClient(True, client)
      Else
        Success = False
        finBL.Error.ErrorBegin("Applicant not found for this Account Application.")
      End If
    Else
      Success = False
    End If
  Else
    ' Client
    client = finBL.CreateClient()
    Success = client.Load(mClientId)
  End If

  ' Validate
  If Success Then
    If Not Client.IsOrganisation Then
      Success = False
      finBL.Error.ErrorBegin("This is not an organisation type Client.")
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Client Summary.
''' &lt;/summary&gt;
Private Function GetClientSummary(parametersJson As String,
                                  ByRef returnValue As String) As Boolean

  Dim Client As finClient
  Dim Html As String
  Dim Product As String
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    Product = .GetString("Product")
  End With

  ' Get Client object
  If Success Then
    Success = GetClientOrApplicant(Client, Nothing, Nothing)
  End If

  ' Get Summary
  If Success Then
    ' Initialise
    sb = finBL.CreateHtmlSummaryPage2StringBuilder()
    SummaryTable = finBL.CreateSummaryTable()

    ' Create Summary
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information

      .Columns.AddText(10).NoBreakChars = 20
      .Columns.AddText()

      With .Rows
        ' Details
        .AddSectionHeading2("Organisation details")
        .AddCaptionText("Name:", Client.Name)
        .AddCaptionText("Company No.:", Client.OrganisationNumber)
        .AddCaptionText("NZBN:", Client.BusinessNumber)
      End With

      ' Warning
      If UCase(Product) = "NZBN ENTITY DETAILS" Then
        .TextBefore = "{{Alert|This product is now obsolete. Consider using the 'NZBN Entity Details v4' product instead.}}"
      End If
    End With

    ' Finalise
    With sb
      .Initialise(iseSummaryPageTarget.WebInternal)
      .HtmlHeaderBegin("", isefinSummaryPageStyle.Blocks)
      .HtmlHeaderEnd()

      .SectionColumnsBegin()
      .ColumnBegin("100%")
      .BlockBegin("Client Summary",,,False)
      .SummaryTableAppend(SummaryTable)
      .BlockEnd()
      .ColumnEnd()
      .SectionColumnsEnd()

      .HtmlFinalise()

      Html = .ToString(True)
    End With
  End If

  ' Finalise
  If Success Then
    returnValue = Html
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Perform a Company Selection.
''' &lt;/summary&gt;
Private Function PerformCompanySelection(branchId As String,
                                         product As String,
                                         entityTypes As String,
                                         fspNumber As String,
                                         ByRef data As Object) As Boolean

  Dim Client As finClient
  Dim CompanySelectionRequest As ISCreditEnquiryRequest
  Dim CompanySelectionResponse_NZBNEntitySearchV4 As ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchV4
  Dim CompanySelectionResponse_NZCOFinancialServiceProviderSearch As ISCreditEnquiryResponse_NZGovernment_NZCOFinancialServiceProviderSearch
  Dim CompanySelectionResult_NZBNEntitySearchByNameResult As ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchByNameResult
  Dim CompanySelectionResult_NZCOFinancialServiceProviderSearchResult As ISCreditEnquiryResponse_NZGovernment_NZCOFinancialServiceProviderSearchResult
  Dim CreditEnquiryResponse As ISCreditEnquiryResponse
  Dim List As List(Of CompanySelectionItem)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  List = New List(Of CompanySelectionItem)

  ' Get Client (do not need Application objects)
  If Success Then
    Success = GetClientOrApplicant(Client, Nothing, Nothing)
  End If

  ' Create Request
  If Success Then
    ' Validate Branch
    If Not finBL.Branches.Exists(branchId) Then branchId = Client.BranchId

    ' Create
    CompanySelectionRequest = finBL.CreditBureau.CreateCreditEnquiryRequest(SERVICE_ID, iseProductClass.CompanySelection, product, branchId)

    ' Update
    With CompanySelectionRequest
      .CompanyName = Client.Name
      .CompanyNumber = Client.OrganisationNumber
      .BusinessNumber = Client.BusinessNumber
    End With

    ' Product Specific Company Search Options
    Select Case CompanySelectionRequest.GetType()
      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZBNEntitySearchV4)
        ' Entity Search
        With DirectCast(CompanySelectionRequest, ISCreditEnquiryRequest_NZGovernment_NZBNEntitySearchV4)
          .EntityTypeDescriptions = entityTypes
        End With

      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZCOFinancialServiceProviderSearch)
        ' NZCO Financial Service Providers Search
        With DirectCast(CompanySelectionRequest, ISCreditEnquiryRequest_NZGovernment_NZCOFinancialServiceProviderSearch)
          .ProviderName = Client.Name
          .ProviderNumber = fspNumber
        End With
    End Select
  End If

  ' Execute
  If Success Then
    Success = finBL.CreditBureau.ExecuteCompanySelection(CompanySelectionRequest, CreditEnquiryResponse)
  End If

  ' Handle Responses
  If Success Then
    Select Case CompanySelectionRequest.GetType()
      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZBNEntitySearchV4)
        CompanySelectionResponse_NZBNEntitySearchV4 = DirectCast(CreditEnquiryResponse, ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchV4)

        ' Add Items
        For Each CompanySelectionResult_NZBNEntitySearchByNameResult In CompanySelectionResponse_NZBNEntitySearchV4.SearchResults
          List.Add(New CompanySelectionItem(CompanySelectionResult_NZBNEntitySearchByNameResult))
        Next

      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZCOFinancialServiceProviderSearch)
        CompanySelectionResponse_NZCOFinancialServiceProviderSearch = DirectCast(CreditEnquiryResponse, ISCreditEnquiryResponse_NZGovernment_NZCOFinancialServiceProviderSearch)

        ' Add Items
        For Each CompanySelectionResult_NZCOFinancialServiceProviderSearchResult In CompanySelectionResponse_NZCOFinancialServiceProviderSearch.SearchResults
          List.Add(New CompanySelectionItem(CompanySelectionResult_NZCOFinancialServiceProviderSearchResult))
        Next
    End Select

    ' Sort
    List.Sort(AddressOf CompanySelectionSorter)

    ' Finalise
    data = List
  End If

  Return Success

End Function

Private Function CompanySelectionSorter(x As CompanySelectionItem, y As CompanySelectionItem) As Integer

  Return StrComp(x.Status, y.Status)

End Function

''' &lt;summary&gt;
'''  Perform Enquiry.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function PerformEnquiry(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim AccountAppLogPk As Integer
  Dim ClientLogPk As Integer
  Dim CreditEnquiryRequest As ISCreditEnquiryRequest
  Dim CreditEnquiryResponse As ISCreditEnquiryResponse
  Dim ExecutePostFailed As Boolean
  Dim Html As String
  Dim obj As Object
  Dim ServiceLogCreateDetails As ISServiceLogCreateDetails
  Dim ServiceLogPk As Integer
  Dim strTemp As String
  Dim Success As Boolean
  Dim Warnings As ISValidationItems
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True
  
  ' Initialise
  Warnings = finBL.Runtime.CreateValidationItems()

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

  ' Create Enquiry
  If Success Then
    Success = CreateCreditEnquiryRequestForClient(WizardFinishParameters.BranchId, WizardFinishParameters.Product, CreditEnquiryRequest)
  End If

  ' Options
  If Success Then
    Select Case CreditEnquiryRequest.GetType()
      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZBNEntityDetails)
        ' Entity Details V4
        Dim Request As ISCreditEnquiryRequest_NZGovernment_NZBNEntityDetails

        Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_NZGovernment_NZBNEntityDetails)
        With Request
          .BusinessNumber = WizardFinishParameters.NZBN
          .CompanyName = WizardFinishParameters.CompanyName
          .CompanyNumber = WizardFinishParameters.CompanyNumber
        End With

      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZBNEntityDetailsV4)
        ' Entity Details V4
        Dim Request As ISCreditEnquiryRequest_NZGovernment_NZBNEntityDetailsV4

        Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_NZGovernment_NZBNEntityDetailsV4)
        With Request
          .BusinessNumber = WizardFinishParameters.NZBN
          .CompanyName = WizardFinishParameters.CompanyName
          .CompanyNumber = WizardFinishParameters.CompanyNumber
        End With

      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZCOEntityRoleSearch)
        ' NZCO Entity Role Search
        Dim Request As ISCreditEnquiryRequest_NZGovernment_NZCOEntityRoleSearch

        Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_NZGovernment_NZCOEntityRoleSearch)
        With Request
          .SearchForDirectors = WizardFinishParameters.IncludeDirectors
          .SearchForShareholders = WizardFinishParameters.IncludeShareholders
          .RegisteredOnly = WizardFinishParameters.OnlyIncludeIfActiveRole
        End With

      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZCOFinancialServiceProviderDetails)
        ' NZCO Financial Service Providers Details
        Dim Request As ISCreditEnquiryRequest_NZGovernment_NZCOFinancialServiceProviderDetails

        Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_NZGovernment_NZCOFinancialServiceProviderDetails)
        With Request
          .ProviderNumber = WizardFinishParameters.FSPId
        End With

      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Unhandled request type '{0}'.", typename(CreditEnquiryRequest))
    End Select
  End If

  ' Execute
  If Success Then
    If finBL.CreditBureau.ExecuteCreditEnquiry(CreditEnquiryRequest, CreditEnquiryResponse, ServiceLogCreateDetails, True, mWorkflowPk, mWorkflowItemPk, ExecutePostFailed, ClientLogPk, AccountAppLogPk) Then
      ServiceLogPk = ServiceLogCreateDetails.ServiceLogPk
      If ExecutePostFailed Then Warnings.Add(finBL.Error.Message())
    Else
      Success = False
    End If
  End If

  ' Get Report
  If Success Then
    Html = GetServiceReportInternal(ServiceLogPk)
  End If

  ' Complete Workflow Item
  If Success Then
    strTemp = ""
    finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, strTemp)
    
    If Len(strTemp) &lt;&gt; 0 Then
      Warnings.Add("The Enquiry was completed successfully, however the Workflow Item could not be actioned due to the following error:" &amp; vbNewLine &amp; vbNewLine &amp; strTemp)
    End If    
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(AccountAppLogPk, ClientLogPk, Html, ServiceLogPk, Warnings.GetSummaryNumbered(False, False, True, , True, True)), returnValue)
  End If

  Return Success

End Function

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

  Dim BranchId As String
  Dim Client As finClient
  Dim Chargeable As Boolean
  Dim CostCentreResolved_NZGovernment As finCostCentreResolved_NZGovernment
  Dim CreditEnquiryRequest As ISCreditEnquiryRequest
  Dim CompanySelectionRequest As ISCreditEnquiryRequest
  Dim Data As Object
  Dim Product As String
  Dim Success As Boolean
  Dim EntityTypes As String

  ' Assume Success
  Success = True

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

  ' Get Cost Centre Defaults for NZ Government
  CostCentreResolved_NZGovernment = finBL.CostCentresResolved.ItemByBranchId(BranchId).NZGovernment

  ' Get Client
  Success = GetClientOrApplicant(Client, Nothing, Nothing)

  ' Create Request for this Product
  If Success Then
    CreditEnquiryRequest = finBL.CreditBureau.CreateCreditEnquiryRequest(SERVICE_ID, iseProductClass.CreditEnquiry, Product, BranchId)
    CompanySelectionRequest = finBL.CreditBureau.CreateCreditEnquiryRequest(SERVICE_ID, iseProductClass.CompanySelection, Product, BranchId)

    If CreditEnquiryRequest Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("Cannot create Credit Enquiry Request.")
    Else
      If finBL.CreditBureau.UpdateCreditEnquiryRequestOptions(CreditEnquiryRequest, Client) Then
        Success = finBL.CreditBureau.UpdateCreditEnquiryRequestFromClient(CreditEnquiryRequest, Client)
      Else
        Success = False
      End If
    End If
  End If

  If Success Then
    ' Ensure Branch is what has been specified, not default from the Client
    If finBL.Branches.Exists(BranchId) Then
      CreditEnquiryRequest.BranchPk = finBL.Branches(BranchId).Pk
    Else
      CreditEnquiryRequest.BranchPk = 0
    End If

    ' Get Options page information
    Select Case CompanySelectionRequest.GetType()
      Case GetType(ISCreditEnquiryRequest_NZGovernment_NZBNEntitySearchV4)
        ' NZBN Entity Details
        Dim Request As ISCreditEnquiryRequest_NZGovernment_NZBNEntitySearchV4

        Request = DirectCast(CompanySelectionRequest, ISCreditEnquiryRequest_NZGovernment_NZBNEntitySearchV4)
        With Request
          Chargeable = .Chargeable
          EntityTypes = .EntityTypes.GetDescriptionsList().ToCsvString()
        End With

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

  ' Build Object
  If Success Then
    Data = New With {
      .Chargeable = Chargeable,
      .EntityTypes = EntityTypes
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Service Report.
''' &lt;/summary&gt;
Private Function GetServiceReport(parametersJson As String,
                                  ByRef returnValue As String) As Boolean

  Dim Html As String
  Dim ServiceLogPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Report
  Html = GetServiceReportInternal(ServiceLogPk)

  ' Finalise
  If Success Then
    returnValue = Html
  End If

  Return Success

End Function

Private Function GetServiceReportInternal(serviceLogPk As Integer) As String

  Dim Html As String
  Dim ServiceLog As ISServiceLog

  ' Get HTML
  If finBL.Database.GetServiceLog(serviceLogPk, ServiceLog) Then
    If Not finBL.CreditBureau.GetCreditEnquiryHtmlFromServiceLog(ServiceLog, Html, ScriptInfo.Target) Then
      Html = finBL.GetHtmlErrorMessage(finBL.Error.Message, finBL.Error.Details)
    End If
  Else
    Html = finBL.GetHtmlErrorMessage(finBL.Error.Message, finBL.Error.Details)
  End If

  Return Html

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 BranchId As String
  Dim ConfirmList As New List(Of String)
  Dim Data As Object
  Dim EntityTypes As String
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim FSPNumber As String
  Dim PageId As String
  Dim Product As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate Page
  Select Case PageId
    Case "Options"
      ' Get Parameters
      With mCombinedParameters
        BranchId = .GetString("BranchId")
        EntityTypes = .GetString("EntityTypes")
        FSPNumber = .GetString("FSPNumber")
        Product = .GetString("Product")
      End With
      
      ' Is Service Available
      If finBL.CreditBureau.IsServiceAvailable(iseProductClass.CreditEnquiry, SERVICE_ID, BranchId) Then
        ' Get Companies List (except for "NZCO Entity Role Search" Product)
        If StrComp(Product, "NZCO ENTITY ROLE SEARCH", CompareMethod.Text) &lt;&gt; 0 Then
          Success = PerformCompanySelection(BranchId, Product, EntityTypes, FSPNumber, Data)
        End If        
      Else
        FailedControlId = "cboBranch"
        FailedMessage = String.Format("This Service is not available or configured for Branch '{0}'.", BranchId)
      End If
  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;
'''  Branch Information.
''' &lt;/summary&gt;
Public Class BranchInfo

  Public BranchId As String
  Public CostCentreText As String

  Public Sub New(branchRO As finBranchRO,
                 serviceId As String)

    Dim CostCentrePk As Integer

    Me.BranchId = branchRO.BranchId

    If finBLShared.Settings.AddOns.CostCentre Then
      If finBLShared.CostCentreFunctions.GetCostCentreFromBranchAndService(branchRO.Pk, serviceId, CostCentrePk) Then
        If finBLShared.CostCentres.ExistsPk(CostCentrePk) Then
          With finBLShared.CostCentres.ItemByPk(CostCentrePk)
            Me.CostCentreText = String.Format("This will be charged to Cost Centre &lt;b&gt;{0}&lt;/b&gt;, '{1}'.", .CostCentreId, finBLShared.HtmlEncode(.Description))
          End With
        End If
      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 AccountAppApplicantName As String

  Public BranchId As String

  Public ClientId As String
  Public ClientName As String
  Public IsOrganisation As Boolean

  Public WorkflowPk As Integer

  ' Client Summary
  Public ClientSummary As String

  ' Lists
  Public Branches As New List(Of BranchInfo)
  Public ProductsList As String

  ' Defaults
  Public DefaultProduct As String

  ' Configuration
  Public AllowBranch As Boolean
  Public ShowBranch As Boolean
  Public ChargeableDefault As Boolean
  Public ServiceName As String
  Public TestMode As Boolean

End Class



''' &lt;summary&gt;
'''  Company Selection Item.
''' &lt;/summary&gt;
Public Class CompanySelectionItem

  Public CompanyName As String
  Public CompanyNumber As String
  Public CompanyType As String
  Public FSPId As String
  Public NZBN As String
  Public RegisteredDate As Date
  Public SourceReference As String
  Public Status As String
  Public StatusDate As Date
  Public TradingNames As String

  Public Sub New(companySelectionResult As ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchByNameResult)

    With companySelectionResult
      Me.CompanyName = .EntityName
      Me.CompanyNumber = .CompanyNumber
      Me.CompanyType = .EntityTypeDescription
      Me.FSPId = ""
      Me.NZBN = .NewZealandBusinessNumber
      Me.RegisteredDate = .RegistrationDate
      Me.SourceReference = ""
      Me.Status = .EntityStatusDescription
      Me.StatusDate = Nothing
      Me.TradingNames = ""
    End With

  End Sub

  Public Sub New(companySelectionResult As ISCreditEnquiryResponse_NZGovernment_NZCOFinancialServiceProviderSearchResult)

    With companySelectionResult
      Me.CompanyName = .FspName
      Me.CompanyNumber = ""
      Me.CompanyType = ""
      Me.FSPId = .FspId
      Me.NZBN = ""
      Me.RegisteredDate = Nothing
      Me.SourceReference = .SourceRegisterReferenceId
      Me.Status = .FspStatus
      Me.StatusDate = .StatusDate
      Me.TradingNames = .GetTradingsNamesList(vbNewLine)
    End With

  End Sub

End Class



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

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

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

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

  End Sub

End Class



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

  ' General
  Public BranchId As String
  Public CompanyName As String
  Public CompanyNumber As String
  Public FSPId As String
  Public NZBN As String
  Public Product As String

  ' Options
  Public IncludeDirectors As Boolean
  Public IncludeShareholders As Boolean
  Public OnlyIncludeIfActiveRole As Boolean

End Class



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

  ' General
  Public AccountAppLogPk As Integer
  Public ClientLogPk As Integer
  Public Html As String
  Public ServiceLogPk As Integer
  Public Warning As String

  Public Sub New(accountAppLogPk As Integer,
                 clientLogPk As Integer,
                 html As String,
                 serviceLogPk As Integer,
                 warning As String)

    Me.AccountAppLogPk = accountAppLogPk
    Me.ClientLogPk = clientLogPk
    Me.Html = html
    Me.ServiceLogPk = serviceLogPk
    Me.Warning = warning

  End Sub

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

Used as a finPOWER Connect Cloud compatible wizard to allow a "New Zealand Government (NZBN)" Organisation enquiry to be performed.

The following products are supported:
* NZBN Entity Details v4
* NZCO Entity Role Search</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Confirm who this enquiry is being made upon."&gt;Organisation Credit Enquiry&lt;/li&gt;
        &lt;li tabId="Options" tooltipText=""&gt;Options&lt;/li&gt;
        &lt;li tabId="CompanySelection" tooltipText="Select the Company to enquire upon."&gt;Company Selection&lt;/li&gt;
        &lt;li tabId="Enquiry" tooltipText="Enquiry results."&gt;Enquiry Report&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"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:6em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblRecord"&gt;Client&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRecord"&gt;Client:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRecord" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="display:none"&gt;
          &lt;th&gt;&lt;label for="cboApplicant"&gt;Applicant:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboApplicant" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblBranch"&gt;Select the Branch to allocate costs to&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBranch"&gt;Branch:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBranch" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;div id="divCostCentreInformation" class="is-info-text info small" style="display:none"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblProduct"&gt;Select the Credit Bureau Product&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboProduct"&gt;Product:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboProduct" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr style="height:100%"&gt;
          &lt;td colspan="2" style="height:100%"&gt;&lt;div id="wbClientSummary" class="is-dock-fill"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Options --&gt;
    &lt;div id="pageOptions"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblEnquiryOptions" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="chklstEntityTypes"&gt;Entity Types:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="chklstEntityTypes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;input id="chkIncludeDirectors" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;input id="chkIncludeShareholders" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;input id="chkOnlyIncludeIfActiveRole" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFSPNumber"&gt;FSP No:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFSPNumber" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Company Selection --&gt;
    &lt;div id="pageCompanySelection"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="gridCompanySelection" style="height:100%"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
   &lt;/div&gt;


    &lt;!-- Enquiry --&gt;
    &lt;div id="pageEnquiry"&gt;
      &lt;div id="wbSummary" 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_BranchDefaults;
var mRecord_CompanySelection;
var mRecord_Options;
var mEnquiryDetails;

// Controls
var C = {
  // General
  lblRecord: null,
  cboRecord: null,
  cboApplicant: null,

  lblBranch: null,
  cboBranch: null,
  divCostCentreInformation: null,

  lblProduct: null,
  cboProduct: null,

  wbClientSummary: null,

  // Options
  lblEnquiryOptions: null,

  chklstEntityTypes: null,

  chkIncludeDirectors: null,
  chkIncludeShareholders: null,
  chkOnlyIncludeIfActiveRole: null,

  txtFSPNumber: null,

  // Company Selection
  gridCompanySelection: null,

  // Enquiry
  wbSummary: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mLastProduct = "";
var mLastFinishParametersJson = "";

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

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

  C.lblBranch = widget.UI.Label("lblBranch", {});
  C.cboBranch = widget.UI.DBCombo("cboBranch", {
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboBranch_Change,
  });
  C.divCostCentreInformation = $("#divCostCentreInformation");

  C.lblProduct = widget.UI.Label("lblProduct", {});
  C.cboProduct = widget.UI.ComboBox("cboProduct", {
    allowBlank: false,
    limitToList: true,
    maxLength: 50,
    onChange: cboProduct_Change
  });

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

  // Options
  C.lblEnquiryOptions = widget.UI.Label("lblEnquiryOptions", {});
  C.chklstEntityTypes = widget.UI.CheckList("chklstEntityTypes", {});

  C.chkIncludeDirectors = widget.UI.CheckBox("chkIncludeDirectors", {
    caption: "Include Directors in search?",
    captionWrap: true
  });
  C.chkIncludeShareholders = widget.UI.CheckBox("chkIncludeShareholders", {
    caption: "Include Shareholders in search?",
    captionWrap: true
  });
  C.chkOnlyIncludeIfActiveRole = widget.UI.CheckBox("chkOnlyIncludeIfActiveRole", {
    caption: "Only include if the Director or Shareholder has an active role in one registered company?",
    captionWrap: true
  });
  C.txtFSPNumber = widget.UI.TextBox("txtFSPNumber", {
    width: widget.UI.FIELD_WIDTH_CODE_20
  });

  // Company Selection
  C.gridCompanySelection = widget.UI.Grid("gridCompanySelection", {
    groupByColumns: "Status",
    rowNumbering: true,
    stickyHeader: true,

    onInitialiseRow: gridCompanySelection_InitialiseRow,
    onRowDrilldown: gridCompanySelection_RowDrilldown,
  });

  //   Enquiry
  C.wbSummary = widget.UI.PreviewPane("wbSummary", {
    showPrint: true,
  });

  // Grids

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

  // Handle Notifications
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  C.chkIncludeDirectors.Value(true);
  C.chkIncludeShareholders.Value(true);

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

  // Hide content
  frmMain.Visible(false);

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

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

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

      // Load Fields
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    if (mRecord.AccountAppId) {
      // Applicant
      C.lblRecord.Text("Account Application");
      C.cboRecord.Caption("Application:");
      C.cboRecord.RefreshUnbound(mRecord.AccountAppId, mRecord.AccountAppName);
      C.cboApplicant.RefreshUnbound(mRecord.AccountAppApplicantPk, mRecord.AccountAppApplicantName);
    }
    else {
      // Client
      C.lblRecord.Text("Client");
      C.cboRecord.Caption("Client:");
      C.cboRecord.RefreshUnbound(mRecord.ClientId, mRecord.ClientName);
    }
    C.cboBranch.Text(mRecord.BranchId);
    C.cboProduct.Text(mRecord.DefaultProduct);

    C.wbClientSummary.SetContent(mRecord.ClientSummary, false);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord &amp;&amp; mRecord.TestMode) {
    widget.SetHeading(mRecord.ServiceName + " Organisation Enquiry (Test Mode)");
  }

  // Information Lists

  // Lists
  if (mRecord) {
    C.cboProduct.ListFromCsvString(mRecord.ProductsList);
    if (mRecord.ShowBranch) {
      C.cboBranch.RefreshFromStandardRange("Branches");
    }
  }

  // Controls
  if (mRecord) {
    C.cboApplicant.VisibleRow(mRecord.AccountAppApplicantPk != 0);

    C.lblBranch.ReadOnly(mRecord.AllowBranch);
    C.cboBranch.ReadOnly(mRecord.AllowBranch);
    C.lblBranch.VisibleRow(mRecord.ShowBranch);
    C.cboBranch.VisibleRow(mRecord.ShowBranch);

    cboBranch_Change();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  widget.Close();
}

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

  // Finish Button
  if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.cboRecord.WidthResizeFromParent();
      C.cboProduct.WidthResizeFromParent();
      break;

    case "Request":
      C.txtToken.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 "CompanySelection":
          switch(C.cboProduct.Text().toUpperCase()) {
            case "NZCO ENTITY ROLE SEARCH":
              found = false;
              break;

            default:
              found = true;
              break;
          }
          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 "Options":
        pageOptions_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "General":
      frmMain.RefreshHeading(mRecord.ServiceName + " Organisation Enquiry", tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;

    case "Options":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Specify '" + C.cboProduct.Text() + "' options.");
      break;

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

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

  // Resize Wizard
  tabWizard_Resize();

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

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "Options":
        // Allow server-side validation
        break;

      case "CompanySelection":
        if (tabWizard.SelectedTabId() == "CompanySelection") {
          // Check company selected
          if (C.gridCompanySelection.ActiveDataRowIndex() == -1) {
            if (mRecord_CompanySelection.length == 0) {
              widget.UI.MsgBoxAlert("No matches were found to enquire upon.");
            }
            else {
              widget.UI.MsgBoxAlert("Please select a company to enquire upon.", {}, function () { C.gridCompanySelection.Focus(); });
            }
            return;
          }
        }
        else {
          // Options page so no checks required
        }

        // If parameters have changed so allow performing another Credit Enquiry
        if (mEnquiryDetails &amp;&amp; mLastFinishParametersJson != JSON.stringify(CreateFinishParameters())) {
          mEnquiryDetails = null;
        }

        // Perform Enquiry
        PerformEnquiry_Pre(validCallback);
        return;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "Options":
        params = {
          branchId: C.cboBranch.Text(),
          entityTypes: C.chklstEntityTypes.Text(),
          fspNumber: C.txtFSPNumber.Text(),
          product: C.cboProduct.Text()
        };
        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 "Options":
        switch (C.cboProduct.Text().toUpperCase()) {
          case "NZCO ENTITY ROLE SEARCH":
            // Perform Enquiry
            PerformEnquiry_Pre(validCallback);
            return;
            
          default:
            mRecord_CompanySelection = o.Data;

            // Refresh Grid
            C.gridCompanySelection.VirtualDataRefresh(mRecord_CompanySelection);
            break;
        }        
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ===========
// pageOptions
// ===========
function pageOptions_Refresh() {
  // Disable form to prevent controls 'flickering' as they update
  frmMain.Visible(false);

  // Labels
  C.lblEnquiryOptions.Text("Enquiry Options");

  // Hide all Controls
  C.lblEnquiryOptions.VisibleRow(false);

  C.chklstEntityTypes.VisibleRow(false);

  C.chkIncludeDirectors.VisibleRow(false);
  C.chkIncludeShareholders.VisibleRow(false);
  C.chkOnlyIncludeIfActiveRole.VisibleRow(false);

  C.txtFSPNumber.VisibleRow(false);

  // Show relevant options
  switch(C.cboProduct.Text().toUpperCase()) {
    case "NZBN ENTITY DETAILS":
    case "NZBN ENTITY DETAILS V4":
      pageOptions_Refresh_NZBNEntityDetails();
      break;

    case "NZCO ENTITY ROLE SEARCH":
      pageOptions_Refresh_NZCOEntityRoleSearch();
      break;

    case "NZCO FINANCIAL SERVICE PROVIDERS DETAILS":
      pageOptions_Refresh_NZCOFinancialServiceProviders();
      break;

    default:
      window.alert(C.cboProduct.Text() + " not handled!");
      break;
  }
}

function pageOptions_Refresh_GetData() {
  var params = {
    branchId: C.cboBranch.Text(),
    product: C.cboProduct.Text()
  }

  widget.GetString("GetOptions", params, pageOptions_Refresh_GetData_Done, function(errorMessage) {
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function pageOptions_Refresh_GetData_Done(data) {
  mRecord_Options = JSON.parse(data);

  // Lists
  C.chklstEntityTypes.ListFromCsvString(mRecord_Options.EntityTypes);

  // Control Visibility

  // Set Fields

  // Change Events

  // Show content
  frmMain.Visible(true);

  // Focus
  tabWizard.FocusFirst();
}

function pageOptions_Refresh_NZBNEntityDetails() {
  // Show Controls
  C.lblEnquiryOptions.VisibleRow(true);
  C.chklstEntityTypes.VisibleRow(true);

  // Setup Grid
  gridCompanySelection_Refresh();

  // Refresh Data
  pageOptions_Refresh_GetData();
}

function pageOptions_Refresh_NZCOEntityRoleSearch() {
  // Show Controls
  C.lblEnquiryOptions.VisibleRow(true);
  C.chkIncludeDirectors.VisibleRow(true);
  C.chkIncludeShareholders.VisibleRow(true);
  C.chkOnlyIncludeIfActiveRole.VisibleRow(true);

  // Show content
  frmMain.Visible(true);

  // Focus
  tabWizard.FocusFirst();
}

function pageOptions_Refresh_NZCOFinancialServiceProviders() {
  // Labels
  C.lblEnquiryOptions.Text("Enter Company search criteria");

  // Show Controls
  C.lblEnquiryOptions.VisibleRow(true);
  C.txtFSPNumber.VisibleRow(true);

  // Setup Grid
  gridCompanySelection_Refresh();

  // Show content
  frmMain.Visible(true);

  // Focus
  tabWizard.FocusFirst();
}

// ===============
// Perform Enquiry
// ===============
function PerformEnquiry(successCallback) {
  // Block UI
  widget.UI.Block("Performing Enquiry, please wait...");

  // Save parameters
  mLastFinishParametersJson = JSON.stringify(CreateFinishParameters());

  // Perform Enquiry
  widget.GetString("PerformEnquiry", CreateFinishParameters(), function (data) { PerformEnquiry_Success(data, successCallback); }, PerformEnquiry_Fail);
}

function PerformEnquiry_Success(data, successCallback) {
  // Parse
  mEnquiryDetails = JSON.parse(data);

  // Show Enquiry Details
  C.wbSummary.SetContent(mEnquiryDetails.Html, false);

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

  // Callback
  successCallback();

  // Show warning
  if (mEnquiryDetails.Warning) widget.UI.MsgBoxAlert(mEnquiryDetails.Warning);

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

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

  widget.UI.MsgBoxAlert(error);
}

function PerformEnquiry_Pre(validCallback) {
  // Confirm
  if (mEnquiryDetails) {
    validCallback();
  }
  else {
    var Chargeable = true;
    if(mRecord) Chargeable = mRecord.ChargeableDefault;
    if(mRecord_Options) Chargeable = mRecord_Options.Chargeable;

    if(Chargeable) {
      var message = "Are you sure you want to perform a " + mRecord.ServiceName + " Enquiry?\n\n";
      if (mRecord.WorkflowPk) {
        message += "NOTE: The Workflow Item that this Credit Enquiry is being peformed for will be completed.\n\n";
      }
      if (mRecord.TestMode) {
        message += "NOTE: You are in 'Test Mode' so no cost will be incurred.";
      }
      else {
        message += "This function incurs a cost.\n\nFor more information please refer to the Terms and Conditions of your Agreement with this Service provider.";
      }
      widget.UI.MsgBoxConfirm(message, { heading: "Perform Credit Enquiry" }, function() { PerformEnquiry(validCallback) });
    }
    else {
      PerformEnquiry(validCallback);
    }
  }
}

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

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  widget.Close();
}

// =========
// cboBranch
// =========
function cboBranch_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  var params = {
    branchId: C.cboBranch.Text()
  }

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

      if(mRecord_BranchDefaults) {
        C.cboProduct.Text(mRecord_BranchDefaults.DefaultProduct);
      }
    },

    // Failure
    function(errorMessage) {
      widget.UI.Unblock();
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );

  // Cost Centre
  // Hide by default
  C.divCostCentreInformation.hide();

  // Get Cost Centre message
  if (mRecord.ShowBranch &amp;&amp; C.cboBranch.Text()) {
    var branch = mRecord.Branches.GetItem(C.cboBranch.Text());

    if (branch) {
      var message = branch.CostCentreText;
    }
  }

  // Show / Hide message
  if (message) {
    C.divCostCentreInformation.html(message);
    C.divCostCentreInformation.show();
  }
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    branchId: C.cboBranch.Text(),
    product: C.cboProduct.Text(),
  };

  switch (C.cboProduct.Text().toUpperCase()) {
    case "NZCO ENTITY ROLE SEARCH":
      params.includeDirectors = C.chkIncludeDirectors.Value();
      params.includeShareholders = C.chkIncludeShareholders.Value();
      params.onlyIncludeIfActiveRole = C.chkOnlyIncludeIfActiveRole.Value();
      break;

    default:
      var item = mRecord_CompanySelection[C.gridCompanySelection.ActiveDataRowListIndex()];
      params.companyName = item.CompanyName;
      params.companyNumber = item.CompanyNumber;
      params.NZBN = item.NZBN;
      params.fspId = item.FSPId;
      break;
  }

  return params;
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId) {
//    case "BankAccountEnquiry.Refresh":
//      // Refresh report
//      wbSummary_Refresh();
//      break;
  }
}

// ====================
// gridCompanySelection
// ====================
function gridCompanySelection_InitialiseRow(e) {
  var item = mRecord_CompanySelection[e.row.listIndex];

  // Update cells
  e.row.cells.Status.value = item.Status;
  e.row.cells.CompanyName.value = item.CompanyName;
  e.row.cells.CompanyNumber.value = item.CompanyNumber;
  e.row.cells.NZBN.value = item.NZBN;
  e.row.cells.FSPId.value = item.FSPId;
  e.row.cells.SourceReference.value = item.SourceReference;
  e.row.cells.RegisteredDate.value = item.RegisteredDate;
  e.row.cells.StatusDate.value = item.StatusDate;
  e.row.cells.CompanyType.value = item.CompanyType;
  e.row.cells.TradingNames.value = item.TradingNames;
}

function gridCompanySelection_Refresh() {
  // Product Conditions
  var isEntityDetails = (C.cboProduct.Text().toUpperCase() == "NZBN ENTITY DETAILS" || C.cboProduct.Text().toUpperCase() == "NZBN ENTITY DETAILS V4");
  var isNZCO = (C.cboProduct.Text().toUpperCase() == "NZCO FINANCIAL SERVICE PROVIDERS DETAILS");

  // Add Columns
  C.gridCompanySelection.ClearColumns();
  C.gridCompanySelection.AddColumnCode("Status", { caption: "Status", visible: false });
  C.gridCompanySelection.AddColumnString("CompanyName", { caption: "Name"});
  C.gridCompanySelection.AddColumnString("CompanyNumber", { caption: "Number", visible: isEntityDetails });
  C.gridCompanySelection.AddColumnString("NZBN", { caption: "NZBN", visible: isEntityDetails });
  C.gridCompanySelection.AddColumnString("FSPId", { caption: "Id", visible: isNZCO });
  C.gridCompanySelection.AddColumnString("SourceReference", { caption: "Source Ref.", visible: isNZCO });
  C.gridCompanySelection.AddColumnDate("RegisteredDate", { caption: "Registered", visible: isEntityDetails });
  C.gridCompanySelection.AddColumnDate("StatusDate", { caption: "Status", visible: isNZCO });
  C.gridCompanySelection.AddColumnString("CompanyType", { caption: "Type", visible: isEntityDetails });
  C.gridCompanySelection.AddColumnString("TradingNames", { caption: "Trading Names", visible: isNZCO });
}

function gridCompanySelection_RowDrilldown(e) {
  cmdNext.click();
}

// =========
// wbSummary
// =========
function wbSummary_Refresh() {
  widget.GetString("GetServiceReport", { serviceLogPk: mEnquiryDetails.ServiceLogPk },
    function (data) {
      C.wbSummary.SetContent(data, false);
    },

    function (error) {
      widget.UI.MsgBoxAlert(error);
    }
  );
}

// ==========
// cboProduct
// ==========
function cboProduct_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Get Client Summary
  widget.GetString("GetClientSummary", { branchId: C.cboBranch.Text(), product: C.cboProduct.Text() },
    function(data) {
      C.wbClientSummary.SetContent(data, false);
    },
    function(errorMessage) {
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>l3Gwe+O8hUuzbDINEwskyg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>800</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>Logo_NZGovernment</Icon>
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>If you do not specify a Default Transaction Type, the Transaction Type selection will be shown regardless of the settings specified below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" 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="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="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>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="BranchId" 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.Branches</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </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>