<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-08-15T01:14:59.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-08-15T00:34:20.1260000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-08-15T01:00:51.2850000</UpdatedUtcDate>
    <ScriptId>HWMWCO</ScriptId>
    <Description>MotorWeb Confirm Owner</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_MotorWeb_ConfirmOwner
Option Explicit On
Option Strict On

' #################################################################
' MotorWeb Confirm Owner wizard
'
' (c) Copyright Intersoft Systems Limited 2024
'
' Version: 1.00 (15/08/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  15/08/2024  ISS      J028794   Created
' #################################################################

' Constants
Private Const FORM_KEY As String = "MotorWeb_ConfirmOwner"
Private Const SERVICE_ID As String = "MotorWeb"
Private Const SUPPORTED_PRODUCT_ID As String = "ConfirmOwner"

' Common Parameters
Private mServiceLogPk As Integer
Private mBranchId As String

' 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
    mBranchId = .GetString("BranchId")
    mServiceLogPk = .GetInteger("id")
  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 "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 "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;
'''  Get Branch Defaults.
''' &lt;/summary&gt;
Private Function GetBranchDefaults(ByRef returnValue As String) As Boolean

  Dim BranchId As String
  Dim CostCentreResolved_MotorWebNZ As finCostCentreResolved_MotorWebNZ
  Dim Data As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Cost Centre
  CostCentreResolved_MotorWebNZ = finBL.CostCentresResolved.ItemByBranchId(BranchId).MotorWebNZ

  ' Cost Centre Defeaults

  ' Create Response
  Data = New With {
    .BranchId = BranchId
  }

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

  Return Success

End Function

Private Function GetMotorWebDetails(ByRef motorWebReference As String,
                                    ByRef originalServiceLogPk As Integer,
                                    ByRef vehicleDescription As String) As Boolean

  Dim ServiceLogs As ISServiceLogs
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise ByRef
  originalServiceLogPk = 0
  motorWebReference = ""
  vehicleDescription = ""
  
  ' Load the Service Logs
  If Success Then
    Success = finBL.SecurityEnquiry.GetSecurityEnquiryServiceLogs(mServiceLogPk, ServiceLogs)
  End If
  
  ' Get the Reference
  If Success Then
    originalServiceLogPk = ServiceLogs(0).Pk
    Select Case ServiceLogs(0).ExResponse.GetType()
      Case GetType(ISSecurityEnquiryResponse_MotorWeb_AssetCheck)
        With DirectCast(ServiceLogs(0).ExResponse, ISSecurityEnquiryResponse_MotorWeb_AssetCheck)
          motorWebReference = .Reference
          vehicleDescription = finBL.Runtime.TextUtilities.ListSeparate(" ", .VirAnalysis.Vehicle.Make, .VirAnalysis.Vehicle.Model, If(Len(.VirAnalysis.Vehicle.Plates.GetCurrentPlateNumber) = 0, .VirAnalysis.Vehicle.Vin, .VirAnalysis.Vehicle.Plates.GetCurrentPlateNumber))
        End With

      Case Else
        ' Not Supported
        Success = False
        finBL.Error.ErrorBeginFormat("Unhandled Product '{0}'.", ServiceLogs(0).ProductId)
    End Select
  End If
  
  ' Return Success
  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 BranchId As String
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim MotorWebReference As String
  Dim OriginalServiceLogPk As Integer
  Dim Success As Boolean
  Dim VehicleDescription As String
  
  ' Assume Success
  Success = True

  ' Validate Parameters
  If mServiceLogPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Id or Service Log details not specified.")
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  End If
  
  ' Branch
  If Success Then
    If Len(mBranchId) &lt;&gt; 0 Then
      BranchId = mBranchId
    Else
      BranchId = finBL.CostCentreFunctions.GetDefaultBranchId()
    End If
  End If

  ' Get the MotorWeb Reference
  If Success Then
    Success = GetMotorWebDetails(MotorWebReference, OriginalServiceLogPk, VehicleDescription) 
  End If
    
  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()

    ' Other Properties
    With FormInitialisationInfo
      ' Record
      .ServiceLogPk = mServiceLogPk
      
      ' Branch
      .BranchId = BranchId

      .VehicleDescription = VehicleDescription
      
      ' Chargeable
      .ConfirmOwner_Chargeable = finBL.SecurityEnquiry.Service_MotorWeb.CreateRequest_ConfirmOwner(0).Chargeable

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get 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
  Dim RelatedServiceLog As ISServiceLog
  Dim RelatedServiceLogs As ISServiceLogs
	Dim SummaryTable As ISSummaryTable
	Dim SummaryTables As ISSummaryTables
  Dim Response As ISSecurityEnquiryResponse
  Dim Response_MotorWeb_ConfirmOwner As ISSecurityEnquiryResponse_MotorWeb_ConfirmOwner

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  Html =""
  
  ' Create the Summary table
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Confirm Owner",, 2)
  
  ' Get the related service logs
  If finBL.Database.GetServiceLogs(serviceLogPk, RelatedServiceLogs) Then
    For Each RelatedServiceLog In RelatedServiceLogs
      If RelatedServiceLog.Pk = serviceLogPk Then
        If finBl.SecurityEnquiry.GetSecurityEnquiryResponseFromServiceLog(RelatedServiceLog, Response) Then
          Select Case Response.GetType()
            Case GetType(ISSecurityEnquiryResponse_MotorWeb_ConfirmOwner)
              Response_MotorWeb_ConfirmOwner = DirectCast(Response, ISSecurityEnquiryResponse_MotorWeb_ConfirmOwner)
              
              SummaryTable.AddRowCaptionDateTime("Enquiry Date:", Response_MotorWeb_ConfirmOwner.EnquiryDate)
              summarytable.AddRowCaptionOutcome("Match:", Response_MotorWeb_ConfirmOwner.Match)
              SummaryTable.AddRowCaptionText("Driver Licence Number:", Response_MotorWeb_ConfirmOwner.Request.DriversLicenceNumber, False)
              SummaryTable.AddRowCaptionDate("Date Of Birth:", Response_MotorWeb_ConfirmOwner.Request.DateOfBirth, False)
              SummaryTable.AddRowCaptionText("Last Name:", Response_MotorWeb_ConfirmOwner.Request.LastName, False)
              SummaryTable.AddRowCaptionText("First Name:", Response_MotorWeb_ConfirmOwner.Request.FirstName, False)
              
              SummaryTables.Add("ConfirmOwner", SummaryTable)
          End Select
        End If
        Exit For
      End If
    Next
  End If

  ' Get the HTML
  Html = finBL.Utilities.GetHtmlFromSummaryTables(SummaryTables, "MotorWeb Confirm Owner Report")

  ' Return Html
  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 Data As Object
  Dim ExecutePostFailed As Boolean
  Dim Html As String
  Dim MotorWebReference As String
  Dim obj As Object
  Dim OriginalServiceLogPk As Integer
  Dim SecurityEnquiryPerformed As Boolean
  Dim SecurityEnquiryRequest As ISSecurityEnquiryRequest
  Dim SecurityEnquiryResponse As ISSecurityEnquiryResponse
  Dim ServiceLog As ISServiceLog
  Dim ServiceLogCreateDetails As ISServiceLogCreateDetails
  Dim ServiceLogPk As Integer
  Dim Success As Boolean
  Dim VehicleDescription As String
  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 the MotorWeb Reference
  If Success Then
    Success = GetMotorWebDetails(MotorWebReference, OriginalServiceLogPk, VehicleDescription) 
  End If
  
  ' Create Enquiry
  If Success Then
    SecurityEnquiryRequest = finBL.SecurityEnquiry.CreateSecurityEnquiryRequest(SERVICE_ID, SUPPORTED_PRODUCT_ID, WizardFinishParameters.BranchId)
    If SecurityEnquiryRequest Is Nothing Then
      Success = False
    End If
  End If

  ' Options
  If Success Then
    Select Case SecurityEnquiryRequest.GetType()
      Case GetType(ISSecurityEnquiryRequest_MotorWeb_ConfirmOwner)
        ' -------------
        ' Confirm Owner
        ' -------------
        With DirectCast(SecurityEnquiryRequest, ISSecurityEnquiryRequest_MotorWeb_ConfirmOwner)
          .Reference = MotorWebReference
          Select Case WizardFinishParameters.ConfirmOwner_Type
            Case "FirstAndLastName"
              .ConfirmType = iseMotorWebConfirmOwnerConfirmMethod.FirstAndLastName
            Case "LastNameAndDateOfBirth"
              .ConfirmType = iseMotorWebConfirmOwnerConfirmMethod.LastNameAndDateOfBirth
            Case "DriversLicence"
            .ConfirmType = iseMotorWebConfirmOwnerConfirmMethod.DriversLicence    
          End Select
          .DateOfBirth = WizardFinishParameters.ConfirmOwner_DateOfBirth
          .DriversLicenceNumber = WizardFinishParameters.ConfirmOwner_DriversLicence
          .FirstName = WizardFinishParameters.ConfirmOwner_FirstName
          .LastName = WizardFinishParameters.ConfirmOwner_Surname
        End With

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

  ' Execute
  If Success Then
    ' Set the parent
    ServiceLogCreateDetails = New ISServiceLogCreateDetails()
    ServiceLogCreateDetails.ParentServiceLogPk = OriginalServiceLogPk

    If finBL.SecurityEnquiry.ExecuteSecurityEnquiry(SecurityEnquiryRequest, SecurityEnquiryResponse, , ServiceLogCreateDetails, ExecutePostFailed, ) 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
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(Data, Html, ServiceLogPk, OriginalServiceLogPk, Warning), 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
        End If
      End If
    End If

  End Sub

End Class



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

  ' Record
  Public ServiceLogPk As Integer
  Public BranchId As String

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

  ' Chargeable
  Public ConfirmOwner_Chargeable As Boolean

  ' Configuration
  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

  ' Confirm Owner
  Public ConfirmOwner_Type As String
  Public ConfirmOwner_DateOfBirth As Date
  Public ConfirmOwner_DriversLicence As String
  Public ConfirmOwner_FirstName As String
  Public ConfirmOwner_PlateNumber As String
  Public ConfirmOwner_Surname As String
  Public ConfirmOwner_Vin As String

End Class


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

  ' General
  Public Data As Object
  Public Html As String
  Public ServiceLogPk As Integer
  Public OriginalServiceLogPk As Integer
  Public Warning As String

  Public Sub New(data As Object,
                 html As String,
                 serviceLogPk As Integer,
                 originalServiceLogPk As Integer,
                 warning As String)

    With Me
    .Data = data
    .Html = html
    .ServiceLogPk = serviceLogPk
    .OriginalServiceLogPk = originalServiceLogPk
    .Warning = warning
  End With

  End Sub

End Class
</Code>
    <Language>VisualBasic</Language>
    <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="Enter Confirm Owner details."&gt;MotorWeb Confirm Owner Enquiry&lt;/li&gt;
        &lt;li tabId="Enquiry" tooltipText="Confirm Owner results."&gt;MotorWeb Confirm Owner Result&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

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

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblDetails"&gt;Confirm Owner details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="divConfirmOwner_Vehicle"&gt;Vehicle:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;div id="divConfirmOwner_Vehicle" class="is-info-text info large" style="display:none"&gt;&lt;/div&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;!-- Confirm Owner --&gt;
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblConfirmOwner_Options"&gt;Select a confirmation method and enter details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="rblConfirmOwner"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datConfirmOwner_DateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datConfirmOwner_DateOfBirth" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtConfirmOwner_FirstName"&gt;First Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtConfirmOwner_FirstName" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtConfirmOwner_Surname"&gt;Surname:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtConfirmOwner_Surname" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtConfirmOwner_DriversLicenceNumber"&gt;Licence No:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtConfirmOwner_DriversLicenceNumber" /&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_BranchDefaults;
var mEnquiryDetails;

// Controls
var C = {
  // Details
  lblDetails: null,
  divConfirmOwner_Vehicle: null,  

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

  // Confirm Owner
  lblConfirmOwner_Options: null,
  rblConfirmOwner: null,
  datConfirmOwner_DateOfBirth: null,
  txtConfirmOwner_FirstName: null,
  txtConfirmOwner_Surname: null,
  txtConfirmOwner_DriversLicenceNumber: null,

  // Enquiry
  wbSummary: null,

  // Differences
  cigDifferences: null,
}

// Form
var frmMain;
var tabWizard;

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

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

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

  // --------
  // Controls
  // --------
  // Details
  C.lblDetails = widget.UI.Label("lblDetails", {});
  C.divConfirmOwner_Vehicle = $("#divConfirmOwner_Vehicle");
  
  //   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");

  //   Confirm Owner
  //C.lblConfirmOwner_Vehicle = widget.UI.Label("lblConfirmOwner_Vehicle", {});
  C.lblConfirmOwner_Options = widget.UI.Label("lblConfirmOwner_Options", {});
  C.rblConfirmOwner = widget.UI.RadioButtonList("rblConfirmOwner", {
    allowBlank: false,

    onChange: rblConfirmOwner_Change,
  });
  C.datConfirmOwner_DateOfBirth = widget.UI.DateBox("datConfirmOwner_DateOfBirth", {
    allowBlank: false,
    historic: true,
    showAge: true,
  });
  C.txtConfirmOwner_FirstName = widget.UI.TextBox("txtConfirmOwner_FirstName", {
    allowBlank: false,
    maxLength: 100,
  });
  C.txtConfirmOwner_Surname = widget.UI.TextBox("txtConfirmOwner_Surname", {
    allowBlank: false,
    maxLength: 50,
  });
  C.txtConfirmOwner_DriversLicenceNumber = widget.UI.TextBox("txtConfirmOwner_DriversLicenceNumber", {
    allowBlank: false,
    maxLength: 50,
  });

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

  // 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;
  mEnquiryDetails = 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) {
    // Details
    //C.lblConfirmOwner_Vehicle.Text(mRecord.VehicleDescription);
    C.divConfirmOwner_Vehicle.html("&lt;b&gt;" + mRecord.VehicleDescription + "&lt;/b&gt;");
    C.divConfirmOwner_Vehicle.show();
    
    // General
    C.cboBranch.Text(mRecord.BranchId);
    
    var list = [];
    list.push({ caption: "First and Last Name", value: "FirstAndLastName" });
    list.push({ caption: "Date of Birth and Last Name", value: "LastNameAndDateOfBirth" });
    list.push({ caption: "Drivers Licence Number", value: "DriversLicence" });
    C.rblConfirmOwner.ListFromArray(list);
    C.rblConfirmOwner.Value("FirstAndLastName");
    rblConfirmOwner_Change();
  }

  // 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("MotorWeb Confirm Owner Enquiry (Test Mode)");
  }

  // Information Lists

  // Lists
  if (mRecord) {
    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();
  }

  // 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() {
  if (mEnquiryDetails) {
    if (mEnquiryDetails.ServiceLogPk != 0) {
      widget.RefreshParent();
    }
  }
  widget.Close();
}

function tabWizard_UpdateButtons() {
  // Back and Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();
    if(!mEnquiryDetails) {
      cmdBack.prop("disabled", tabIndex &lt;= 0);
    } else {
    // Can't go backwards if the Create has already run
    cmdBack.prop("disabled", true);
    }
    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":
      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()) {
    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

        // 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 MotorWeb Confirm Owner Enquiry?\n\n";
          if (mRecord.TestMode) {
            message += "NOTE: You are in 'Test Mode' so no cost will be incurred.";
          }
          else {
            if (mRecord.ConfirmOwner_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 MotorWeb Confirm Owner 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(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);

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

  // Callback
  successCallback();

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

  // Refresh / Update Parent (to show updated details)
  //widget.RefreshParent();
  //widget.ParentNotify("ServiceLog.Refresh", { serviceLogPk: mEnquiryDetails.OriginalServiceLogPk });
  
  // Notify Log form
  widget.ActionNotificationSend("ServiceLog.Refresh", { serviceLogPk: mEnquiryDetails.OriginalServiceLogPk }, null, true);
  widget.ExecuteApplicationShortcutUrl("app://global?type=ServiceLog.Refresh&amp;ServiceLogPk=" + mEnquiryDetails.OriginalServiceLogPk)
}

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;

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

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

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

  if (!excludeServiceParameters) {
    if (mEnquiryDetails != null) {
      params.securityEnquiryPerformed = mEnquiryDetails.SecurityEnquiryPerformed;
      params.serviceLogPk = mEnquiryDetails.ServiceLogPk;
    }
  }

  // Confirm Owner
  params.ConfirmOwner_Type = C.rblConfirmOwner.Value();
  switch (C.rblConfirmOwner.Value()) {
    case "FirstAndLastName":
      params.ConfirmOwner_FirstName = C.txtConfirmOwner_FirstName.Text();
      params.ConfirmOwner_Surname = C.txtConfirmOwner_Surname.Text();
      break;

    case "LastNameAndDateOfBirth":
      params.ConfirmOwner_DateOfBirth = C.datConfirmOwner_DateOfBirth.Value();
      params.ConfirmOwner_Surname = C.txtConfirmOwner_Surname.Text();
      break;

    case "DriversLicence":
      params.ConfirmOwner_DriversLicence = C.txtConfirmOwner_DriversLicenceNumber.Text();
      break;
  }

  return params;
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    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);
    }
  );
}

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

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

// ===============
// rblConfirmOwner
// ===============
function rblConfirmOwner_Change(sender, e) {
  // Reset
  C.datConfirmOwner_DateOfBirth.VisibleRow(false);
  C.txtConfirmOwner_FirstName.VisibleRow(false);
  C.txtConfirmOwner_Surname.VisibleRow(false);
  C.txtConfirmOwner_DriversLicenceNumber.VisibleRow(false);

  // Show Controls
  var confirmOwnerType = C.rblConfirmOwner.Value();
  switch (confirmOwnerType) {
    case "FirstAndLastName":
      C.txtConfirmOwner_FirstName.VisibleRow(true);
      C.txtConfirmOwner_Surname.VisibleRow(true);
      break;

    case "LastNameAndDateOfBirth":
      C.datConfirmOwner_DateOfBirth.VisibleRow(true);
      C.txtConfirmOwner_Surname.VisibleRow(true);
      break;

    case "DriversLicence":
      C.txtConfirmOwner_DriversLicenceNumber.VisibleRow(true);
      break;

    default:
      window.alert("Confirm Owner Type '" + confirmOwnerType + "' not handled.");
      break;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>0</TimeoutSeconds>
    <UniqueId>EMiVVmKSm0COsl-ap-k47A</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_MotorWeb</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 />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </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="Id" 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>