<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-17T23:34:36.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-09-12T00:11:01.9310000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-17T23:32:49.5390000</UpdatedUtcDate>
    <ScriptId>HWCOCE</ScriptId>
    <Description>Centrix (New Zealand) Organisation Credit Enquiry</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_CentrixNZ_Organisation
Option Explicit On
Option Strict On

' ####################################################################
' Centrix (New Zealand) Organisation Credit Enquiry wizard HTML Widget
'
' (c) Copyright Intersoft Systems Limited 2022
'
' Version: 1.17 (18/09/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.10  12/07/2022  ISS      J028905   Show readonly cost centre information
'    1.11  21/07/2022  ISS      J026867   Implement supported products
'    1.12  06/12/2022  ISS      J028905   Show readonly cost centre information
'    1.13  16/03/2023  ISS      J030537   Default product update
'    1.14  11/04/2024  ISS      J033284   Removed obsoleted commercial report products
'    1.15  16/05/2024  ISS      J033469   Add "Include Ownership Tree?" option for Commercial Beneficial Ownerships
'    1.16  27/05/2024  ISS      J033575   Added Print button
'    1.17  18/09/2024  ISS      J029950   Changed the Workflow Executor to the finBL.HtmlWidgetUtilities.WorkflowItemComplete function
' #################################################################

' Constants
Private Const FORM_KEY As String = "CentrixNZ_Organisation"
Private Const SERVICE_ID As String = "CentrixNZ"
Private Const SUPPORTED_PRODUCTS As String = "Commercial Report,Commercial Beneficial Owners"

' 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 "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)

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

    Case "GetProductOptions"
      ' Retrieve Options for selected Product
      Main = GetProductOptions(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;
'''  Creates a Credit Enquiry Request for a Client.
''' &lt;/summary&gt;
Private Function CreateCreditEnquiryRequestForClient(branchId As String,
                                                     product As String,
                                                     productClass As iseProductClass,
                                                     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, productClass, 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 Branch Defaults
''' &lt;/summary&gt;
Private Function GetBranchDefaults(ByRef returnValue As String) As Boolean

  Dim BranchId As String
  Dim CostCentreResolved_CentrixNZ As finCostCentreResolved_CentrixNZ
  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_CentrixNZ = finBL.CostCentresResolved.ItemByBranchId(BranchId).CentrixNZ

  ' Get Default Product
  DefaultProduct = CostCentreResolved_CentrixNZ.CreditEnquiryDefaultProductCompany
  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 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

      ' 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
      .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;
'''  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(creditEnquiryRequest As ISCreditEnquiryRequest,
                                  ByRef clientValid As Boolean) As String

  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim SummaryTable As ISSummaryTable

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

  ' Create Summary
  With SummaryTable
    .TableClass = iseSummaryTableClass.Information

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

    If Len(creditEnquiryRequest.ProductWarning) &lt;&gt; 0 Then
      .TextBefore = "{{warning|" &amp; creditEnquiryRequest.ProductWarning &amp; "}}"
    End If
    .TextBefore &amp;= "{{info|If any of these details are incorrect or out-of-date, close this form, update the Client record and try again.}}"

    With .Rows
      ' Person's details
      .AddSectionHeading2("Organisation details")
      .AddCaptionText("Name:", creditEnquiryRequest.CompanyName)
      .AddCaptionText("Company No.:", creditEnquiryRequest.CompanyNumber)
      .AddCaptionText("NZBN:", creditEnquiryRequest.BusinessNumber)
    End With
  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()
  End With

  Return sb.ToString(True)

End Function

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

  Dim Client As finClient
  Dim CommercialSearchByName As ISCreditEnquiryResponse_CentrixNZ_CommercialSearchByName
  Dim CompanySelectionResponse As ISCreditEnquiryResponse_CentrixNZ_CompanySelection
  Dim CompanySelectionResult As ISCreditEnquiryResponse_CentrixNZ_CompanySelectionResult
  Dim CreditEnquiryRequest As ISCreditEnquiryRequest
  Dim CreditEnquiryResponse As ISCreditEnquiryResponse
  Dim List As List(Of CompanySelectionItem)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' 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
    Success = CreateCreditEnquiryRequestForClient(branchId, product, iseProductClass.CompanySelection, CreditEnquiryRequest)
  End If

  ' Execute
  If Success Then
    If finBL.CreditBureau.ExecuteCompanySelection(CreditEnquiryRequest, CreditEnquiryResponse) Then
      ' Create Objects
      List = New List(Of CompanySelectionItem)

      Select Case CreditEnquiryResponse.GetType()
        Case GetType(ISCreditEnquiryResponse_CentrixNZ_CommercialSearchByName)
          ' -----------------
          ' Commercial Report
          ' -----------------
          ' Initialise
          CommercialSearchByName = DirectCast(CreditEnquiryResponse, ISCreditEnquiryResponse_CentrixNZ_CommercialSearchByName)

          ' Add Items
          For Each CompanySelectionResult In CommercialSearchByName.SearchResults
            List.Add(New CompanySelectionItem(CompanySelectionResult))
          Next

        Case GetType(ISCreditEnquiryResponse_CentrixNZ_CompanySelection)
          ' ------------------------
          ' Commercial Credit Report
          ' ------------------------
          ' Initialise
          CompanySelectionResponse = DirectCast(CreditEnquiryResponse, ISCreditEnquiryResponse_CentrixNZ_CompanySelection)

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

      ' Sort
      List.Sort(AddressOf CompanySelectionSorter)

      ' Finalise
      data = List
    Else
      Success = False
    End If
  End If

  Return Success

End Function

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

  Return StrComp(x.StatusCode, y.StatusCode)

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

  ' Assume Success
  Success = True

  ' Get Request
  If Success Then
    Success = CreateCreditEnquiryRequestForClient(WizardFinishParameters.BranchId, WizardFinishParameters.Product, iseProductClass.CreditEnquiry, CreditEnquiryRequest)
  End If

  ' Update Request
  If Success Then
    If CreditEnquiryRequest Is Nothing Then
      Success = False
      finBL.Error.ErrorBeginFormat("Unhandled Product '{0}'.", WizardFinishParameters.Product)
    Else
      ' Update
      Select Case CreditEnquiryRequest.GetType()
        Case GetType(ISCreditEnquiryRequest_CentrixNZ_CommercialReport)
          ' -----------------
          ' Commercial Report
          ' -----------------
          Dim Request As ISCreditEnquiryRequest_CentrixNZ_CommercialReport

          Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_CentrixNZ_CommercialReport)
          With Request
            .BusinessNumber = WizardFinishParameters.BusinessNumber
            .CompanyName = WizardFinishParameters.CompanyName
            .CompanyNumber = WizardFinishParameters.CompanyNumber

            ' Options
            .AccountTypeDescription = WizardFinishParameters.AccountType
            .EnquiryReasonDescription = WizardFinishParameters.EnquiryReason
            .AmountSought = WizardFinishParameters.Amount
          End With

        Case GetType(ISCreditEnquiryRequest_CentrixNZ_CommercialCreditReport)
          ' ------------------------
          ' Commercial Credit Report
          ' ------------------------
          Dim Request As ISCreditEnquiryRequest_CentrixNZ_CommercialCreditReport

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

        Case GetType(ISCreditEnquiryRequest_CentrixNZ_CommercialCreditReportPreviousReport)
          ' ----------------------------------------
          ' Commercial Credit Report Previous Report
          ' ----------------------------------------
          Dim Request As ISCreditEnquiryRequest_CentrixNZ_CommercialCreditReportPreviousReport

          Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_CentrixNZ_CommercialCreditReportPreviousReport)
          With Request
            .EnquiryNumber = WizardFinishParameters.EnquiryNumber
          End With

        Case GetType(ISCreditEnquiryRequest_CentrixNZ_CommercialBeneficialOwners)
          ' ----------------------------
          ' Commercial Beneficial Owners
          ' ----------------------------
          Dim Request As ISCreditEnquiryRequest_CentrixNZ_CommercialBeneficialOwners

          Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_CentrixNZ_CommercialBeneficialOwners)
          With Request
            .BusinessNumber = WizardFinishParameters.BusinessNumber
            .CompanyName = WizardFinishParameters.CompanyName
            .CompanyNumber = WizardFinishParameters.CompanyNumber
            
            ' Options
            .IncludeOwnershipTree = WizardFinishParameters.IncludeOwnershipTree
          End With

        Case Else
          Success = False
          finBL.Error.ErrorBeginFormat("Unhandled request type '{0}'.", typename(CreditEnquiryRequest))
      End Select
    End If
  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
    finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, strTemp)
    
    If Len(strTemp) &lt;&gt; 0 Then
      Warnings.Add("The Enquiry 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 AccountTypes As Object
  Dim BranchId As String
  Dim CreditEnquiryRequest As ISCreditEnquiryRequest
  Dim Data As Object
  Dim EnquiryReasons As String
  Dim Product As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Create Request for this Product
  Success = CreateCreditEnquiryRequestForClient(BranchId, Product, iseProductClass.CreditEnquiry, CreditEnquiryRequest)

  ' Get Options page information
  If Success Then
    Select Case CreditEnquiryRequest.GetType()
      Case GetType(ISCreditEnquiryRequest_CentrixNZ_CommercialReport)
        ' -----------------
        ' Commercial Report
        ' -----------------
        Dim Request As ISCreditEnquiryRequest_CentrixNZ_CommercialReport

        Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_CentrixNZ_CommercialReport)
        With Request
          ' Lists
          AccountTypes = .AccountTypes.GetDescriptionsList().ToCsvString()
          EnquiryReasons = .EnquiryReasons.GetDescriptionsList().ToCsvString()
        End With

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

  If Success Then
    Data = New With {
      .AccountTypes = AccountTypes,
      .EnquiryReasons = EnquiryReasons
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Product Options.
''' &lt;/summary&gt;
Private Function GetProductOptions(ByRef returnValue As String) As Boolean

  Dim BranchId As String
  Dim ClientValid As Boolean
  Dim ClientSummary As String
  Dim CreditEnquiryRequest As ISCreditEnquiryRequest
  Dim Data As Object
  Dim Product As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Request
  Success = CreateCreditEnquiryRequestForClient(BranchId, Product, iseProductClass.CreditEnquiry, CreditEnquiryRequest)

  ' Client Summary
  If Success Then
    ClientSummary = GetClientSummary(CreditEnquiryRequest, ClientValid)
  End If

  ' Options
  If Success Then
    Select Case CreditEnquiryRequest.GetType()
      Case Else
        Data = New With {
          .ClientSummary = ClientSummary
        }
    End Select
  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 FailedControlId As String
  Dim FailedMessage 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 "General"
      ' Get Parameters
      With mCombinedParameters
        BranchId = .GetString("BranchId")
        Product = .GetString("Product")
      End With

      If finBL.CreditBureau.IsServiceAvailable(iseProductClass.CreditEnquiry, SERVICE_ID, BranchId) Then
        ' Get Companies List
        Success = PerformCompanySelection(BranchId, Product, Data)
      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 WorkflowPk As Integer

  ' 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 ServiceName As String
  Public TestMode As Boolean

End Class



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

  Public Addresses As String
  Public BusinessNumber As String
  Public CompanyDirectors As String
  Public CompanyName As String
  Public CompanyNumber As String
  Public Status As String
  Public StatusCode As String

  Public Sub New(companySelectionResult As ISCreditEnquiryResponse_CentrixNZ_CompanySelectionResult)

    With companySelectionResult
      Me.Addresses = .Addresses
      Me.BusinessNumber = .NewZealandBusinessNumber
      Me.CompanyDirectors = .CompanyDirectors
      Me.CompanyName = .CompanyName
      Me.CompanyNumber = .CompanyNumber
      Me.StatusCode = .CompanyStatusCode
      Me.Status = .CompanyStatusCodeDescription
    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 Product As String
  Public BusinessNumber As String
  Public CompanyName As String
  Public CompanyNumber As String

  ' Options
  Public AccountType As String
  Public Amount As Decimal
  Public EnquiryNumber As String
  Public EnquiryReason As String
  Public IncludeOwnershipTree 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 "Centrix (New Zealand)" Organisation Credit enquiry to be perforrmed.

The following products are supported:
* Commercial Report
* Commercial Credit Report
* Commercial Credit Report Previous Report
* Commercial Beneficial Owners</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="CompanySelection" tooltipText="Select the Company to enquire upon."&gt;Company Selection&lt;/li&gt;
        &lt;li tabId="Options" tooltipText=""&gt;Options&lt;/li&gt;
        &lt;li tabId="Enquiry" tooltipText="Credit Enquiry results."&gt;Credit 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;!-- 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;!-- 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="lblEnquiryDetails"&gt;Enquiry details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtEnquiryNumber"&gt;Enquiry&amp;nbsp;Number:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtEnquiryNumber" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboEnquiryReason"&gt;Reason:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboEnquiryReason" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountType"&gt;Account Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAmount"&gt;Amount:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numAmount" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
           &lt;th colspan="2"&gt;&lt;input id="chkIncludeOwnershipTree" type="checkbox" /&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 mEnquiryDetails;

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

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

  lblProduct: null,
  cboProduct: null,

  wbClientSummary: null,

  // Options
  lblEnquiryDetails: null,
  txtEnquiryNumber: null,
  cboEnquiryReason: null,
  cboAccountType: null,
  numAmount: null,
  chkIncludeOwnershipTree: 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.lblEnquiryDetails = widget.UI.Label("lblEnquiryDetails", {});
  C.txtEnquiryNumber = widget.UI.TextBox("txtEnquiryNumber", {
    allowBlank: false,
    maxLength: 100,
  });
  C.cboEnquiryReason = widget.UI.ComboBox("cboEnquiryReason", {
    allowBlank: false,
    limitToList: true,
    maxLength: 100,
  });
  C.cboAccountType = widget.UI.ComboBox("cboAccountType", {
    allowBlank: false,
    limitToList: true,
    maxLength: 100,
  });
  C.numAmount = widget.UI.NumberBox("numAmount", {});
  C.chkIncludeOwnershipTree = widget.UI.CheckBox("chkIncludeOwnershipTree", {
    caption: "Include Ownership Tree?",
  });

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

    onInitialiseRow: gridCompanySelection_InitialiseRow,
    onRowDrilldown: gridCompanySelection_RowDrilldown,
  });
  C.gridCompanySelection.AddColumnCode("Status", { caption: "Status", visible: false });
  C.gridCompanySelection.AddColumnString("CompanyName", { caption: "Name"});
  C.gridCompanySelection.AddColumnString("CompanyNumber", { caption: "Number"});
  C.gridCompanySelection.AddColumnString("Addresses", { caption: "Addresses"});
  C.gridCompanySelection.AddColumnString("CompanyDirectors", { caption: "Directors"});

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

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = 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);
  }

  // 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 Credit 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();
    cboProduct_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 "Options":
      C.cboEnquiryReason.WidthResizeFromParent();
      C.cboAccountType.WidthResizeFromParent();
      C.numAmount.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 "Options":
          switch (C.cboProduct.Text().toUpperCase()) {
            case "COMMERCIAL BENEFICIAL OWNERS":
            case "COMMERCIAL REPORT":
            case "COMMERCIAL CREDIT REPORT PREVIOUS REPORT":
              found = true;
              break;
          }
          break;

        case "CompanySelection":
          if (C.cboProduct.Text().toUpperCase() != "COMMERCIAL CREDIT REPORT PREVIOUS REPORT") {
            found = true;
          }
          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 Credit 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 "General":
        // General Page has server-side validation, so do not assume default for this page
        break;

      case "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;
        }

        // Product-specific
        switch (C.cboProduct.Text().toUpperCase()) {
          case "COMMERCIAL BENEFICIAL OWNERS":
          case "COMMERCIAL REPORT":
            // Continues to Options page
            break;

          default:
            PerformEnquiry_Pre(validCallback);
            return;
        }
        break;

      case "Options":
        PerformEnquiry_Pre(validCallback);
        return;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        params = {
          branchId: C.cboBranch.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 "General":
        mRecord_CompanySelection = o.Data;

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

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ===========
// pageOptions
// ===========
function pageOptions_Refresh() {
  // Hide all
  C.txtEnquiryNumber.VisibleRow(false);

  C.cboEnquiryReason.VisibleRow(false);
  C.cboAccountType.VisibleRow(false);
  C.numAmount.VisibleRow(false);
  C.chkIncludeOwnershipTree.VisibleRow(false);

  // Show relevant options
  switch(C.cboProduct.Text().toUpperCase()) {
    case "COMMERCIAL BENEFICIAL OWNERS":
      pageOptions_Refresh_CommercialBeneficialOwners();
      break;

    case "COMMERCIAL REPORT":
      pageOptions_Refresh_CommercialReport();
      break;

    case "COMMERCIAL CREDIT REPORT PREVIOUS REPORT":
      pageOptions_Refresh_CommercialCreditReportPreviousReport();
      break;

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

function pageOptions_Refresh_CommercialReport() {
  // Show controls
  C.cboEnquiryReason.VisibleRow(true);
  C.cboAccountType.VisibleRow(true);
  C.numAmount.VisibleRow(true);

  // Retrieve Options
  pageOptions_Refresh_CommercialReport_GetOptions();
}

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

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

      // Finalise
      C.cboEnquiryReason.ListFromCsvString(data.EnquiryReasons);
      C.cboAccountType.ListFromCsvString(data.AccountTypes);
    },

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

function pageOptions_Refresh_CommercialCreditReportPreviousReport() {
  // Show controls
  C.txtEnquiryNumber.VisibleRow(true);
}

function pageOptions_Refresh_CommercialBeneficialOwners() {
  // Show controls
  C.chkIncludeOwnershipTree.VisibleRow(true);
}

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

  // Confirm
  if (mEnquiryDetails) {
    // Already created so just move on
    validCallback();
  }
  else {
    var message = "Are you sure you want to perform a " + mRecord.ServiceName + " Credit 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); });
  }
}

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

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

  widget.GetString("GetBranchDefaults", { branchId: C.cboBranch.Text() },
    // 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();
  }
}

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

  // Reset
  C.cboEnquiryReason.Text("");
  C.cboAccountType.Text("");
  C.numAmount.Value(0);

  // Get Options
  if (C.cboProduct.Text()) {
    // Block UI
    widget.UI.Block("Getting Product Options, please wait...");

    // Params
    var params = {
      BranchId: C.cboBranch.Text(),
      Product: C.cboProduct.Text(),
    };

    // Get Options
    widget.GetString("GetProductOptions", params, cboProduct_Change_Done, function(errorMessage) {
      // Unblock
      widget.UI.Unblock();

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

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

  // Handle Response
  switch (C.cboProduct.Text()) {
    default:
      break;
  }

  // Refresh Client Summary
  C.wbClientSummary.SetContent(data.ClientSummary, false);

  // Update Buttons
  tabWizard_UpdateButtons();

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

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

  switch (C.cboProduct.Text().toUpperCase()) {
    case "COMMERCIAL CREDIT REPORT PREVIOUS REPORT":
      params.EnquiryNumber = C.txtEnquiryNumber.Text();
      break;

    case "COMMERCIAL REPORT":
      params.EnquiryReason = C.cboEnquiryReason.Text();
      params.AccountType = C.cboAccountType.Text();
      params.Amount = C.numAmount.Value();
      // Do not break, as default parameters also need to be sent

    case "COMMERCIAL BENEFICIAL OWNERS":
      params.IncludeOwnershipTree = C.chkIncludeOwnershipTree.Value();
      // Do not break, as default parameters also need to be sent

    default:
      var item = mRecord_CompanySelection[C.gridCompanySelection.ActiveDataRowListIndex()];
      params.BusinessNumber = item.BusinessNumber;
      params.CompanyName = item.CompanyName;
      params.CompanyNumber = item.CompanyNumber;
      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.Addresses.value = item.Addresses;
  e.row.cells.CompanyDirectors.value = item.CompanyDirectors;

  // Styles
  e.row.cells.Addresses.small = true;
  e.row.cells.CompanyDirectors.small = true;
}

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