<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-07-31T04:01:28.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2022-08-14T22:59:27.0270000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2023-07-31T04:00:59.7470000</UpdatedUtcDate>
    <ScriptId>SEPPSRNZ</ScriptId>
    <Description>PPSRNZ Security Enquiry</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_PPSRNZ_Security
Option Explicit On
Option Strict On

' #################################################################
' PPSRNZ Security Enquiry wizard
'
' Version: 1.06 (31/07/2023)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  07/06/2022  ISS      J027794   Created
'    1.01  22/06/2022  ISS      J028914   Enable history for Collateral Items
'    1.02  11/07/2022  ISS      J028905   Show readonly cost centre information
'    1.03  22/07/2022  ISS      J026867   Implement supported products
'    1.04  29/08/2022  ISS      J028816   Branch now defaults for Workflows
'    1.05  16/03/2023  ISS      J030537   Default product update
'    1.06  31/07/2023  ISS      J031048   Security Enquiries for unsaved Security Statement Items are now recorded in the Json
' #################################################################

' Constants
Private Const FORM_KEY As String = "PPSRNZ_Security"
Private Const SERVICE_ID As String = "PPSRNZ"
Private Const SUPPORTED_PRODUCTS As String = "Get Vehicle Data"

' Common Parameters
Private mAccountAppCollateralItemPk As Integer
Private mAccountAppId As String
Private mBranchId As String
Private mSecurityStmtId As String
Private mSecurityStmtItemJson As String
Private mSecurityStmtItemPk As Integer
Private mWorkflowItemPk As Integer
Private mWorkflowPk 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
    mAccountAppCollateralItemPk = .GetInteger("AccountAppCollateralItemPk")
    mAccountAppId = .GetString("AccountAppId")
    mBranchId = .GetString("BranchId")
    mSecurityStmtId = .GetString("SecurityStmtId")
    mSecurityStmtItemJson = .GetString("SecurityStmtItemJson")
    mSecurityStmtItemPk = .GetInteger("SecurityStmtItemPk")
    mWorkflowItemPk = .GetInteger("WorkflowItemPk")
    mWorkflowPk = .GetInteger("WorkflowPk")

    If mSecurityStmtItemPk = 0 Then
      ' NOTE: Older Application Shortcuts have a different named parameters
      mSecurityStmtItemPk = .GetInteger("Id")
    End If
  End With

  ' Validate
  Main = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)

  ' Handle Events
  If Main Then
    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 "GetHistory"
        ' Get History records
        Main = GetHistory(returnValue)

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

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

      Case "PerformEnquiry"
        ' Perform Enquiry
        Main = PerformEnquiry(parametersJson, returnValue)

      Case "UpdateDifferences"
        ' Update Differences
        Main = UpdateDifferences(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 If

End Function

''' &lt;summary&gt;
'''  Create a finAccountAppCollateralItem object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function GetAccountAppCollateralItem(ByRef accountAppCollateralItem As finAccountAppCollateralItem) As Boolean

  Dim AccountApp As finAccountApp
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  accountAppCollateralItem = Nothing

  ' Validate
  If Len(mAccountAppId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Application Id not specified.")
  ElseIf mAccountAppCollateralItemPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Application Collateral Item Pk not specified.")
  ElseIf mAccountAppCollateralItemPk &lt; -1 Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Account Application Collateral Item Pk '{0}'.", mAccountAppCollateralItemPk)
  End If

  ' Load and Validate
  If Success Then
    AccountApp = finBL.CreateAccountApp()
    If AccountApp.Load(mAccountAppId) Then
      If AccountApp.CollateralItems.ExistsPk(mAccountAppCollateralItemPk) Then
        accountAppCollateralItem = AccountApp.CollateralItems.ItemByPk(mAccountAppCollateralItemPk)

        ' Ensure it is a Motor vehicle
        Select Case accountAppCollateralItem.SecurityBaseType
          Case isefinSecurityBaseType.MotorVehicle
            ' OK

          Case Else
            Success = False
            finBL.Error.ErrorBegin("Invalid Account Application Collateral Item Base Type.")

        End Select
      Else
        Success = False
        finBL.Error.ErrorBeginFormat("Invalid Account Application Collateral Item Pk '{0}'.", mAccountAppCollateralItemPk)
      End If
    Else
      Success = False
      finBL.Error.ErrorBeginFormat("Invalid Account Application Id '{0}'.", mAccountAppId)
    End If
  End If

  If Not Success Then
    accountAppCollateralItem = Nothing
  End If

  ' Return Success
  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 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 Default Product - PPSR NZ is not not Cost Centres
  DefaultProduct = "Get Vehicle Data"

  ' 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 {
    .BranchId = BranchId,
    .DefaultProduct = DefaultProduct
  }

  ' Serialise
  Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)

  Return Success

End Function

''' &lt;summary&gt;
'''  Get History records.
''' &lt;/summary&gt;
Public Function GetHistory(ByRef response As String) As Boolean

  Dim AccountAppCollateralItem As finAccountAppCollateralItem
  Dim HistoryItems As List(Of HistoryItem)
  Dim SecurityStmtItem As finSecurityStmtItemBase
  Dim ServiceLog As ISServiceLog
  Dim ServiceLogs As ISServiceLogs
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  HistoryItems = New List(Of HistoryItem)()

  If mSecurityStmtItemPk &lt;&gt; 0 OrElse mAccountAppCollateralItemPk &lt;&gt; 0 Then
    ' Load Security Item
    If Success Then
      If mSecurityStmtItemPk &lt;&gt; 0 OrElse Len(mSecurityStmtItemJson) &lt;&gt; 0 Then
        ' Get Security Statement Item
        Success = GetSecurityStmtItem(SecurityStmtItem)

        ' Get the Service Logs
        If Success Then
          ServiceLogs = SecurityStmtItem.SecurityEnquiries
        End If
      ElseIf mAccountAppCollateralItemPk &lt;&gt; 0 Then
        ' Get Account App Collateral Item
        Success = GetAccountAppCollateralItem(AccountAppCollateralItem)

        ' Get the Service Logs
        If Success Then
          ServiceLogs = AccountAppCollateralItem.SecurityEnquiries
        End If
      Else
        Success = False
      End If
    End If

    ' Get History Items
    If Success AndAlso ServiceLogs IsNot Nothing Then
      For Each ServiceLog In ServiceLogs
        HistoryItems.Add(New HistoryItem(finBL, ServiceLog))
      Next
    End If
  End If

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

  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 AccountAppCollateralItem As finAccountAppCollateralItem
  Dim BranchId As String
  Dim BranchRO As finBranchRO
  Dim Caption As String
  Dim Chargeable As Boolean
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ListRO As ISListReadOnly
  Dim Plate As String
  Dim SecurityStmtItem As finSecurityStmtItemBase
  Dim Success As Boolean
  Dim Vin As String
  Dim Warning As String
  Dim WorkFlow As finWorkflow

  ' Assume Success
  Success = True

  ' Validate Parameters
  If Len(mAccountAppId) = 0 AndAlso mAccountAppCollateralItemPk &lt;&gt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("An AccountAppId must be specified if an AccountAppCollateralItemPk has been supplied.")
  ElseIf Len(mAccountAppId) &lt;&gt; 0 AndAlso mAccountAppCollateralItemPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("An AccountAppCollateralItemPk must be specified if an AccountAppId has been supplied.")
  ElseIf Len(mSecurityStmtId) = 0 AndAlso mSecurityStmtItemPk &lt;&gt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("A SecurityStmtId must be specified if a SecurityStmtItemPk has been supplied.")
  ElseIf Len(mSecurityStmtId) &lt;&gt; 0 AndAlso mSecurityStmtItemPk = 0 AndAlso Len(mSecurityStmtItemJson) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("A SecurityStmtItemPk must be specified if a SecurityStmtId has been supplied.")
  ElseIf mWorkflowPk = 0 AndAlso mWorkflowItemPk &lt;&gt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("You must also specify the WorkflowPk if a Workflow Item has been specified.")
  ElseIf mWorkflowPk &lt;&gt; 0 AndAlso mWorkflowItemPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("You must also specify the WorkflowItemPk of the Workflow Item to Action if a Workflow has been specified.")
  End If

  ' Get Security/ Collateral Item
  If Success Then
    If mSecurityStmtItemPk &lt;&gt; 0 OrElse Len(mSecurityStmtItemJson) &lt;&gt; 0 Then
      ' Get Security Statement Item
      Success = GetSecurityStmtItem(SecurityStmtItem)
      Caption = "Security Item"
    ElseIf mAccountAppCollateralItemPk &lt;&gt; 0 Then
      ' Get Account App Collateral Item
      Success = GetAccountAppCollateralItem(AccountAppCollateralItem)
      Caption = "Collateral Item"
    ElseIf mWorkflowPk &lt;&gt; 0 Then
      Workflow = finBL.CreateWorkflow()
      Success = Workflow.LoadPk(mWorkflowPk)
    End If
  End If

  ' Branch
  If Success Then
    If Len(mBranchId) &lt;&gt; 0 Then
      BranchId = mBranchId
    ElseIf SecurityStmtItem IsNot Nothing Then
      BranchId = finBL.CostCentreFunctions.GetDefaultBranchId(SecurityStmtItem.SecurityStmt)
    ElseIf AccountAppCollateralItem IsNot Nothing Then
      BranchId = finBL.CostCentreFunctions.GetDefaultBranchId(AccountAppCollateralItem.AccountApp)
    ElseIf Workflow IsNot Nothing Then
      BranchId = finBL.CostCentreFunctions.GetDefaultBranchId(Workflow)
    Else
      BranchId = finBL.CostCentreFunctions.GetDefaultBranchId()
    End If
  End If

  ' Plate and VIN
  If Success Then
    If SecurityStmtItem IsNot Nothing AndAlso SecurityStmtItem.ItemAsMotorVehicle IsNot Nothing Then
      Plate = SecurityStmtItem.ItemAsMotorVehicle.RegistrationNumber
      Vin = SecurityStmtItem.ItemAsMotorVehicle.VIN
    ElseIf AccountAppCollateralItem IsNot Nothing Then
      Plate = AccountAppCollateralItem.RegistrationNumber
      Vin = AccountAppCollateralItem.VIN
    Else
      Plate = ""
      Vin = ""
    End If
  End If

  ' Cache Request
    With finBL.SecurityEnquiry.Service_PPSRNZ.CreateRequest_GetVehicleData()
      Chargeable = .Chargeable
      Warning = .ProductWarning
    End With

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

    ' Other Properties
    With FormInitialisationInfo
      ' Record
      .AccountAppId = mAccountAppId
      .AccountAppCollateralItemPk = mAccountAppCollateralItemPk
      .SecurityStmtId = mSecurityStmtId
      .SecurityStmtItemPk = mSecurityStmtItemPk

      ' General
      .WorkflowPk = mWorkflowPk

      ' Branch
      .BranchId = BranchId

      ' Security
      .Caption = Caption
      .Plate = Plate
      .Vin = Vin
      .Warning = Warning

      ' Lists
      For Each BranchRO In finBL.Branches
        .Branches.Add(New BranchInfo(BranchRO, SERVICE_ID))
      Next
      'ListRO = finBL.SecurityEnquiry.GetSecurityEnquiryProductIdsList(0, SERVICE_ID)
      ListRO = finBL.Runtime.CreateListReadOnly(SUPPORTED_PRODUCTS)
      .ProductsList = ListRO.ToCsvString()

      ' Defaults
      If ListRO.Count = 1 Then
        .DefaultProduct = ListRO(0)
      Else
        .DefaultProduct = finBL.SecurityEnquiry.GetSecurityEnquiryDefaultProduct(SERVICE_ID, 0)
        If Not ListRO.Exists(.DefaultProduct) Then
          finBL.Trace.WriteWarning(String.Format("Default product {0} not supported by this HTML Widget.", .DefaultProduct))
          .DefaultProduct = ListRO(0)
        End If
      End If

      ' Chargeable
      .Chargeable = Chargeable

      ' Configuration
      .AdHocEnquiry = mSecurityStmtItemPk = 0 AndAlso mAccountAppCollateralItemPk = 0 AndAlso Len(mSecurityStmtItemJson) = 0
      .AllowBranch = Len(mBranchId) &lt;&gt; 0
      .ShowBranch = finBL.Settings.AddOns.CostCentre
      .EditJson = Len(mSecurityStmtItemJson) &lt;&gt; 0
      .ServiceName = finBL.SecurityEnquiry.Service_PPSRNZ.ServiceName
      .TestMode = finBL.SettingsUser.CostCentreTestModeResolved

      ' Update Defaults to keep in sync
      mCombinedParameters.SetString("Product", .DefaultProduct)
      mCombinedParameters.SetString("BranchId", .BranchId)
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Create a finSecurityStmtItem object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function GetSecurityStmtItem(ByRef securityStmtItem As finSecurityStmtItemBase) As Boolean

  Dim JsonHtmlWidgetSecurityStmtItem As finSecurityStmtItemBase.jsonHtmlWidgetSecurityStmtItem
  Dim obj As Object
  Dim SecurityStmt As finSecurityStmt
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  securityStmtItem = Nothing

  ' Validate
  If Len(mSecurityStmtId) = 0 AndAlso Len(mSecurityStmtItemJson) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Security Statement Id not specified.")
  ElseIf mSecurityStmtItemPk = 0 AndAlso Len(mSecurityStmtItemJson) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Security Statement Item Pk not specified.")
  ElseIf mSecurityStmtItemPk &lt; -1 Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Security Statement Item Pk '{0}'.", mSecurityStmtItemPk)
  ElseIf finBL.IsRunningFromWeb AndAlso Not finBL.CurrentUser.Permissions.Allow("Cloud.Form.SecurityStmt") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view the Security Statement and associated forms.")
  End If

  ' Load and Validate
  If Success Then
    SecurityStmt = finBL.CreateSecurityStmt()
    If SecurityStmt.Load(mSecurityStmtId) Then
      If SecurityStmt.SecurityItems.ExistsPk(mSecurityStmtItemPk) Then
        securityStmtItem = SecurityStmt.SecurityItems.ItemByPk(mSecurityStmtItemPk)

        ' Ensure it is a Motor vehicle
        Select Case securityStmtItem.BaseType
          Case isefinSecurityBaseType.MotorVehicle
            ' OK

          Case Else
            Success = False
            finBL.Error.ErrorBegin("Invalid Security Statement Item Base Type.")

        End Select
      ElseIf Len(mSecurityStmtItemJson) &lt;&gt; 0 Then
        ' Create temporary Security Statement Item, e.g., when running a Security Enquiry from the Security Statement Item Edit form
        If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(mSecurityStmtItemJson, GetType(finSecurityStmtItemBase.jsonHtmlWidgetSecurityStmtItem), obj) Then
          ' Need the Security Type in order to create the correct object
          JsonHtmlWidgetSecurityStmtItem = DirectCast(obj, finSecurityStmtItemBase.jsonHtmlWidgetSecurityStmtItem)
          securityStmtItem = SecurityStmt.SecurityItems.CreateSecurityStmtItem(JsonHtmlWidgetSecurityStmtItem.SecurityTypeId)
          Success = securityStmtItem.FromHtmlWidgetJsonString(mSecurityStmtItemJson)
        Else
          Success = False
        End If
      Else
        Success = False
        finBL.Error.ErrorBeginFormat("Invalid Security Statement Item Pk '{0}'.", mSecurityStmtItemPk)
      End If
    Else
      Success = False
    End If
  End If

  ' Return Success
  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 ServiceLog As ISServiceLog
  Dim ServiceLogPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Report
  Html = GetServiceReportInternal(ServiceLogPk, ServiceLog)

  ' Finalise
  If Success Then
    returnValue = Html
  End If

  Return Success

End Function

Private Function GetServiceReportInternal(serviceLogPk As Integer,
                                          ByRef serviceLog As ISServiceLog) As String

  Dim Html As String

  ' Get HTML
  If finBL.Database.GetServiceLog(serviceLogPk, ServiceLog) Then
    If Not finBL.SecurityEnquiry.GetSecurityEnquiryHtmlFromServiceLog(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)
    serviceLog = Nothing
  End If

  Return Html

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 AccountAppCollateralItem As finAccountAppCollateralItem
  Dim CompareItems As finCompareItems
  Dim Data As Object
  Dim ExecutePostFailed As Boolean
  Dim Html As String
  Dim obj As Object
  Dim Ok As Boolean
  Dim RefreshDifferences As Boolean
  Dim SecurityEnquiryPerformed As Boolean
  Dim SecurityEnquiryRequest As ISSecurityEnquiryRequest
  Dim SecurityEnquiryResponse As ISSecurityEnquiryResponse
  Dim SecurityStmtItem As finSecurityStmtItemBase
  Dim ServiceLog As ISServiceLog
  Dim ServiceLogCreateDetails As ISServiceLogCreateDetails
  Dim ServiceLogPk As Integer
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' 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
    SecurityEnquiryRequest = finBL.SecurityEnquiry.CreateSecurityEnquiryRequest(SERVICE_ID, WizardFinishParameters.Product, WizardFinishParameters.BranchId)
    If SecurityEnquiryRequest Is Nothing Then
      Success = False
    End If
  End If

  ' Options
  If Success Then
    Select Case SecurityEnquiryRequest.GetType()
      Case GetType(ISSecurityEnquiryRequest_PPSRNZ_GetVehicleData)
        ' ----------------
        ' Get Vehicle Data
        ' ----------------
        RefreshDifferences = True
        With DirectCast(SecurityEnquiryRequest, ISSecurityEnquiryRequest_PPSRNZ_GetVehicleData)
          .Vin = WizardFinishParameters.Vin
          .RegistrationPlate = WizardFinishParameters.PlateNumber
        End With

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

  ' Get Security/ Collateral Item
  If Success Then
    If mSecurityStmtItemPk &lt;&gt; 0 OrElse Len(mSecurityStmtItemJson) &lt;&gt; 0 Then
      Success = Me.GetSecurityStmtItem(SecurityStmtItem)
    ElseIf mAccountAppCollateralItemPk &lt;&gt; 0 Then
      Success = Me.GetAccountAppCollateralItem(AccountAppCollateralItem)
    End If
  End If

  ' Execute
  If Success Then
    If finBL.SecurityEnquiry.ExecuteSecurityEnquiry(SecurityEnquiryRequest, SecurityEnquiryResponse, SecurityStmtItem, ServiceLogCreateDetails, ExecutePostFailed, AccountAppCollateralItem) Then
      ServiceLogPk = ServiceLogCreateDetails.ServiceLogPk
      SecurityEnquiryPerformed = True
      If ExecutePostFailed Then Warning = finBL.Error.Message()
    Else
      SecurityEnquiryPerformed = False
      Success = False
    End If
  End If

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

  ' Add Log for Workflow (link to Service Log)
  If Success AndAlso mWorkflowPk &lt;&gt; 0 AndAlso ServiceLog IsNot Nothing Then
    If Not finBL.WorkflowFunctions.WorkflowAddSecurityEnquiryLog(mWorkflowPk, mWorkflowItemPk, ServiceLog) Then
      'gUI.ErrorMessageShow()
    End If
  End If

  ' Refresh Differences
  If Success AndAlso RefreshDifferences Then
    If SecurityStmtItem IsNot Nothing Then
      ' -------------
      ' Security Item
      ' -------------
      If finBL.CurrentUser.Permissions.Allow("SecurityItem.Update") Then
        Success = finBL.SecurityEnquiry.GetSecurityStmtItemDifferences(SecurityStmtItem, ServiceLogPk, CompareItems)
      Else
        CompareItems = Nothing
      End If
    ElseIf AccountAppCollateralItem IsNot Nothing Then
      ' ---------------
      ' Collateral Item
      ' ---------------
      Ok = finBL.CurrentUser.Permissions.Allow("AccountApp.Update")
      If Ok AndAlso AccountAppCollateralItem.AccountApp.Status = isefinAccountAppStatus.Reviewing Then
        Ok = finBL.CurrentUser.Permissions.Allow("AccountApp.UpdateReviewing")
      End If

      If Ok Then
        Success = finBL.SecurityEnquiry.GetAccountAppCollateralItemDifferences(AccountAppCollateralItem, ServiceLogPk, CompareItems)
      Else
        CompareItems = Nothing
      End If
    End If
    If CompareItems IsNot Nothing Then Data = CompareItems.ToHtmlWidgetJsonObject()
  End If

  ' Complete Workflow Item if there are no Differences
  ' NOTE: If there are differences then the Workflow Item will be completed in UpdateDifferences
  If Success AndAlso mWorkflowPk &lt;&gt; 0 AndAlso CompareItems Is Nothing Then
    finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, Warning)
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(mSecurityStmtItemPk, mAccountAppCollateralItemPk, Data, Html, SecurityEnquiryPerformed, ServiceLogPk, Warning, ""), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Update Security/ Collateral Item from Differences grids.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function UpdateDifferences(parametersJson As String,
                                   ByRef returnValue As String) As Boolean

  Dim AccountAppCollateralItem As finAccountAppCollateralItem
  Dim CompareItems As finCompareItems
  Dim Data As Object
  Dim Html As String
  Dim Json As String
  Dim obj As Object
  Dim Ok As Boolean
  Dim SecurityStmtItem As finSecurityStmtItemBase
  Dim ServiceLogPk As Integer
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Get Security/ Collateral Item
  If Success Then
    If mSecurityStmtItemPk &lt;&gt; 0 OrElse Len(mSecurityStmtItemJson) &lt;&gt; 0 Then Me.GetSecurityStmtItem(SecurityStmtItem)
    If mAccountAppCollateralItemPk &lt;&gt; 0 Then Me.GetAccountAppCollateralItem(AccountAppCollateralItem)
  End If

  ' Get the Differences
  If Success Then
    If SecurityStmtItem IsNot Nothing Then
      ' -------------
      ' Security Item
      ' -------------
      Ok = finBL.CurrentUser.Permissions.Allow("SecurityItem.Update")

      If Ok Then
        Success = finBL.SecurityEnquiry.GetSecurityStmtItemDifferences(SecurityStmtItem, WizardFinishParameters.ServiceLogPk, CompareItems)
      Else
        CompareItems = Nothing
      End If
    ElseIf AccountAppCollateralItem IsNot Nothing Then
      ' ---------------
      ' Collateral Item
      ' ---------------
      Ok = finBL.CurrentUser.Permissions.Allow("AccountApp.Update")
      If Ok AndAlso AccountAppCollateralItem.AccountApp.Status = isefinAccountAppStatus.Reviewing Then
        Ok = finBL.CurrentUser.Permissions.Allow("AccountApp.UpdateReviewing")
      End If

      If Ok Then
        Success = finBL.SecurityEnquiry.GetAccountAppCollateralItemDifferences(AccountAppCollateralItem, WizardFinishParameters.ServiceLogPk, CompareItems)
      Else
        CompareItems = Nothing
      End If
    End If
  End If

  ' Get Compare Items
  If Success And CompareItems IsNot Nothing Then
    Success = CompareItems.UpdateFromHtmlWidgetJsonString(WizardFinishParameters.CompareItemsJson)
  End If

  ' Update Security/ Collateral Item
  If Success Then
    If CompareItems IsNot Nothing AndAlso CompareItems.CountDifferences &lt;&gt; 0 Then
      If SecurityStmtItem IsNot Nothing Then
        ' -------------
        ' Security Item
        ' -------------
        Success = finBL.SecurityEnquiry.UpdateSecurityStmtItemDifferences(SecurityStmtItem, CompareItems)
        If Success Then
          If Len(mSecurityStmtItemJson) = 0 Then
            ' Save Security Statement
            Success = SecurityStmtItem.SecurityStmt.Save()
          Else
            ' Return updated Security Statement Item JSON (this can then be passed back to the Security Statement Item Edit form)
            Json = SecurityStmtItem.ToHtmlWidgetJsonString()
          End If
        End If
      ElseIf AccountAppCollateralItem IsNot Nothing Then
        ' ---------------
        ' Collateral Item
        ' ---------------
        Success = finBL.SecurityEnquiry.UpdateAccountAppCollateralItemDifferences(AccountAppCollateralItem, CompareItems)
        If Success Then
          Success = AccountAppCollateralItem.AccountApp.Save()
        End If
      End If
    End If
  End If

  ' Complete Workflow
  If Success AndAlso WizardFinishParameters.SecurityEnquiryPerformed AndAlso mWorkflowPk &lt;&gt; 0 AndAlso mWorkflowItemPk &lt;&gt; 0 Then
    finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, Warning)
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(mSecurityStmtItemPk, mAccountAppCollateralItemPk, Data, Html, WizardFinishParameters.SecurityEnquiryPerformed, ServiceLogPk, Warning, Json), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object; "true" if validation passed, otherwise, information as to why validation failed.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim 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.SecurityEnquiry.IsServiceAvailableAndConfigured(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
        Else
          Me.CostCentreText = "Cost Centre not defined for this Service."
        End If
      Else
        Me.CostCentreText = "Cost Centre not defined for this Service."
      End If
    End If

  End Sub

End Class


''' &lt;summary&gt;
'''  History item.
''' &lt;/summary&gt;
Public Class HistoryItem

  Public Pk As Integer
  Public CreatedDate As Date
  Public ServiceId As String
  Public ProductClass As String
  Public ProductId As String
  Public ProductOptions As String
  Public EnquiryReference As String

  Public Sub New (finBL As ISfinSupport,
                  serviceLog As ISServiceLog)

    With serviceLog
      Me.Pk = .Pk
      Me.CreatedDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(.CreatedDate)
      Me.ServiceId = .ServiceId
      Me.ProductClass = .ProductClass
      Me.ProductId = .ProductId
      Me.ProductOptions = .ProductOptions
      Me.EnquiryReference = .EnquiryReference
    End With

  End Sub

End Class


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

  ' Record
  Public AccountAppId As String
  Public AccountAppCollateralItemPk As Integer
  Public SecurityStmtId As String
  Public SecurityStmtItemPk As Integer

  Public BranchId As String
  Public WorkflowPk As Integer

  ' Security
  Public Caption As String
  Public Plate As String
  Public Vin As String
  Public Warning As String

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

  ' Defaults
  Public DefaultProduct As String

  ' Chargeable
  Public Chargeable As Boolean

  ' Configuration
  Public AdHocEnquiry As Boolean
  Public EditJson As Boolean
  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

  ' General Security Enquiry
  Public PlateNumber As String
  Public Vin As String

  ' Differences
  Public CompareItemsJson As String
  Public SecurityEnquiryPerformed As Boolean
  Public ServiceLogPk As Integer

End Class


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

  ' General
  Public AccountAppCollateralItemPk As Integer
  Public SecurityStmtItemPk As Integer
  Public Data As Object
  Public Html As String
  Public SecurityEnquiryPerformed As Boolean
  Public ServiceLogPk As Integer
  Public UpdatedItemJson As String
  Public Warning As String

  Public Sub New(securityStmtItemPk As Integer,
                 accountAppCollateralItemPk As Integer,
                 data As Object,
                 html As String,
                 securityEnquiryPerformed As Boolean,
                 serviceLogPk As Integer,
                 warning As String,
                 updatedItemJson As String)

    With Me
    .AccountAppCollateralItemPk = accountAppCollateralItemPk
    .SecurityStmtItemPk = securityStmtItemPk
    .Data = data
    .Html = html
    .SecurityEnquiryPerformed = securityEnquiryPerformed
    .ServiceLogPk = serviceLogPk
    .Warning = warning
    .UpdatedItemJson = updatedItemJson
  End With

  End Sub

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

Used as a finPOWER Connect Cloud compatible wizard to allow an "PPSRNZ" Security Enquiry to be performed.

The following products are supported:
* Get Vehicle Data</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="History"&gt;Security Enquiry History&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Confirm security details."&gt;Security Enquiry&lt;/li&gt;
        &lt;li tabId="Enquiry" tooltipText="Security Enquiry results."&gt;Security Enquiry Report&lt;/li&gt;
        &lt;li tabId="Differences" tooltipText="Select differences to update on the Security Item."&gt;Update Differences&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- History --&gt;
    &lt;div id="pageHistory"&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="gridHistory" style="height:100%"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- General --&gt;
    &lt;div id="pageGeneral" style="display:flex;flex-direction:column;"&gt;
      &lt;table class="is-form" &gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&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 Security Enquiry 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&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;div id="divWarning" class="is-info-text info small" style="display:none"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;!-- Vehicle Report --&gt;
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblSearchDetails"&gt;Search details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPlate"&gt;Plate:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPlate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtVin"&gt;VIN:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtVin" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/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;!-- Differences --&gt;
    &lt;div id="pageDifferences" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:1; position:relative"&gt;
        &lt;div id="cigDifferences" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdHistory" class="is-button" style="float:left"&gt;History&lt;/button&gt;

    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;&amp;lt; Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next &amp;gt;&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Finish&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;



&lt;script&gt;
// Properties
var mRecord;
var mRecord_BranchDefaults;
var mRecord_Differences;
var mRecord_History;
var mEnquiryDetails;


// Controls
var C = {
  // History
  gridHistory: null,

  // General
  lblBranch: null,
  cboBranch: null,
  divCostCentreInformation: null,

  lblProduct: null,
  cboProduct: null,
  divWarning: null,

  // Vehicle Report
  lblSearchDetails: null,
  txtPlate: null,
  txtVin: null,

  // Enquiry
  wbSummary: null,

  // Differences
  cigDifferences: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;

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

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

  // --------
  // Controls
  // --------
  //   History
  C.gridHistory = widget.UI.Grid("gridHistory", {
    rowNumbering: true,
    stickyHeader: true,

    onInitialiseRow: gridHistory_InitialiseRow,
    onRowDrilldown: gridHistory_RowDrilldown,
  });

  //   General
  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.divWarning = $("#divWarning");

  //   Vehicle Report
  C.lblSearchDetails = widget.UI.Label("lblSearchDetails", {});
  C.txtPlate = widget.UI.TextBox("txtPlate", {
    allowBlank: true,
    maxLength: 6,
    width: "8em",
  });
  C.txtVin = widget.UI.TextBox("txtVin", {
    allowBlank: true,
    maxLength: 17,
    width: "14em",
  });

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

  //   Differences
  C.cigDifferences = widget.UI.CompareItemsGrid("cigDifferences", {});

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

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

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdBack = $("#cmdBack");
  cmdNext = $("#cmdNext");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabWizard_Cancel);
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  cmdHistory = $("#cmdHistory");
  cmdHistory.click(function() { Form_ExecuteAction("History"); });

  // 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;
  mRecord_Differences = null;
  mRecord_History = 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) {
    // Disable close button for non adhoc query that has a workflow
    if (!mRecord.AdHocEnquiry &amp;&amp; mRecord.WorkflowPk != 0) {
      widget.DisableCloseButton();
    }

    // General
    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 + " Security Enquiry (Test Mode)");
  }

  // Information Lists

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

  // Controls
  if (mRecord) {
    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() {
  var VisibleTabCount = tabWizard.TabCount();
  var tabIndex = tabWizard.SelectedTabIndex();

  // Unbind the Finish button so that we don't call it multiple times
  cmdFinish.unbind("click");

  if (mRecord &amp;&amp; mRecord.AdHocEnquiry) {
      // Finish Button
    cmdFinish.click(function() { Form_ExecuteAction("Close"); });

    VisibleTabCount -= 1;

    // History Button
    cmdHistory.hide();

    // Back and Next Buttons?
    cmdBack.prop("disabled", tabIndex &lt;= 1);
    cmdNext.prop("disabled", tabIndex &gt;= VisibleTabCount - 1);

    // Finish Button
    cmdFinish.text("Close");
    cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
  }
  else {
    // Finish Button
    cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

    // History Button
    if (tabIndex == 0) {
      cmdHistory.hide();
    }
    else {
      cmdHistory.show();
    }

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

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "History":
      break;

    case "General":
      C.cboProduct.WidthResizeFromParent();
      break;

    default:
      break;
  }

  // Auto-Format page To sort out topmost headings
  tabWizard.AutoFormatPage();
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

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

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

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

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "History":
      // Load History (we move back to this page, not forward!)
      if (!mRecord_History) {
        gridHistory_Refresh();
      }
      else {
        // Refresh (e.g., to show hidden rows)
        C.gridHistory.VirtualDataRefresh(mRecord_History);

        // Activate Last Row
        C.gridHistory.ActivateLastDataRow();
      }
      break;

    case "General":
      var summary = "Confirm security details";
      if (mRecord.SecurityStmtId) {
        summary += " for Security Statement '" + mRecord.SecurityStmtId + "'.";
      }
      else if(mRecord.AccountAppId) {
        summary += " for Account Application '" + mRecord.AccountAppId + "'.";
      }
      else {
        summary += ".";
      }
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), summary);
      C.divWarning.html(mRecord.Warning);
      C.divWarning.show();
      break;

    case "Differences":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Select differences to update on the " + mRecord.Caption);
      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
        switch (C.cboProduct.Text()) {
          case "Get Vehicle Data":
            if (C.txtPlate.Text().length == 0 &amp;&amp; C.txtVin.Text().length == 0) {
              Ok = false;
              widget.UI.MsgBoxAlert("VIN or Plate must be entered.");
              return;
            }
            break;
        }

        // There is no Options page so you need to Confirm on the General page
        // Confirm
        if (mEnquiryDetails &amp;&amp; mLastFinishParametersJson != JSON.stringify(CreateFinishParameters(true))) {
          // Parameters have changed so allow performing another Security Enquiry
          mEnquiryDetails = null;
        }

        // Confirm
        if (mEnquiryDetails) {
          validCallback();
        }
        else {
          var message = "Are you sure you want to perform a " + mRecord.ServiceName + " Security Enquiry?\n\n";
          if (mRecord.WorkflowPk) {
            message += "NOTE: The Workflow Item that this Security 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 {
            var Chargeable = true;
            switch (C.cboProduct.Text()) {
              case "Get Vehicle Data":
                Chargeable = mRecord.Chargeable;
                break;

              default:
                break;
            }
            if (Chargeable) {
              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 Security Enquiry" }, function() { PerformEnquiry(validCallback) });
        }
        return;

      case "Differences":
        // Differences
        if (C.cigDifferences.CountChecked() == 0) {
          Ok = false;
          widget.UI.MsgBoxAlert("You have not checked any details to update.");
        }
        break;

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

  // Perform Enquiry
  widget.GetString("PerformEnquiry", CreateFinishParameters(true), 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);

  // Differences
  mRecord_Differences = mEnquiryDetails.Data;
  if (mRecord_Differences != null) {
    C.cigDifferences.Refresh(mRecord_Differences, false, mRecord.Caption, "Enquiry Result");
  }

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

  // Callback
  successCallback();

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

  // Refresh / Update Parent (to show updated details)
  if (mRecord.EditJson) {
    if (mEnquiryDetails &amp;&amp; mEnquiryDetails.ServiceLogPk) widget.ParentNotify("SecurityEnquiryComplete", { ServiceLogPk: mEnquiryDetails.ServiceLogPk });    
  }
  else {
    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 "CLOSE":
      // Close
      tabWizard_Cancel();
      break;

    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

    case "HISTORY":
      // Show History page
      tabWizard_Refresh(0);
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to update the " + mRecord.Caption + "?",
                            { heading: "Update " + mRecord.Caption },
                            function () { Form_ExecuteAction_FinishPost();
    });
  });
}

function Form_ExecuteAction_FinishPost() {
  // Disable Form
  widget.UI.Block("Updating, please wait...");

  // Finish
  widget.GetString("UpdateDifferences", CreateFinishParameters(false),
    function (data) {
      data = JSON.parse(data);

      // Unblock
      widget.UI.Unblock();

      // Not really saving, just passing details back to parent form
      if (mRecord.EditJson) {
        // Notify parent (e.g., Security Statement Item Edit form) that a the Security Item has been updated
        // NOTE: This is essential if this wizard needs to be run from the Security Statement Item Edit form
        if (data &amp;&amp; data.UpdatedItemJson) widget.ParentNotify("RecordUpdated", data.UpdatedItemJson);

        // Close
        widget.Close();
        return;
      }

      if (data &amp;&amp; data.Warnings) {
        widget.UI.MsgBoxAlert("Updating " + mRecord.Caption + " completed but the following warnings were given:\n\n" + data.Warnings, {}, function () {
          // Close Form
          widget.Close();

          // Refresh Parent (to show updated status)
          widget.RefreshParent();
        })
      }
      else {
        // Close Form
        widget.Close();

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

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

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

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

  if (!excludeServiceParameters) {
    // Compare Items
    if (mRecord_Differences != null) {
      params.compareItemsJson = JSON.stringify(mRecord_Differences);
    }
    if (mEnquiryDetails != null) {
      params.securityEnquiryPerformed = mEnquiryDetails.SecurityEnquiryPerformed;
      params.serviceLogPk = mEnquiryDetails.ServiceLogPk;
    }
  }

  switch (C.cboProduct.Text()) {
    case "Get Vehicle Data":
      // Get Vehicle Data
      params.PlateNumber = C.txtPlate.Text();
      params.Vin = C.txtVin.Text();
      break;
  }

  return params;
}

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

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

// ===========
// gridHistory
// ===========
function gridHistory_Refresh() {
  // Add Columns
  C.gridHistory.ClearColumns();
  C.gridHistory.AddColumnDrilldown();
  C.gridHistory.AddColumnDateTime("CreatedDate", { caption: "Date"});
  C.gridHistory.AddColumnString("ServiceId", { caption: "Service Id"});
  C.gridHistory.AddColumnString("ProductClass", { caption: "Product Class"});
  C.gridHistory.AddColumnString("ProductId", { caption: "Product Id"});
  C.gridHistory.AddColumnString("ProductOptions", { caption: "Product Options"});
  C.gridHistory.AddColumnString("EnquiryReference", { caption: "Reference"});

  // Fetch data
  widget.GetString("GetHistory", {},
    function (data) {
      // Parse Data
      mRecord_History = JSON.parse(data);

      // Refresh Grid
      C.gridHistory.VirtualDataRefresh(mRecord_History);

      // Activate Last Row
      C.gridHistory.ActivateLastDataRow();
    },

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

function gridHistory_InitialiseRow(e) {
  var item = mRecord_History[e.row.listIndex];

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

function gridHistory_RowDrilldown(e) {
  var item = mRecord_History[e.row.listIndex];

  widget.ExecuteApplicationShortcutUrl("FormShow?form=ServiceLog&amp;Page=Security Enquiry&amp;id=" + item.Pk);
}

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

        // Security Enquiry
      }
    },

    // 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.lblSearchDetails.VisibleRow(false);
  C.txtPlate.VisibleRow(false);
  C.txtVin.VisibleRow(false);

  // Handle Response
  switch (C.cboProduct.Text()) {
    case "Get Vehicle Data":
      C.lblSearchDetails.VisibleRow(true);
      C.txtPlate.VisibleRow(true);
      C.txtVin.VisibleRow(true);

      if (mRecord) {
        C.txtPlate.ReadOnly(!mRecord.AdHocEnquiry &amp;&amp; !mRecord.EditJson);
        C.txtVin.ReadOnly(!mRecord.AdHocEnquiry &amp;&amp; !mRecord.EditJson);

        C.txtPlate.Text(mRecord.Plate);
        C.txtVin.Text(mRecord.Vin);
      }
      break;
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>YvglzU4Gw0yv3HnERSTNmQ</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon>Logo_PPSR_NZ</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="SecurityStmtId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>SecurityStmts</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="SecurityStmtItemPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="SecurityStmtItemJson" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Used by the New Account wizard to add and edit unsaved or "Quote" Standard Transactions.</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>
            <MaxLength>0</MaxLength>
            <Rows>4</Rows>
          </Parameter>
          <Parameter name="AccountAppId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>AccountApps</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="AccountAppCollateralItemPk" type="Number">
            <BlankTip />
            <Caption>Account App Collateral Item Pk</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="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>