<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-18T01:42:41.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-09-18T01:38:56.7060000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-18T01:39:14.9670000</UpdatedUtcDate>
    <ScriptId>HWINZICE</ScriptId>
    <Description>illion (New Zealand) Individual Credit Enquiry</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_illionNZ_Individual
Option Explicit On
Option Strict On

' #################################################################
' illion (New Zealand) Individual Credit Enquiry wizard HTML Widget
'
' Version: 1.10 (18/09/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.05  12/07/2022  ISS      J028905   Show readonly cost centre information
'    1.06  22/07/2022  ISS      J026867   Implement supported products
'    1.07  16/03/2023  ISS      J030537   Default product update
'    1.08  22/03/2023  ISS      J030746   Product change event
'    1.09  27/05/2024  ISS      J033583   Added Print button
'    1.10  18/09/2024  ISS      J029950   Changed the Workflow Executor to the finBL.HtmlWidgetUtilities.WorkflowItemComplete function
' #################################################################

' Constants
Private Const FORM_KEY As String = "illionNZ_Individual"
Private Const SERVICE_ID As String = "illionNZ"
Private Const SUPPORTED_PRODUCTS As String = "Consumer Enquiry,Quotation Seeker"

' 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(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_IllionNZ As finCostCentreResolved_IllionNZ
  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_IllionNZ = finBL.CostCentresResolved.ItemByBranchId(BranchId).IllionNZ

  ' Get Default Product
  DefaultProduct = ""
  If Len(DefaultProduct) = 0 Then
    DefaultProduct = finBL.CreditBureau.GetServiceDefaultEnquiryProduct(SERVICE_ID, iseProductTarget.Individual, 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
        .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.Individual, 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.Individual, .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

      mCombinedParameters.SetString("Product", .DefaultProduct)
      mCombinedParameters.SetString("BranchId", .BranchId)
      If GetClientSummary(strTemp) Then
        .ClientSummary = strTemp
      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;
'''  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.IsIndividual AndAlso Len(Client.LastName) = 0 Then
      Success = False
      finBL.Error.ErrorBegin("Organisation type Clients must have a 'Person Acting' defined to perform an Individual Credit Enquiry.")
    End If
  End If

  Return Success

End Function

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

  Dim BranchId As String
  Dim ContactPhone As String
  Dim CreditEnquiryRequest As ISCreditEnquiryRequest
  Dim DriversLicenceNumber As String
  Dim Html As String
  Dim PassportExpiry As Date
  Dim PassportNumber As String
  Dim Product As String
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim ShowContactDetails As Boolean
  Dim ShowDriversLicence As Boolean
  Dim ShowPassport As Boolean
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable

  ' Assume Success
  Success = True

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

  ' Create Request
  If Success Then
    Success = CreateCreditEnquiryRequestForClient(BranchId, Product, CreditEnquiryRequest)
  End If

  ' Get Information from the Request
  If Success Then
    Select Case CreditEnquiryRequest.GetType()
      Case GetType(ISCreditEnquiryRequest_IllionNZ_ConsumerEnquiry)
        ' ----------------
        ' Consumer Enquiry
        ' ----------------
        ' No custom fields

      Case GetType(ISCreditEnquiryRequest_IllionNZ_QuotationSeeker)
        ' ----------------
        ' Quotation Seeker
        ' ----------------
        ' No custom fields

      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Unhandled Product '{0}'.", Product)
    End Select
  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()

      .TextBefore = "{{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("Person's details")
        .AddCaptionText("First Name:", CreditEnquiryRequest.FirstName)
        .AddCaptionText("Middle Names:", CreditEnquiryRequest.MiddleNames)
        .AddCaptionText("Last Name:", CreditEnquiryRequest.LastName)
        .AddCaptionDate("Date of Birth:", CreditEnquiryRequest.DateOfBirth)
        .AddCaptionText("Gender:", CreditEnquiryRequest.Gender)

        ' Contact Details
        If ShowContactDetails Then
          .AddSectionHeading2("Contact Details")
          .AddCaptionText("Phone No:", ContactPhone)
        End If

        ' Drivers Licence
        If ShowDriversLicence Then
          .AddSectionHeading2("Drivers Licence")
          If Len(DriversLicenceNumber) = 0 Then
            .AddWiki("{{warning|New Zealand Drivers Licence details not found.}}")
          Else
            .AddCaptionText("Licence No:", DriversLicenceNumber)
          End If
        End If

        ' Passport
        If ShowPassport Then
          .AddSectionHeading2("Passport")
          If Len(PassportNumber) = 0 Then
            .AddWiki("{{warning|Passport details not found.}}")
          Else
            .AddCaptionText("Passport No:", PassportNumber)
            If PassportExpiry &lt;&gt; Nothing Then .AddCaptionDate("Expiry:", PassportExpiry)
          End If
        End If

        ' Address details
        .AddSectionHeading2("Address details")
        .AddCaptionAddressDetailsPhysical("Current:", CreditEnquiryRequest.ToAddressDetails(False))
        .AddCaptionAddressDetailsPhysical("Previous:", CreditEnquiryRequest.ToAddressDetails(True))
      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()

      Html = .ToString(True)
    End With
  End If

  ' Finalise
  If Success Then
    returnValue = Html
  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 CreditObligations As Object
  Dim Data As Object
  Dim DefaultCreditObligation As String
  Dim DefaultAccountType As String
  Dim DefaultAmountSought As Decimal
  Dim DefaultEnquiryType As String
  Dim EnquiryTypes As Object
  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, CreditEnquiryRequest)

  ' Get Options page information
  If Success Then
    If TypeOf CreditEnquiryRequest Is ISCreditEnquiryRequest_IllionNZ_ConsumerEnquiry Then
      ' ----------------
      ' Consumer Enquiry
      ' ----------------
      Dim Request As ISCreditEnquiryRequest_IllionNZ_ConsumerEnquiry

      Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_IllionNZ_ConsumerEnquiry)
      With Request
        ' Lists
        AccountTypes = .AccountTypes.ToCodeDescriptionList().ToJsonObject()
        CreditObligations = .CreditObligations.ToCodeDescriptionList().ToJsonObject()
        EnquiryTypes = .EnquiryTypes.ToCodeDescriptionList().ToJsonObject()

        ' List Defaults
        DefaultAccountType = .AccountTypeDescription
        DefaultCreditObligation = .CreditObligationDescription
        DefaultEnquiryType = .EnquiryTypeDescription
        DefaultAmountSought = .AmountSought
      End With

    ElseIf TypeOf CreditEnquiryRequest Is ISCreditEnquiryRequest_IllionNZ_QuotationSeeker Then
      ' ----------------
      ' Quotation Seeker
      ' ----------------
      Dim Request As ISCreditEnquiryRequest_IllionNZ_QuotationSeeker

      Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_IllionNZ_QuotationSeeker)
      With Request
        ' Lists
        AccountTypes = .AccountTypes.ToCodeDescriptionList().ToJsonObject()
        CreditObligations = .CreditObligations.ToCodeDescriptionList().ToJsonObject()
        EnquiryTypes = .EnquiryTypes.ToCodeDescriptionList().ToJsonObject()

        ' List Defaults
        DefaultAccountType = .AccountTypeDescription
        DefaultCreditObligation = .CreditObligationDescription
        DefaultEnquiryType = .EnquiryTypeDescription
        DefaultAmountSought = .AmountSought
      End With
    Else
      finBL.Error.ErrorBeginFormat("Unhandled Product '{0}'.", Product)
      Success = False
    End If
  End If

  If Success Then
    Data = New With {
      .AccountTypes = AccountTypes,
      .CreditObligations = CreditObligations,
      .EnquiryTypes = EnquiryTypes,
      .DefaultAccountType = DefaultAccountType,
      .DefaultCreditObligation = DefaultCreditObligation,
      .DefaultEnquiryType = DefaultEnquiryType,
      .DefaultAmountSought = DefaultAmountSought
    }
  End If

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

  Return Success

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_IllionNZ_ConsumerEnquiry)
        ' ----------------
        ' Consumer Enquiry
        ' ----------------
        Dim Request As ISCreditEnquiryRequest_IllionNZ_ConsumerEnquiry

        Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_IllionNZ_ConsumerEnquiry)
        With Request
          .AccountTypeDescription = WizardFinishParameters.AccountType
          .CreditObligationDescription = WizardFinishParameters.CreditObligation
          .EnquiryTypeDescription = WizardFinishParameters.EnquiryType
          .AmountSought = WizardFinishParameters.AmountSought
        End With

      Case GetType(ISCreditEnquiryRequest_IllionNZ_QuotationSeeker)
        ' ----------------
        ' Quotation Seeker
        ' ----------------
        Dim Request As ISCreditEnquiryRequest_IllionNZ_QuotationSeeker

        Request = DirectCast(CreditEnquiryRequest, ISCreditEnquiryRequest_IllionNZ_QuotationSeeker)
        With Request
          .AccountTypeDescription = WizardFinishParameters.AccountType
          .CreditObligationDescription = WizardFinishParameters.CreditObligation
          .EnquiryTypeDescription = WizardFinishParameters.EnquiryType
          .AmountSought = WizardFinishParameters.AmountSought
        End With

      Case Else
        finBL.Error.ErrorBeginFormat("Unhandled Product '{0}'.", WizardFinishParameters.Product)
        Success = False
    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 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 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
    BranchId = .GetString("BranchId")
    PageId = .GetString("PageId")
  End With

  ' Validate Page
  Select Case PageId
    Case "General"
      ' Is Service Available
      If Not finBL.CreditBureau.IsServiceAvailable(iseProductClass.CreditEnquiry, SERVICE_ID, BranchId) Then
        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

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

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

  ' Options
  Public AccountType As String
  Public CreditObligation As String
  Public EnquiryType As String
  Public AmountSought As Decimal

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 "illion (New Zealand)" Individual Credit enquiry to be performed.

The following products are supported:
* Consumer Enquiry
* Quotation Seeker</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;Individual Credit Enquiry&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;!-- Options --&gt;
    &lt;div id="pageOptions"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:6em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;!-- Enquiry Details --&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="cboAccountType"&gt;Account&amp;nbsp;Type:&amp;nbsp;&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="cboCreditObligation"&gt;Credit&amp;nbsp;Obligation:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCreditObligation" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboEnquiryType"&gt;Enquiry&amp;nbsp;Type:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboEnquiryType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAmountSought"&gt;Amount:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numAmountSought" /&gt;&lt;/td&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_Options;
var mRecord_BranchDefaults;
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,
  cboAccountType: null,
  cboCreditObligation: null,
  cboEnquiryType: null,
  numAmountSought: null,

  // Enquiry
  wbSummary: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mLastBranch = "";
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.cboAccountType = widget.UI.ComboBox("cboAccountType", {
    allowBlank: false,
    limitToList: true,
    maxLength: 50,
  });
  C.cboCreditObligation = widget.UI.ComboBox("cboCreditObligation", {
    allowBlank: false,
    limitToList: true,
    maxLength: 50,
  });
  C.cboEnquiryType = widget.UI.ComboBox("cboEnquiryType", {
    allowBlank: false,
    limitToList: true,
    maxLength: 50,
  });
  C.numAmountSought = widget.UI.NumberBox("numAmountSought", {
    decimals: -1,
    minValue: 0,
    maxValue: 9999999,
  });

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

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

  // 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 "Options":
          if(C.cboProduct.Text().toUpperCase() != "DRIVER LICENCE VERIFICATION") {
            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 + " Individual 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 "Options":
        // Confirm
        if (mEnquiryDetails &amp;&amp; mLastFinishParametersJson != JSON.stringify(CreateFinishParameters())) {
          // Parameters have changed so allow performing another Credit Enquiry
          mEnquiryDetails = null;
        }

        // Confirm
        if (mEnquiryDetails) {
          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) });
        }
        return;

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

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

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

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

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

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

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

    accountType: C.cboAccountType.Text(),
    creditObligation: C.cboCreditObligation.Text(),
    enquiryType: C.cboEnquiryType.Text(),
    amountSought: C.numAmountSought.Value(),
  };

  return params;
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId) {
    default:
      break;
  }
}

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

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

// ===========
// pageOptions
// ===========
function pageOptions_Refresh() {
  // Hide all
  C.lblEnquiryDetails.VisibleRow(false);
  C.cboAccountType.VisibleRow(false);
  C.cboCreditObligation.VisibleRow(false);
  C.cboEnquiryType.VisibleRow(false);
  C.numAmountSought.VisibleRow(false);

  // Show relevant options
  switch(C.cboProduct.Text().toUpperCase()) {
    case "CONSUMER ENQUIRY":
    case "QUOTATION SEEKER":
      pageOptions_Refresh_ConsumerQuotation();
      break;

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

function pageOptions_Refresh_ConsumerQuotation() {
  // Show Controls
  C.lblEnquiryDetails.VisibleRow(true);
  C.cboAccountType.VisibleRow(true);
  C.cboCreditObligation.VisibleRow(true);
  C.cboEnquiryType.VisibleRow(true);
  C.numAmountSought.VisibleRow(true);

  // Retrieve Options
  pageOptions_Refresh_ConsumerQuotation_GetOptions();
}

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

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

      // Finalise
      pageOptions_Refresh_ConsumerQuotation_GetOptions_Done();
    },

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

function pageOptions_Refresh_ConsumerQuotation_GetOptions_Done() {
  // Lists
  C.cboAccountType.ListFromCodeDescriptionList(mRecord_Options.AccountTypes);
  C.cboCreditObligation.ListFromCodeDescriptionList(mRecord_Options.CreditObligations);
  C.cboEnquiryType.ListFromCodeDescriptionList(mRecord_Options.EnquiryTypes);

  // Defaults
  C.cboAccountType.Text(mRecord_Options.DefaultAccountType);
  C.cboCreditObligation.Text(mRecord_Options.DefaultCreditObligation);
  C.cboEnquiryType.Text(mRecord_Options.DefaultEnquiryType);
  C.numAmountSought.Value(mRecord_Options.DefaultAmountSought);
}

// =========
// 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) {
        // Set Default Product
        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;
  
  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>YvglzU4Gw0yv3HnERSTNmQ</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_Illion</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>