<?xml version="1.0" encoding="utf-8"?><finPOWERConnect version="1.00" exportedUtcDate="2022-09-19T04:25:36.0000000" parameters="Account Application Types: ACCAPPHW&#xD;&#xA;Scripts: ACCAPPHW&#xD;&#xA;"><AccountAppTypes><finAccountAppType version="1.00" exportedUtcDate="2022-09-19T04:25:36.0000000">
  <CreatedUserId>ADMIN</CreatedUserId>
  <CreatedUtcDate>2017-09-11T04:28:58.8700000</CreatedUtcDate>
  <UpdatedUserId>ADMIN</UpdatedUserId>
  <UpdatedUtcDate>2022-09-19T04:18:22.4600000</UpdatedUtcDate>
  <AcceptAllowCreateOpen>true</AcceptAllowCreateOpen>
  <AcceptAllowCreateQuote>false</AcceptAllowCreateQuote>
  <AcceptDeclineCreateClientsWhenNotAccepted>false</AcceptDeclineCreateClientsWhenNotAccepted>
  <AcceptDeclineUpdateExistingClientsWhenNotAccepted>false</AcceptDeclineUpdateExistingClientsWhenNotAccepted>
  <AcceptDefaultQuote>false</AcceptDefaultQuote>
  <AcceptedWorkflowTypeId />
  <AccountAppTypeId>ACCAPPHW</AccountAppTypeId>
  <Active>true</Active>
  <AddressPhysicalContactMethodId pk="1">AD</AddressPhysicalContactMethodId>
  <AddressPostalContactMethodId pk="1">AD</AddressPostalContactMethodId>
  <AllowAdditionalApplicants>true</AllowAdditionalApplicants>
  <AllowAdditionalCollateral>true</AllowAdditionalCollateral>
  <AllowEditKeyLockedApplicants>true</AllowEditKeyLockedApplicants>
  <AllowMultipleQuotes>true</AllowMultipleQuotes>
  <AutoCalculateFinancial>true</AutoCalculateFinancial>
  <ClientContactUpdateMethod>CreateNew</ClientContactUpdateMethod>
  <ClientEmploymentUpdateMethod>CreateNew</ClientEmploymentUpdateMethod>
  <ClientIdentificationUpdateMethod>CreateNew</ClientIdentificationUpdateMethod>
  <Code>Option Explicit On
Option Strict On

' #################################################################
' Sample single page Loan Application supporting multiple Quotes.
'
' Version: 1.01 (14/09/2017)
'
' Usage: For use with HTML Widget ACCAPP.HW
' #################################################################

'#Const "PreferredLoanAmount",Currency,1500,"Preferred Loan Amount."
'#Const "PreferredNumberOfPayments",Integer,"12","Preferred Number of Payments."
'#Const "PreferredPaymentFrequency",String,"Monthly","Preferred Payment Frequency."

' Constants
Private PreferredLoanAmount As Decimal = 1500
Private PreferredNumberOfPayments As Integer = 12
Private PreferredPaymentFrequency As String = "Monthly"

Public Overrides Sub Initialise()

  ' Get Constants
  PreferredLoanAmount = ScriptInfo.Constants.GetCurrency("PreferredLoanAmount", PreferredLoanAmount)
  PreferredNumberOfPayments = ScriptInfo.Constants.GetInteger("PreferredNumberOfPayments", PreferredNumberOfPayments)
  PreferredPaymentFrequency = ScriptInfo.Constants.GetString("PreferredPaymentFrequency", PreferredPaymentFrequency)

End Sub

Public Overrides Function InitialiseAccountApp(accountApp As finAccountApp) As Boolean

  ' Assume Success
  InitialiseAccountApp = True

  ' Set Defaults or return False to fail initialisation
  With accountApp
    .PreferredLoanAmount = PreferredLoanAmount
    .PreferredNumberOfPayments = PreferredNumberOfPayments
    .PreferredPaymentFrequency = PreferredPaymentFrequency
  End With

  ' Add a default Applicant
  With accountApp.Applicants.AddApplicant("MAIN", True, True)
    ' Since we may only allow entry of a single address, ensure that it is flagged as Physical as well as Postal
    .AddressPhysicalIsPostal = True
  End With

  ' Add a default Collateral
  accountApp.CollateralItems.AddCollateralItem("MV1", True, False, "MV")
  accountApp.CollateralItems.AddCollateralItem("MV2", True, False, "MV")
  With accountApp.CollateralItems.AddCollateralItem("MVTradeIn1", True, False, "MV")
    .TradeIn = True
  End With

End Function

Public Overrides Function UpdateAccountCalc(accountApp As finAccountApp, accountAppCalculation As finAccountAppCalculation, accountCalc As finAccountCalc, defaultFromAccountApp As Boolean) As Boolean

  ' Call Base Method to update the Account Calculation
  UpdateAccountCalc = MyBase.UpdateAccountCalc(accountApp, accountAppCalculation, accountCalc, defaultFromAccountApp)

  ' Update properties from Account Application, e.g., if first Calculation (item zero) then update PreferredLoanAmount etc from Account's Calculation
  ' NOTE: This is not strictly necessary but it keeps things intuitive
  If accountAppCalculation.Index = 0 Then
    With accountCalc
      .StandardTransactions(0).ValueCurrency = accountApp.PreferredLoanAmount
      .PaymentCycle = accountApp.PreferredPaymentFrequency
      .TermNumberOfPayments = accountApp.PreferredNumberOfPayments
    End With
  End If

End Function

Public Overrides Function AfterCalculationUpdateFromAccount(accountApp As finAccountApp, accountAppCalculation As finAccountAppCalculation, account As finAccount) As Boolean

  ' Assume Success
  AfterCalculationUpdateFromAccount = True

  ' Update properties on Account Application, e.g., if first Calculation (item zero) then update PreferredLoanAmount etc from Account's Calculation
  ' NOTE: This is not strictly necessary but it keeps things intuitive
  If accountAppCalculation.Index = 0 Then
    With account.Calculation
      accountApp.PreferredAccountTypeId = .AccountTypeId
      accountApp.PreferredLoanAmount = .StandardTransactions(0).ValueCurrency
      accountApp.PreferredPaymentFrequency = .PaymentCycleDescription
      accountApp.PreferredNumberOfPayments = .TermNumberOfPayments
    End With
  End If

End Function

Public Overrides Sub ValidateAccount(accountApp As finAccountApp, accountAppCalculation As finAccountAppCalculation, account As finAccount, ByRef warningSeverity As isefinAccountWarningSeverity, ByRef warningMessage As String)

  ' Call Base Method
  MyBase.ValidateAccount(accountApp, accountAppCalculation, account, warningSeverity, warningMessage)

  ' Warn if Quote values do not match the Preferred Values in the wizard (perfectly valid with multiple Quotes but its nice to give a warning)
  If Len(warningMessage) = 0 Then
    With account.Calculation
      If account.Calculation.StandardTransactions.Count &lt;&gt; 0 AndAlso accountApp.PreferredLoanAmount &lt;&gt; account.Calculation.StandardTransactions(0).ValueCurrency Then
        warningSeverity = isefinAccountWarningSeverity.Alert
        warningMessage = String.Format("WARNING: Preferred Loan Amount ({0}) does not match the amount on this Quote ({1}).", finBL.FormatCurrency(accountApp.PreferredLoanAmount, True), finBL.FormatCurrency(account.Calculation.StandardTransactions(0).ValueCurrency, True))
      End If
    End With
  End If

End Sub

Public Overrides Function UpdateClientFromApplicant(accountAppApplicant As finAccountAppApplicant, client As finClient) As Boolean

  Dim IdentificationDetails As finIdentificationDetails
  Dim ClientIdentificationItem As finClientIdentificationItem
  Dim Identification_DL As String

  ' Call Base Method to update the Client (may return an existing Client record but with properties updated)
  UpdateClientFromApplicant = MyBase.UpdateClientFromApplicant(accountAppApplicant, client)

  ' Add Identification Items
  Identification_DL = accountAppApplicant.UserData.GetString("Identification_DL")

  If Len(Identification_DL) &lt;&gt; 0 Then
    ' Parse
    IdentificationDetails = finBL.CreateIdentificationDetails()
    IdentificationDetails.FromXmlString(Identification_DL)

    ' Create Client Identification Item
    ClientIdentificationItem = client.IdentificationItems.CreateClientIdentificationItem()
    IdentificationDetails.UpdateClientIdentificationItem(ClientIdentificationItem)
    With ClientIdentificationItem
      ' Image File?
      ' NOTE: This will be copied across when the Client is saved. Do not specify file extension when checking for file existing
      If accountAppApplicant.AccountApp.DocumentFiles.FileExists("MAIN_DL", "") Then
        .DocumentFileName = "MAIN_DL.png"
      End If
    End With
    If ClientIdentificationItem.IdentificationTypePk &lt;&gt; 0 Then
      client.IdentificationItems.Insert(0, ClientIdentificationItem)
    End If
  End If

End Function

Public Overrides Function UpdateClientAfterSave(accountAppApplicant As finAccountAppApplicant, client As finClient) As Boolean

  Dim DocumentFile As finDocumentFile

  ' Assume Success
  UpdateClientAfterSave = True

  ' Copy Identification Files
  If accountAppApplicant.AccountApp.DocumentFiles.FileExists("MAIN_DL", "") Then
    For Each DocumentFile In accountAppApplicant.AccountApp.DocumentFiles
      If Not client.DocumentFiles.CopyFromDocumentFile(DocumentFile) Then
        ' Ignore errors
      End If
    Next
  End If

End Function</Code>
  <CompletedWorkflowTypeId />
  <CreatedWorkflowTypeId />
  <DataCaptureMethod>HtmlWidget</DataCaptureMethod>
  <DataEntryApplicantHtmlWidgetScriptId />
  <DataEntryCollateralHtmlWidgetScriptId />
  <DataEntryCreationHtmlWidgetScriptId />
  <DataEntryGeneralHtmlWidgetScriptId pk="45">ACCAPPHW</DataEntryGeneralHtmlWidgetScriptId>
  <DataEntryQuoteHtmlWidgetScriptId />
  <DataEntryReviewingAllowEdit>true</DataEntryReviewingAllowEdit>
  <DataEntryReviewingHtmlWidgetScriptId pk="45">ACCAPPHW</DataEntryReviewingHtmlWidgetScriptId>
  <DataEntryReviewingPageSetId />
  <DataEntryReviewingPageSetForceTabbedView>true</DataEntryReviewingPageSetForceTabbedView>
  <DefaultAccountRoleId pk="1">B</DefaultAccountRoleId>
  <DefaultAccountTypeId pk="1">CC</DefaultAccountTypeId>
  <DefaultClientGroupId pk="1">G</DefaultClientGroupId>
  <DefaultClientTypeId pk="1">I</DefaultClientTypeId>
  <Description>Sample Loan Application</Description>
  <DetailViewMethod>Default</DetailViewMethod>
  <DetailViewSummaryScriptId />
  <EmailContactMethodId pk="7">EMAIL</EmailContactMethodId>
  <FacsimileContactMethodId pk="5">FAX</FacsimileContactMethodId>
  <Icon>Applicant</Icon>
  <Language>VisualBasic</Language>
  <MenuCaption>New Sample Loan Application</MenuCaption>
  <MobileContactMethodId pk="4">MOB</MobileContactMethodId>
  <NextAccountAppId />
  <Notes>Account Application Type for sample HTML Widget to allow entry of a new or existing Account Application.</Notes>
  <PermissionKeyUse />
  <PhoneContactMethodId pk="2">PH</PhoneContactMethodId>
  <PhoneWorkContactMethodId pk="3">PW</PhoneWorkContactMethodId>
  <ReviewingWorkflowTypeId />
  <RunAsAdministrator>true</RunAsAdministrator>
  <ShowFromAddButton>true</ShowFromAddButton>
  <ShowInMenu>true</ShowInMenu>
  <SummaryPageScriptId />
  <SummaryPageShowHubEntry>false</SummaryPageShowHubEntry>
  <TimeoutSeconds>0</TimeoutSeconds>
  <ValidateDataSchemaAccess>true</ValidateDataSchemaAccess>
  <Version>1</Version>
  <Constants>
    <ISScriptConstants version="1.00">
      <ScriptConstant name="PreferredLoanAmount" constantType="Currency">
        <Notes>Preferred Loan Amount.</Notes>
        <Value>1500</Value>
      </ScriptConstant>
      <ScriptConstant name="PreferredNumberOfPayments" constantType="Integer">
        <Notes>Preferred Number of Payments.</Notes>
        <Value>12</Value>
      </ScriptConstant>
      <ScriptConstant name="PreferredPaymentFrequency" constantType="String">
        <Notes>Preferred Payment Frequency.</Notes>
        <Value>Monthly</Value>
        <Encrypt>false</Encrypt>
      </ScriptConstant>
    </ISScriptConstants>
  </Constants>
  <DataSchema>
    <finDataSchema version="1.00" exportedUtcDate="2022-09-19T04:25:36.0000000">
      <Tables>
        <Table>
          <TableId>Application</TableId>
          <Description>finAccountApp</Description>
          <Fields>
            <Field>
              <FieldId>EligibilityOver18</FieldId>
              <FieldType>Boolean</FieldType>
              <Description />
              <ReadOnly>false</ReadOnly>
            </Field>
            <Field>
              <FieldId>EligibilityResident</FieldId>
              <FieldType>Boolean</FieldType>
              <Description />
              <ReadOnly>false</ReadOnly>
            </Field>
            <Field>
              <FieldId>EligibilityCreditCheck</FieldId>
              <FieldType>Boolean</FieldType>
              <Description />
              <ReadOnly>false</ReadOnly>
            </Field>
            <Field>
              <FieldId>EligibilityTermsConditions</FieldId>
              <FieldType>Boolean</FieldType>
              <Description />
              <ReadOnly>false</ReadOnly>
            </Field>
          </Fields>
        </Table>
        <Table>
          <TableId>Applicant</TableId>
          <Description>finAccountAppApplicant</Description>
          <Fields>
            <Field>
              <FieldId>Identification_DL</FieldId>
              <FieldType>String</FieldType>
              <Description>Drivers Licence details.</Description>
              <ReadOnly>false</ReadOnly>
              <MaxLength>0</MaxLength>
            </Field>
          </Fields>
        </Table>
        <Table>
          <TableId>Collateral</TableId>
          <Description>finAccountAppCollateralItem</Description>
          <Fields />
        </Table>
      </Tables>
    </finDataSchema>
  </DataSchema>
  <Documents>AAL</Documents>
</finAccountAppType></AccountAppTypes><Scripts><finScript version="1.00" exportedUtcDate="2022-09-19T04:25:36.0000000">
  <CreatedUserId>ADMIN</CreatedUserId>
  <CreatedUtcDate>2017-09-11T04:28:58.7730000</CreatedUtcDate>
  <UpdatedUserId>ADMIN</UpdatedUserId>
  <UpdatedUtcDate>2022-09-19T04:24:03.0270000</UpdatedUtcDate>
  <ScriptId>ACCAPPHW</ScriptId>
  <Description>Sample Account Application</Description>
  <ScriptType>HtmlWidget</ScriptType>
  <Active>true</Active>
  <AllowUI>false</AllowUI>
  <Category />
  <Code>Option Explicit On
Option Strict On

' #################################################################
' Sample Account Application HTML Widget
'
' Version: 1.07 (19/09/2022)
'
' Usage: For sample purposes only
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.06  24/09/2020  ISS                Updated
'    1.07  10/08/2022  ISS      J029212   Fixed Compile Errors
'          19/09/2022  ISS      J029525   Updated Gender List
' #################################################################

' Constants
Private MAX_IMAGE_WIDTH As Integer = 1024

' Objects
Private mCombinedParameters As ISKeyValueList
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList

' Standard Parameters
Private mAccountAppPk As Integer
Private mAccountAppTypeId As String
Private mOcrImageMaxWidth As Integer
Private mReadOnly As Boolean

' Other
Private mDriversLicenceDefinedSettings As Boolean

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 Configuration options
  mDriversLicenceDefinedSettings = (finBL.Settings.DriversLicenceIdentificationTypePk &gt; 0)

  ' Get Other
  With mCombinedParameters
    mAccountAppPk = .GetInteger("AccountAppPk")
    mAccountAppTypeId = .GetString("AccountAppTypeId")
    If Len(mAccountAppTypeId) = 0 Then mAccountAppTypeId = ScriptInfo.ScriptId ' Useful for testing
    mOcrImageMaxWidth = .GetInteger("OcrImageMaxWidth")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

  ' Override
  If mOcrImageMaxWidth &lt;= 0 Then
    mOcrImageMaxWidth = 4096
  End If

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

    Case "ClientPreload"
      ' Get Client Preload details
      Main = ClientPreload(parametersJson, returnValue)

    Case "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, requestInfo, returnValue)

    Case "GetAccountSummary"
      ' Get Account Summary
      GetAccountSummary(parametersJson, returnValue)

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

    Case "ScanImage"
      ' Scan Drivers Licence or Passport Image
      Main = ScanImage(requestInfo, returnValue)

    Case "WizardValidate"
      ' Validate wizard page
      Main = WizardValidate(parametersJson, returnValue)

    Case Else
      Main = False
      finBL.Error.ErrorBeginFormat("Event '{0}' not handled.", eventId)
  End Select

End Function

Private Function GetPage() As String

  Dim Html As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If Success Then
    If mAccountAppPk = 0 AndAlso Len(mAccountAppTypeId) = 0 Then
      Success = False
      Html = finBL.GetHtmlErrorMessage("Widget must be passed an 'AccountAppPk' or 'AccountAppTypeId' parameter or be configured to define an 'AccountAppTypeId' parameter for testing purposes.")
    End If
  End If

  If Success Then
    ' Initialise
    Html = ScriptInfo.TemplateText
  ElseIf Len(Html) = 0 Then
    Html = finBL.GetHtmlErrorMessage(finBL.Error.Message(True))
  End If

  Return Html

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 Account As finAccount
  Dim AccountAppDetails As AccountAppDetails
  Dim CodeDescriptionList As ISCodeDescriptionList
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim IdentificationTypeRO As finIdentificationTypeRO
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If mAccountAppPk &lt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("Invalid Account App Pk.")
  ElseIf Len(mAccountAppTypeId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account App Type Id not specified.")
  ElseIf Not finBL.AccountAppTypes.Exists(mAccountAppTypeId) Then
    Success = False
    finBL.Error.ErrorBegin("Invalid Account App Type.")
  End If

  ' Get Account Application Details
  If Success Then
    Success = GetAccountAppDetails(mAccountAppPk, mAccountAppTypeId, AccountAppDetails)
  End If

  ' Create Account (required to get Account Type Lists)
  If Success Then
    Success = AccountAppDetails.AccountApp.CreateAccount(Account)
  End If

  ' Get Initialisation Info
  If Success Then
    ' Initialise
    CodeDescriptionList = finBL.Runtime.CreateCodeDescriptionList()
    FormInitialisationInfo = New FormInitialisationInfo()

    ' Retrieve Global Settings Identification Type
    If mDriversLicenceDefinedSettings Then
      IdentificationTypeRO = finBL.IdentificationTypes(finBL.Settings.DriversLicenceIdentificationTypeId)
    End If

    ' Initialisation Info
    With FormInitialisationInfo
      ' Record
      .ReadOnly = mReadOnly

      ' Account Application
      .AccountAppDetails = AccountAppDetails

      ' Permissions

      ' Lists
      .List_Genders = finBL.Enums.isefinGender_GetList().ToCsvString()
      .List_Purposes = finBL.InformationLists("AccountPurpose").List
      If Account.AccountType IsNot Nothing Then
        .List_Payments = Account.AccountType.PaymentCycleListResolved
      End If
      .List_LicenceSpecialTypes = finBL.Enums.isefinIdentificationTypeSpecialType_GetList_DriversLicence(True).ToCsvString()

      ' AU States List
      If IdentificationTypeRO Is Nothing OrElse IdentificationTypeRO.SpecialType = isefinIdentificationTypeSpecialType.AU_DriversLicence Then
        If CodeDescriptionList.FromDataTable(finBL.Addressing.GetStatesDataTable("AU")) Then
          .List_States_AU = CodeDescriptionList.ToJsonObject()
        Else
          Success = False
        End If
      End If

      ' US States List
      If Success Then
        If IdentificationTypeRO Is Nothing OrElse IdentificationTypeRO.SpecialType = isefinIdentificationTypeSpecialType.US_DriversLicence Then
          If CodeDescriptionList.FromDataTable(finBL.Addressing.GetStatesDataTable("US")) Then
            .List_States_US = CodeDescriptionList.ToJsonObject()
          Else
            Success = False
          End If
        End If
      End If

      ' Settings
      If Success Then
        .DefaultCountry = finBL.CurrentCountry.CountryName
        .DriversLicenceSpecialTypeAllowUpdate = (Not mDriversLicenceDefinedSettings)
        .PostalValidation = finBL.Settings.AddOns.AddressFullVerification AndAlso finBL.Addressing.AddressInterfaceAvailable

        ' Configuration Options
        .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      End If
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., add a new or update an existing Account Application.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim AccountAppDetails As AccountAppDetails
  Dim AccountAppDetailsTemp As AccountAppDetails
  Dim AccountApp As finAccountApp
  Dim FileUploadInfo As finFileUploadInfo
  Dim ImageError As String
  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get/ Create Account Application
  If Success Then
    If GetAccountAppDetails(mAccountAppPk, mAccountAppTypeId, AccountAppDetailsTemp) Then
      AccountApp = AccountAppDetailsTemp.AccountApp
    Else
      Success = False
    End If
  End If

  ' Validate Timestamp
  If Success AndAlso Not AccountApp.IsNew Then
    If AccountAppDetails.Timestamp &lt;&gt; AccountApp.Timestamp Then
      Success = False
      finBL.Error.ErrorBegin("This record has been edited by another User.")
    End If
  End If

  ' Update Account Application
  If Success Then
    Success = UpdateAccountAppFromAccountAppDetails(AccountApp, AccountAppDetails)
  End If

  ' Save
  If Success Then
    Success = AccountApp.Save()
  End If

  ' Save Images to Document Manager
  ' NOTE: Must be done after the Account Application is saved since the Document Manager is not available for an unsaved record
  If Success AndAlso finBL.DocumentManager.IsAvailable AndAlso requestInfo.Files.Count &lt;&gt; 0 Then
    ' Client Image
    If Success Then
      FileUploadInfo = requestInfo.GetFileByTag("ClientImage")

      If FileUploadInfo Is Nothing Then
        ' No Image found
      Else If Not AccountApp.Applicants.ItemByKey("MAIN").ImageFileAdd(FileUploadInfo.FileData, "", MAX_IMAGE_WIDTH, True) Then
        ImageError = finBL.Error.Message(True)
      End If
    End If

    ' Identification Image
    If Success Then
      FileUploadInfo = requestInfo.GetFileByTag("IdImage_DL")

      If FileUploadInfo Is Nothing Then
        ' No Image found
      Else If AccountApp.DocumentFiles.AddImage(FileUploadInfo.FileData, "", MAX_IMAGE_WIDTH, True, "MAIN_DL.png") Then
        ' No need to update Drivers Licence information to link to Image file, a fixed file name is used in the Account Application Type Script
      Else
        ImageError = finBL.Error.Message(True)
      End If
    End If

    ' Re-save Application to account for uploaded Images (ignore errors)
    AccountApp.Save()
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(AccountApp.AccountAppId, ImageError), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim Client As finClient
  Dim ClientId As String
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    ClientId = .GetString("ClientId")
    PageId = .GetString("PageId")
  End With

  ' Validate Page
  Select Case PageId
    Case "Client"
      Client = finBL.CreateClient()

      ' Validate selected Client
      If Client.Load(ClientId) Then
        If Not Client.IsIndividualOrSoleTrader Then
          FailedControlId = "cboClient"
          FailedMessage = "Only Individual or Sole Trader Clients can be specified for this Application Type."
        End If
      Else
        Success = False
      End If
  End Select

  ' Finalise
  If Success AndAlso Len(FailedMessage) &lt;&gt; 0 Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardValidationFailed(FailedMessage, FailedControlId), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get New/ Existing Account Application Details.
''' &lt;/summary&gt;
Private Function GetAccountAppDetails(accountAppPk As Integer,
                                      accountAppTypeId As String,
                                      ByRef accountAppDetails As AccountAppDetails) As Boolean

  Dim AccountApp As finAccountApp
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  AccountApp = finBL.CreateAccountApp()

  ' Get Account Application
  If accountAppPk = 0 Then
    ' New Account Application
    Success = AccountApp.Initialise(accountAppTypeId)
  Else
    ' Load Existing
    Success = accountApp.LoadPk(accountAppPk)
  End If

  ' Create Account App Details
  If Success Then
    ' Create
    accountAppDetails = New AccountAppDetails()

    ' Update from Account Application
    Success = UpdateAccountAppDetailsFromAccountApp(accountAppDetails, AccountApp)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Update an AccountAppDetails object from an Account Application.
''' &lt;/summary&gt;
Public Function UpdateAccountAppDetailsFromAccountApp(accountAppDetails As AccountAppDetails,
                                                      accountApp As finAccountApp) As Boolean

  Dim Applicant As finAccountAppApplicant
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If accountApp.Applicants.Exists("MAIN") Then
    Applicant = accountApp.Applicants.ItemByKey("MAIN")
  Else
    Success = False
    finBL.Error.ErrorBegin("Application does not have a 'MAIN' Applicant and so cannot be accessed via this wizard.")
  End If

  ' Update
  If Success Then
    With accountAppDetails
      ' Not Serialised
      .AccountApp = accountApp
      .Applicant = Applicant

      ' System
      .IsNew = accountApp.IsNew
      .Pk = accountApp.Pk
      .Timestamp = accountApp.Timestamp
      .AccountAppId = accountApp.AccountAppId

      ' Eligibility
      .EligibilityOver18 = accountApp.UserData.GetBoolean("EligibilityOver18")
      .EligibilityResident = accountApp.UserData.GetBoolean("EligibilityResident")
      .EligibilityCreditCheck = accountApp.UserData.GetBoolean("EligibilityCreditCheck")
      .EligibilityTermsConditions = accountApp.UserData.GetBoolean("EligibilityTermsConditions")

      ' Loan Details
      .Purpose = accountApp.Purpose
      .PreferredLoanAmount = accountApp.PreferredLoanAmount
      .PreferredNumberOfPayments = accountApp.PreferredNumberOfPayments
      .PreferredPaymentFrequency = accountApp.PreferredPaymentFrequency

      ' Applicant
      .ClientId = applicant.ClientId
      .ClientName = finBL.ClientFunctions.GetRecordDescription(applicant.ClientId)

      .Title = applicant.Title
      .FirstName = applicant.FirstName
      .MiddleNames = applicant.MiddleNames
      .LastName = applicant.LastName
      .PreferredName = applicant.PreferredName

      If applicant.DateOfBirth &lt;&gt; Nothing Then .DateOfBirth = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(applicant.DateOfBirth)
      If applicant.Gender &lt;&gt; isefinGender.Unknown Then .Gender = applicant.GenderText

      .Phone = applicant.ContactPhone
      .Mobile = applicant.ContactMobile
      .Email = applicant.ContactEmail

      .StreetAddress_Postal = applicant.AddressPostal.StreetAddressFull
      .Suburb_Postal = applicant.AddressPostal.Suburb
      .City_Postal = applicant.AddressPostal.City
      .State_Postal = applicant.AddressPostal.State
      .Postcode_Postal = applicant.AddressPostal.Postcode
      .Country_Postal = applicant.AddressPostal.Country

      .PostalAndPhysicalAddressSame = applicant.AddressPhysicalIsPostal

      .StreetAddress_Physical = applicant.AddressPhysical.StreetAddressFull
      .Suburb_Physical = applicant.AddressPhysical.Suburb
      .City_Physical = applicant.AddressPhysical.City
      .State_Physical = applicant.AddressPhysical.State
      .Postcode_Physical = applicant.AddressPhysical.Postcode
      .Country_Physical = applicant.AddressPhysical.Country

      ' Image Summary HTML
      If Len(applicant.ImageFileName) &lt;&gt; 0 AndAlso finBL.DocumentManager.IsAvailable Then
        sb = finBL.CreateHtmlSummaryPage2StringBuilder()
        With sb
          .Initialise(ScriptInfo)
          .HtmlHeaderBegin()
          .HtmlHeaderEnd()

          .Append("{{DocumentManagerImage maxWidth='400px' fileName='" &amp; applicant.ImageFileNameResolved &amp; "'}}")
          .HtmlFinalise()
        End With

        .ImageSummaryHtml = sb.ToString(True)
      End If

      ' Applicant - Drivers Licence
      If mDriversLicenceDefinedSettings Then
        .DL_SpecialType = finBL.IdentificationTypes.ItemByPk(finBL.Settings.DriversLicenceIdentificationTypePk).SpecialTypeText
      Else
        .DL_SpecialType = Applicant.DriversLicenceSpecialTypeText
      End If
      .DL_NameFamily = Applicant.DriversLicenceNameFamily
      .DL_NameOther = Applicant.DriversLicenceNameOther
      .DL_DateOfBirth = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Applicant.DriversLicenceDateOfBirth)
      .DL_Expiry = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Applicant.DriversLicenceExpiryDate)
      .DL_State = Applicant.DriversLicenceIssuer

      ' Drivers Licence Number / Version
      SplitDriversLicenceNumber(Applicant.DriversLicenceNumber, .DL_Value, .DL_Version)
    End With
  End If

  ' New Record Defaults
  If Success AndAlso accountAppDetails.IsNew Then
    ' NOTE: Generally these would be set in the Account Application Type Script
    With accountAppDetails
      .PostalAndPhysicalAddressSame = True
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Update an existing Account Application from Account App Details object.
''' &lt;/summary&gt;
Public Function UpdateAccountAppFromAccountAppDetails(accountApp As finAccountApp,
                                                      accountAppDetails As AccountAppDetails) As Boolean

  Dim Applicant As finAccountAppApplicant
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If accountApp.Applicants.Exists("MAIN") Then
    Applicant = accountApp.Applicants.ItemByKey("MAIN")
  Else
    Success = False
    finBL.Error.ErrorBegin("Application does not have a 'MAIN' Applicant and so cannot be accessed via this wizard.")
  End If

  ' Update
  If Success Then
    With accountAppDetails
      ' Eligibility
      accountApp.UserData.SetBoolean("EligibilityOver18", .EligibilityOver18)
      accountApp.UserData.SetBoolean("EligibilityResident", .EligibilityResident)
      accountApp.UserData.SetBoolean("EligibilityCreditCheck", .EligibilityCreditCheck)
      accountApp.UserData.SetBoolean("EligibilityTermsConditions", .EligibilityTermsConditions)

      ' Loan Details
      accountApp.Purpose = .Purpose
      accountApp.PreferredLoanAmount = .PreferredLoanAmount
      accountApp.PreferredNumberOfPayments = .PreferredNumberOfPayments
      accountApp.PreferredPaymentFrequency = .PreferredPaymentFrequency

      ' Applicant
      applicant.ClientId = .ClientId
      applicant.LoadedFromClientId = .ClientId

      applicant.Title = .Title
      applicant.FirstName = .FirstName
      applicant.MiddleNames = .MiddleNames
      applicant.LastName = .LastName
      applicant.PreferredName = .PreferredName

      If .DateOfBirth Is Nothing Then
        applicant.DateOfBirth = Nothing
      Else
        applicant.DateOfBirth = CDate(.DateOfBirth)
      End If
      applicant.GenderText = .Gender

      applicant.ContactPhone = .Phone
      applicant.ContactMobile = .Mobile
      applicant.ContactEmail = .Email

      applicant.AddressPostal.StreetAddressFull = .StreetAddress_Postal
      applicant.AddressPostal.Suburb = .Suburb_Postal
      applicant.AddressPostal.City = .City_Postal
      applicant.AddressPostal.State = .State_Postal
      applicant.AddressPostal.Postcode = .Postcode_Postal
      applicant.AddressPostal.Country = .Country_Postal

      applicant.AddressPhysicalIsPostal = .PostalAndPhysicalAddressSame

      applicant.AddressPhysical.StreetAddressFull = .StreetAddress_Physical
      applicant.AddressPhysical.Suburb = .Suburb_Physical
      applicant.AddressPhysical.City = .City_Physical
      applicant.AddressPhysical.State = .State_Physical
      applicant.AddressPhysical.Postcode = .Postcode_Physical
      applicant.AddressPhysical.Country = .Country_Physical

      ' Applicant - Drivers Licence
      Applicant.DriversLicenceSpecialType = finBL.Enums.isefinIdentificationTypeSpecialType_FromString(.DL_SpecialType)
      Applicant.DriversLicenceNameFamily = .DL_NameFamily
      Applicant.DriversLicenceNameOther = .DL_NameOther
      Applicant.DriversLicenceIssuer = .DL_State

      If Len(.DL_Version) = 0 Then
        Applicant.DriversLicenceNumber = .DL_Value
      Else
        Applicant.DriversLicenceNumber = String.Format("{0}-{1}", .DL_Value, .DL_Version)
      End If

      If .DL_DateOfBirth Is Nothing Then
        Applicant.DriversLicenceDateOfBirth = Nothing
      Else
        Applicant.DriversLicenceDateOfBirth = CDate(.DL_DateOfBirth)
      End If
      If .DL_Expiry Is Nothing Then
        Applicant.DriversLicenceExpiryDate = Nothing
      Else
        Applicant.DriversLicenceExpiryDate = CDate(.DL_Expiry)
      End If
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account Financial Summary.
''' &lt;/summary&gt;
Private Sub GetAccountSummary(parametersJson As String,
                              ByRef returnValue As String)

  Dim Account As finAccount
  Dim AccountApp As finAccountApp
  Dim AccountAppDetails As AccountAppDetails
  Dim AccountAppDetailsTemp As AccountAppDetails
  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get/ Create Account Application
  If Success Then
    If GetAccountAppDetails(mAccountAppPk, mAccountAppTypeId, AccountAppDetailsTemp) Then
      AccountApp = AccountAppDetailsTemp.AccountApp
    Else
      Success = False
    End If
  End If

  ' Update Account Application
  If Success Then
    Success = UpdateAccountAppFromAccountAppDetails(AccountApp, AccountAppDetails)
  End If

  ' Create Account
  If Success Then
    Success = AccountApp.CreateAccount(Account)
  End If

  ' Validate and Calculate
  If Success Then
    Success = Account.Calculation.Calculate()
  End If

  ' Get Financial Summary
  If Success Then
    returnValue = finBL.SummaryPageFunctions.AccountFinancialSummary(False, Account, -1 , finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, "AccountApp"))
  End If

  ' Error
  If Not Success Then
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message(True, True))
  End If

End Sub

''' &lt;summary&gt;
'''  Update an existing Account Application from Account App Details object.
''' &lt;/summary&gt;
Public Function ClientPreload(parametersJson As String,
                              ByRef returnValue As String) As Boolean

  Dim AccountAppDetails As AccountAppDetails
  Dim Client As finClient
  Dim ClientId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate
  If Len(ClientId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Client Id not specified.")
  End If

  ' Get Account App Details
  If Success Then
    Success = GetAccountAppDetails(mAccountAppPk, mAccountAppTypeId, AccountAppDetails)
  End If

  ' Load Client
  If Success Then
    Client = finBL.CreateClient()
    Success = Client.Load(ClientId)
  End If

  ' Validate Client
  If Success Then
    If Not Client.IsIndividualOrSoleTrader Then
      Success = False
      finBL.Error.ErrorBegin("Only Individual or Sole Trader Clients can be preloaded for this Application Type.")
    End If
  End If

  ' Preload Client into Applicant
  If Success Then
    If AccountAppDetails.Applicant.UpdateFromClient(Client) Then
      Success = UpdateAccountAppDetailsFromAccountApp(AccountAppDetails, AccountAppDetails.AccountApp)
    Else
      Success = False
    End If
  End If

  ' Finalise
  If Success Then
    ' Record new Client Id
    AccountAppDetails.ClientId = Client.ClientId

    ' Serialise
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(AccountAppDetails, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Scan a Drivers Licence Image.
''' &lt;/summary&gt;
Private Function ScanImage(requestInfo As finScriptRequestInfo,
                           ByRef response As String) As Boolean

  Dim IdentificationDetails As finIdentificationDetails
  Dim OcrParsedText As finOcrParsedText
  Dim OcrRequest As ISOcrRequest_TextDetection
  Dim OcrResponse As ISOcrResponse_TextDetection
  Dim ScanImageResults As ScanImageResults
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If requestInfo.Files.Count = 0 Then
    Success = False
    finBL.Error.ErrorBegin("No image file supplied to scan.")
  End If

  ' OCR Service
  If Success Then
    ' Request
    ' NOTE: Restrict image width and optimise image size for better performance
    OcrRequest = finBL.Ocr.CreateRequest_TextDetection()
    Success = OcrRequest.LoadImageBase64(requestInfo.Files(0).FileDataToBase64String(), mOcrImageMaxWidth, False, True)

    ' Execute
    If Success Then
      Success = finBL.Ocr.ExecuteTextDetection(OcrRequest, OcrResponse, OcrParsedText)
    End If

    ' Parse Response
    If Success Then
      ScanImageResults = New ScanImageResults()

      ' Generic Client details
      With OcrParsedText.GetClientDetails()
        ScanImageResults.FirstName = .FirstName
        ScanImageResults.MiddleNames = .MiddleNames
        ScanImageResults.LastName = .LastName
        ScanImageResults.DateOfBirth = finBL.Runtime.DateUtilities.CastToNullableUtcDate(.DateOfBirth)
        If .Gender &lt;&gt; isefinGender.Unknown Then
          ScanImageResults.Gender = .GenderText
        End If

        If .AddressDetails.HasValue Then
          With .AddressDetails
            ScanImageResults.StreetAddressFull = .StreetAddressFull
            ScanImageResults.City = .City
            ScanImageResults.Suburb = .Suburb
            ScanImageResults.State = .State
            ScanImageResults.Postcode = .Postcode
            ScanImageResults.Country = .Country
          End With
        End If
      End With

      ' Identification Document specific details
      IdentificationDetails = OcrParsedText.GetIdentificationDetails()
      If IdentificationDetails IsNot Nothing Then
        With IdentificationDetails
          Select Case .SpecialType
            Case isefinIdentificationTypeSpecialType.AU_DriversLicence, isefinIdentificationTypeSpecialType.NZ_DriversLicence, isefinIdentificationTypeSpecialType.US_DriversLicence
              ' Drivers Licence
              ScanImageResults.DL_SpecialType = .SpecialTypeText
              ScanImageResults.DL_NameFamily = ""
              ScanImageResults.DL_NameOther = .IdName
              ScanImageResults.DL_DateOfBirth = finBL.Runtime.DateUtilities.CastToNullableUtcDate(.IdDateOfBirth)
              ScanImageResults.DL_Expiry = finBL.Runtime.DateUtilities.CastToNullableUtcDate(.DateExpiry)
              ScanImageResults.DL_State = .Issuer

              ' Licence Number
              SplitDriversLicenceNumber(.Value, ScanImageResults.DL_Value, ScanImageResults.DL_Version)
          End Select
        End With

        ' Update Identification Names for supported Special Types
        Select Case OcrParsedText.IdentificationTypeSpecialType
          Case isefinIdentificationTypeSpecialType.AU_DriversLicence
            With OcrParsedText.ParsedDocumentDetails_AU_DriversLicence
              ScanImageResults.DL_NameFamily = .FamilyName
              ScanImageResults.DL_NameOther = .OtherNames
            End With

          Case isefinIdentificationTypeSpecialType.NZ_DriversLicence
            With OcrParsedText.ParsedDocumentDetails_NZ_DriversLicence
              ScanImageResults.DL_NameFamily = .FamilyName
              ScanImageResults.DL_NameOther = .OtherNames
            End With

          Case Else
            ' Special Type not yet supported in OCR
        End Select
      End If

      ' Other (just in case JavaScript code wants to do something special)
      With OcrResponse
        ScanImageResults.ParsedDocumentType = OcrParsedText.ParsedDocumentType.ToString()
      End With
    End If
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Splits a Drivers Licence Number to number and version.
''' &lt;/summary&gt;
Private Sub SplitDriversLicenceNumber(value As String,
                                      ByRef licenceNumber As String,
                                      ByRef licenceVersion As String)

  Dim i As Integer

  ' Split
  i = InStr(value, "-")
  If i = 0 Then
    licenceNumber = value
    licenceVersion = ""
  Else
    licenceNumber = Mid(value, 1, i - 1)
    licenceVersion = Mid(value, i + 1)
  End If

End Sub

Private Class ScanImageResults

  Public ParsedDocumentType As String
  Public DocumentStyle As String

  ' Client Details
  Public DateOfBirth As Date?
  Public FirstName As String
  Public MiddleNames As String
  Public LastName As String
  Public Gender As String
  Public StreetAddressFull As String
  Public Suburb As String
  Public City As String
  Public State As String
  Public Postcode As String
  Public Country As String

  ' Identification Details
  Public DL_SpecialType As String
  Public DL_NameFamily As String
  Public DL_NameOther As String
  Public DL_Value As String
  Public DL_State As String
  Public DL_Version As String
  Public DL_DateOfBirth As Date?
  Public DL_Expiry As Date?

End Class



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

  ' Record
  Public [ReadOnly] As Boolean

  ' Account Application
  Public AccountAppDetails As AccountAppDetails

  ' Permissions
  Public CanDelete As Boolean

  ' Lists
  Public List_Genders As String
  Public List_Purposes As String
  Public List_Payments As String
  Public List_LicenceSpecialTypes As String
  Public List_States_AU As Object
  Public List_States_US As Object  

  ' Settings
  Public AllowImageUpload As Boolean
  Public PostalValidation As Boolean
  Public DefaultCountry As String
  Public DriversLicenceSpecialTypeAllowUpdate As Boolean

  ' Configuration
  Public AlwaysShowAdvanced As Boolean
  Public HideCity As Boolean
  Public PromptOnSave As Boolean

End Class


Public Class AccountAppDetails

  ' Not Serialised
  Friend AccountApp As finAccountApp
  Friend Applicant As finAccountAppApplicant

  ' System
  Public IsNew As Boolean
  Public AccountAppId As String
  Public Pk As Integer
  Public Timestamp As Integer

  ' Eligibility
  Public EligibilityOver18 As Boolean
  Public EligibilityResident As Boolean
  Public EligibilityCreditCheck As Boolean
  Public EligibilityTermsConditions As Boolean

  ' Loan Details
  Public Purpose As String
  Public PreferredLoanAmount As Decimal
  Public PreferredNumberOfPayments As Integer
  Public PreferredPaymentFrequency As String

  ' Applicant
  Public ClientId As String
  Public ClientName As String

  Public Title As String
  Public FirstName As String
  Public MiddleNames As String
  Public LastName As String
  Public PreferredName As String

  Public DateOfBirth As Date?
  Public Gender As String

  Public Phone As String
  Public Mobile As String
  Public Email As String

  Public StreetAddress_Postal As String
  Public Suburb_Postal As String
  Public City_Postal As String
  Public State_Postal As String
  Public Postcode_Postal As String
  Public Country_Postal As String

  Public PostalAndPhysicalAddressSame As Boolean

  Public StreetAddress_Physical As String
  Public Suburb_Physical As String
  Public City_Physical As String
  Public State_Physical As String
  Public Postcode_Physical As String
  Public Country_Physical As String

  Public ImageSummaryHtml As String

  ' Applicant - Drivers Licence
  Public DL_SpecialType As String
  Public DL_SpecialTypeAllowEdit As Boolean
  Public DL_NameFamily As String
  Public DL_NameOther As String
  Public DL_Value As String
  Public DL_State As String
  Public DL_Version As String
  Public DL_DateOfBirth As Date?
  Public DL_Expiry As Date?

End Class


Public Class WizardValidationFailed

  Public FailedMessage As String
  Public FailedControlId As String

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

    Me.FailedMessage = failedMessage
    Me.FailedControlId = failedControlId

  End Sub

End Class


Public Class WizardFinishDetails

  Public AccountAppId As String
  Public ImageError As String

  Public Sub New(accountAppId As String,
                 imageError As String)

    Me.AccountAppId = accountAppId
    Me.ImageError = imageError

  End Sub

End Class</Code>
  <Language>VisualBasic</Language>
  <Notes>Sample HTML Widget to allow entry of a new or existing Account Application.</Notes>
  <PermissionKeyExecute />
  <RunWithoutPrompts>false</RunWithoutPrompts>
  <TemplateText>&lt;style type="text/less"&gt;
.name-details {
  display:flex;
  flex-direction:row;

  &gt; div {
    padding-right:2px;
    flex-grow:2;

    /* Title */
    &amp;:first-child {
      flex-grow:0;
    }

    /* First Name */
    &amp;:nth-child(2) {
      flex-grow:1;
    }
  }

  /* Responsive */
  @media screen and (max-width: 640px) {
    flex-direction:column;

    &gt; div {
      margin-bottom:4px;
    }
  }
}
&lt;/style&gt;

&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;Account Application&lt;/div&gt;
    &lt;div class="summary"&gt;Enter Application details.&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="Application" tooltipText="Enter general Application details."&gt;Application&lt;/li&gt;
        &lt;li tabId="Client" tooltipText="Preload an existing Client or load details from an item of identification."&gt;Preload Applicant Details&lt;/li&gt;
        &lt;li tabId="Applicant" tooltipText="Enter Name and other details for this Applicant."&gt;Applicant&lt;/li&gt;
        &lt;li tabId="Identification" tooltipText="Enter Drivers licence details for this Applicant."&gt;Identification&lt;/li&gt;
        &lt;li tabId="Image" tooltipText="Optionally, upload an Image for this Applicant."&gt;Image&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Application --&gt;
    &lt;div id="pageApplication" class="is-tab-page" style="display:flex; flex-direction:column;"&gt;
      &lt;div&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="lblEligibility"&gt;Eligibility&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;input id="chkEligibilityOver18" type="checkbox"/&gt;
            &lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;input id="chkEligibilityResident" type="checkbox"/&gt;
            &lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;input id="chkEligibilityCreditCheck" type="checkbox"/&gt;
            &lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;input id="chkEligibilityTermsConditions" type="checkbox"/&gt;
            &lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblLoanDetails"&gt;Loan details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboPurpose"&gt;Purpose:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboPurpose"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="numPreferredLoanAmount"&gt;Loan Amount:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numPreferredLoanAmount" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="numPreferredNumberOfPayments"&gt;No. Payments:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numPreferredNumberOfPayments"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboPreferredPaymentFrequency"&gt;Frequency:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboPreferredPaymentFrequency"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;
      &lt;div id="wbAccountSummary" style="flex-grow:1; margin-top:8px;"&gt;&lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Client --&gt;
    &lt;div id="pageClient" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:6em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPreload"&gt;Preload Applicant details from an existing Client record&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboClient"&gt;Client:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboClient"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;button id="cmdClientPreload" class="is-button ok"&gt;Preload Client Details&lt;/button&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOcr"&gt;Or, supply a Drivers Licence photograph&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;
            &lt;label for="fileIdImage"&gt;Upload a photo or use your device's camera to capture an image of your Driver's Licence and prepopulate Applicant details&lt;/label&gt;
            &lt;input id="fileIdImage" type="file" accept="image/*" field-type="file" max-files="1"/&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Applicant --&gt;
    &lt;div id="pageApplicant" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPersonsName"&gt;Person's Name&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFirstName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;div class="name-details"&gt;
              &lt;div&gt;&lt;input id="cboTitle"/&gt;&lt;/div&gt;
              &lt;div&gt;&lt;input id="txtFirstName"/&gt;&lt;/div&gt;
              &lt;div&gt;&lt;input id="txtMiddleNames"/&gt;&lt;/div&gt;
              &lt;div&gt;&lt;input id="txtLastName"/&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPreferredName"&gt;Preferred:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPreferredName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOtherDetails"&gt;Other details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateDateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateDateOfBirth"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboGender"&gt;Gender:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboGender"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblContactDetails"&gt;Contact details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPhone"&gt;Phone:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPhone"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtMobile"&gt;Mobile:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtMobile"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtEmail"&gt;Email:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtEmail"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPostalAddress"&gt;Postal Address&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtStreetAddress_Postal"&gt;Street:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtStreetAddress_Postal"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtSuburb_Postal"&gt;Suburb:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtSuburb_Postal"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCity_Postal"&gt;City:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCity_Postal"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtState_Postal"&gt;State:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtState_Postal"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPostcode_Postal"&gt;Postcode:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPostcode_Postal"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCountry_Postal"&gt;Country:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCountry_Postal"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkPostalAndPhysicalAddressSame" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tbody id="tbodyPhysicalAddress" style="display:none"&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPhysicalAddress"&gt;Physical Address&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtStreetAddress_Physical"&gt;Street:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtStreetAddress_Physical"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtSuburb_Physical"&gt;Suburb:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtSuburb_Physical"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCity_Physical"&gt;City:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCity_Physical"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtState_Physical"&gt;State:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtState_Physical"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPostcode_Physical"&gt;Postcode:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPostcode_Physical"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCountry_Physical"&gt;Country:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCountry_Physical"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Identification --&gt;
    &lt;div id="pageIdentification" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;!-- Drivers Licence Special Type --&gt;
        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblIdentification"&gt;Drivers Licence details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboDL_SpecialType"&gt;Licence Type:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDL_SpecialType"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Licence Details --&gt;
        &lt;tbody id="tbLicenceDetails" style="display:none;"&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtDL_Value"&gt;Licence No.:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtDL_Value"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboDL_State"&gt;State:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDL_State" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtDL_Version"&gt;Version:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtDL_Version"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtDL_NameFamily"&gt;Family Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtDL_NameFamily"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtDL_NameOther"&gt;Given Name(s):&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtDL_NameOther"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateDL_DateOfBirth"&gt;Date of Birth:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;
              &lt;input id="dateDL_DateOfBirth"/&gt;
              &lt;label id="lblDOBWarning" style="color:red; font-weight:normal; margin-left:4px;"&gt;Differs from Applicant's Date of Birth&lt;/label&gt;
            &lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateDL_Expiry"&gt;Expiry Date:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateDL_Expiry"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Image --&gt;
    &lt;div id="pageImage" class="is-tab-page" style="display:flex; flex-direction:column;"&gt;
      &lt;div&gt;
        &lt;table class="is-form"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblImageUpload"&gt;Choose an Image to Upload&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;label for="fileImageFile"&gt;The maximum image size saved to the Document Manager will be 1024 x 728 and the orientation will automatically be adjusted if necessary&lt;/label&gt;
              &lt;input id="fileImageFile" type="file" accept="image/*" field-type="file" max-files="1"/&gt;
            &lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblExistingHeading"&gt;Existing Image&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div id="wbImageSummary" style="flex-grow:1;"&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;Add New&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;



&lt;script&gt;
var mAllowImageUpload = true; //TODO: Remove

// Properties
var mRecord;
var mAccountApp;

// Controls
var C = {
  // Application
  lblEligibility: null,
  chkEligibilityOver18: null,
  chkEligibilityResident: null,
  chkEligibilityCreditCheck: null,
  chkEligibilityTermsConditions: null,

  lblLoanDetails: null,
  cboPurpose: null,
  numPreferredLoanAmount: null,
  numPreferredNumberOfPayments: null,
  cboPreferredPaymentFrequency: null,
  wbAccountSummary: null,

  // Client
  lblPreload: null,
  cboClient: null,
  lblOcr: null,
  fileIdImage: null,

  // Applicant
  lblPersonsName: null,
  cboTitle: null,
  txtFirstName: null,
  txtMiddleNames: null,
  txtLastName: null,
  txtPreferredName: null,
  dateDateOfBirth: null,
  cboGender: null,

  lblOtherDetails: null,
  txtPhone: null,
  txtMobile: null,
  txtEmail: null,

  lblContactDetails: null,
  lblPostalAddress: null,
  txtStreetAddress_Postal: null,
  txtSuburb_Postal: null,
  txtCity_Postal: null,
  txtState_Postal: null,
  txtPostcode_Postal: null,
  txtCountry_Postal: null,

  lblPhysicalAddress: null,
  txtStreetAddress_Physical: null,
  txtSuburb_Physical: null,
  txtCity_Physical: null,
  txtState_Physical: null,
  txtPostcode_Physical: null,
  txtCountry_Physical: null,

  chkPostalAndPhysicalAddressSame: null,

  // Identification
  lblIdentification: null,
  cboDL_SpecialType: null,
  txtDL_NameFamily: null,
  txtDL_NameOther: null,
  tbLicenceDetails: null,
  txtDL_Value: null,
  cboDL_State: null,
  txtDL_Version: null,
  dateDL_DateOfBirth: null,
  lblDOBWarning: null,
  dateDL_Expiry: null,

  // Image
  lblImageUpload: null,
  fileImageFile: null,
  lblExistingHeading: null,
  wbImageSummary: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mClientIdOriginal;

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   Application
  C.lblEligibility = widget.UI.Label("lblEligibility", {});
  C.chkEligibilityOver18 = widget.UI.CheckBox("chkEligibilityOver18", {
    caption: "Are you 18 years or older?"
  });
  C.chkEligibilityResident = widget.UI.CheckBox("chkEligibilityResident", {
    caption: "" // Caption set in Fields_Update()
  });
  C.chkEligibilityCreditCheck = widget.UI.CheckBox("chkEligibilityCreditCheck", {
    caption: "Do you agree to a Credit Check?",
  });
  C.chkEligibilityTermsConditions = widget.UI.CheckBox("chkEligibilityTermsConditions", {
    caption: "Do you accept our Terms and Conditions?",
  });

  C.lblLoanDetails = widget.UI.Label("lblLoanDetails", {});
  C.cboPurpose = widget.UI.ComboBox("cboPurpose", {
    maxLength: 50
  });
  C.numPreferredLoanAmount = widget.UI.NumberBox("numPreferredLoanAmount", {
    decimals: -1,
    width: "8em",
    onChange: UpdateAccountSummary,
  });
  C.numPreferredNumberOfPayments = widget.UI.NumberBox("numPreferredNumberOfPayments", {
    decimals: 0,
    blankIfZero: true,
    width: "4em",
    onChange: UpdateAccountSummary,
  });
  C.cboPreferredPaymentFrequency = widget.UI.ComboBox("cboPreferredPaymentFrequency", {
    maxLength: 20,
    onChange: UpdateAccountSummary,
  });
  C.wbAccountSummary = widget.UI.PreviewPane("wbAccountSummary", {
    border: false
  });

  //   Client
  C.lblPreload = widget.UI.Label("lblPreload", {});
  C.cboClient = widget.UI.DBCombo("cboClient", {
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.lblOcr = widget.UI.Label("lblOcr", {});

  //   Applicant
  C.lblPersonsName = widget.UI.Label("lblPersonsName", {});
  C.cboTitle = widget.UI.InformationListComboBox("cboTitle", {
    maxLength: 20,
    width: "8em",
  });
  C.txtFirstName = widget.UI.TextBox("txtFirstName", {
    maxLength: 40,
    blankTip: "First",
  });
  C.txtMiddleNames = widget.UI.TextBox("txtMiddleNames", {
    maxLength: 60,
    blankTip: "Middle",
  });
  C.txtLastName = widget.UI.TextBox("txtLastName", {
    maxLength: 40,
    blankTip: "Last",
  });
  C.txtPreferredName = widget.UI.TextBox("txtPreferredName", {
    maxLength: 40,
  });
  C.lblOtherDetails = widget.UI.Label("lblOtherDetails", {});
  C.dateDateOfBirth = widget.UI.DateBox("dateDateOfBirth", {
    historic: true,
    showAge: true,
  });
  C.cboGender = widget.UI.ComboBox("cboGender", {
    limitToList: true,
    maxLength: 15,
  });

  C.lblContactDetails = widget.UI.Label("lblContactDetails", {});
  C.txtPhone = widget.UI.TextBox("txtPhone", {
    maxLength: 20,
    width: "12em",
  });
  C.txtMobile = widget.UI.TextBox("txtMobile", {
    maxLength: 20,
    width: "12em",
  });
  C.txtEmail = widget.UI.TextBox("txtEmail", {
    maxLength: 50,
    width: "12em",
  });

  C.lblPostalAddress = widget.UI.Label("lblPostalAddress", {});
  C.txtStreetAddress_Postal = widget.UI.TextBox("txtStreetAddress_Postal", {
    maxLength: 130,
  });
  C.txtSuburb_Postal = widget.UI.TextBox("txtSuburb_Postal", {
    maxLength: 50,
  });
  C.txtCity_Postal = widget.UI.TextBox("txtCity_Postal", {
    maxLength: 50,
  });
  C.txtState_Postal = widget.UI.TextBox("txtState_Postal", {
    maxLength: 50,
  });
  C.txtPostcode_Postal = widget.UI.TextBox("txtPostcode_Postal", {
    maxLength: 10,
  });
  C.txtCountry_Postal = widget.UI.TextBox("txtCountry_Postal", {
    maxLength: 50,
  });

  C.chkPostalAndPhysicalAddressSame = widget.UI.CheckBox("chkPostalAndPhysicalAddressSame", {
    caption: "This is also the Physical Address",
    onChange: chkPostalAndPhysicalAddressSame_Change,
  });

  C.lblPhysicalAddress = widget.UI.Label("lblPhysicalAddress", {});
  C.txtStreetAddress_Physical = widget.UI.TextBox("txtStreetAddress_Physical", {
    maxLength: 130,
  });
  C.txtSuburb_Physical = widget.UI.TextBox("txtSuburb_Physical", {
    maxLength: 50,
  });
  C.txtCity_Physical = widget.UI.TextBox("txtCity_Physical", {
    maxLength: 50,
  });
  C.txtState_Physical = widget.UI.TextBox("txtState_Physical", {
    maxLength: 50,
  });
  C.txtPostcode_Physical = widget.UI.TextBox("txtPostcode_Physical", {
    maxLength: 10,
  });
  C.txtCountry_Physical = widget.UI.TextBox("txtCountry_Physical", {
    maxLength: 50,
  });

  //   Identification
  C.lblIdentification = widget.UI.Label("lblIdentification", {});
  C.cboDL_SpecialType = widget.UI.ComboBox("cboDL_SpecialType", {
    limitToList: true,
    maxLength: 50,

    onChange: cboDL_SpecialType_Change,
  });
  C.txtDL_NameFamily = widget.UI.TextBox("txtDL_NameFamily", {
    maxLength: 100,
  });
  C.txtDL_NameOther = widget.UI.TextBox("txtDL_NameOther", {
    maxLength: 100,
  });
  C.tbLicenceDetails = $("#tbLicenceDetails");
  C.txtDL_Value = widget.UI.TextBox("txtDL_Value", {
    maxLength: 50,
  });
  C.cboDL_State = widget.UI.DBCombo("cboDL_State", {
    maxLength: 50,
    width: "7em"
  });
  C.txtDL_Version = widget.UI.TextBox("txtDL_Version", {
    maxLength: 3,
    width: "3em",
  });
  C.dateDL_DateOfBirth = widget.UI.DateBox("dateDL_DateOfBirth", {
    historic: true,

    onChange: dateDL_DateOfBirth_Change
  });
  C.lblDOBWarning = widget.UI.Label("lblDOBWarning", {});
  C.dateDL_Expiry = widget.UI.DateBox("dateDL_Expiry", {});

  //   Image
  C.lblImageUpload = widget.UI.Label("lblImageUpload", {});
  C.lblExistingHeading = widget.UI.Label("lblExistingHeading", {});
  C.wbImageSummary = widget.UI.PreviewPane("wbImageSummary", {
    border: false
  });

  // Controls
  $("#cmdClientPreload").click(ClientPreload);

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

  // Create Tabs
  tabWizard = new widget.UI.Tabs("tabWizard", {style: "wizard"}); // If not using a 'wizard' style then: onSelectedTabChanged: function() { tabWizard_Refresh(tabWizard.SelectedTabIndex()); } });

  // Handle resize
  $(window).resize(Form_Resize);

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

  // Initialise Addressing
  // NOTE: This sets the maxlength of the supplied controls so call before creating the form
  widget.UI.InitialiseAddressAutoComplete({streetAddress: "txtStreetAddress_Postal", suburb: "txtSuburb_Postal", city: "txtCity_Postal", state: "txtState_Postal", postcode: "txtPostcode_Postal", country: "txtCountry_Postal"});
  widget.UI.InitialiseAddressAutoComplete({streetAddress: "txtStreetAddress_Physical", suburb: "txtSuburb_Physical", city: "txtCity_Physical", state: "txtState_Physical", postcode: "txtPostcode_Physical", country: "txtCountry_Physical"});

  // Reset
  Form_Reset();

  C.fileIdImage = $("#fileIdImage");
  C.fileIdImage.change(ScanImage);
  C.fileImageFile = $("#fileImageFile");
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Set Tab
  tabWizard.SelectedTabId("Application");

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mAccountApp = null;

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    Record_Load_Done,

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

function Record_Load_Done(data) {
  // Initialise
  mRecord = JSON.parse(data);
  mAccountApp = mRecord.AccountAppDetails;
  Fields_Load();

  // Define Actions

  // Skip "New" Page
  tabWizard_Refresh(0);
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mAccountApp) {
    // Eligibility
    C.chkEligibilityOver18.Value(mAccountApp.EligibilityOver18);
    C.chkEligibilityResident.Value(mAccountApp.EligibilityResident);
    C.chkEligibilityCreditCheck.Value(mAccountApp.EligibilityCreditCheck);
    C.chkEligibilityTermsConditions.Value(mAccountApp.EligibilityTermsConditions);

    // Loan Details
    C.cboPurpose.Text(mAccountApp.Purpose);
    C.numPreferredLoanAmount.Value(mAccountApp.PreferredLoanAmount);
    C.numPreferredNumberOfPayments.Value(mAccountApp.PreferredNumberOfPayments);
    C.cboPreferredPaymentFrequency.Text(mAccountApp.PreferredPaymentFrequency);

    // Applicant
    Fields_Load_Applicant(mAccountApp);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
  tabWizard_Resize();
}

function Fields_Load_Applicant(record) {
  // Update List Controls  

  // Applicant
  C.cboClient.Text(record.ClientId);

  C.cboTitle.Text(record.Title);
  C.txtFirstName.Text(record.FirstName);
  C.txtMiddleNames.Text(record.MiddleNames);
  C.txtLastName.Text(record.LastName);
  C.txtPreferredName.Text(record.PreferredName);

  C.dateDateOfBirth.Value(record.DateOfBirth);
  C.cboGender.Text(record.Gender);

  C.txtPhone.Text(record.Phone);
  C.txtMobile.Text(record.Mobile);
  C.txtEmail.Text(record.Email);

  C.txtStreetAddress_Postal.Text(record.StreetAddress_Postal);
  C.txtSuburb_Postal.Text(record.Suburb_Postal);
  C.txtCity_Postal.Text(record.City_Postal);
  C.txtState_Postal.Text(record.State_Postal);
  C.txtPostcode_Postal.Text(record.Postcode_Postal);
  C.txtCountry_Postal.Text(record.Country_Postal);

  C.chkPostalAndPhysicalAddressSame.Value(record.PostalAndPhysicalAddressSame);

  C.txtStreetAddress_Physical.Text(record.StreetAddress_Physical);
  C.txtSuburb_Physical.Text(record.Suburb_Physical);
  C.txtCity_Physical.Text(record.City_Physical);
  C.txtState_Physical.Text(record.State_Physical);
  C.txtPostcode_Physical.Text(record.Postcode_Physical);
  C.txtCountry_Physical.Text(record.Country_Physical);

  // Applicant - Drivers Licence
  C.cboDL_SpecialType.Text(record.DL_SpecialType);
  C.txtDL_NameFamily.Text(record.DL_NameFamily);
  C.txtDL_NameOther.Text(record.DL_NameOther);
  C.txtDL_Value.Text(record.DL_Value);
  C.cboDL_State.Text(record.DL_State);
  C.txtDL_Version.Text(record.DL_Version);
  C.dateDL_DateOfBirth.Value(record.DL_DateOfBirth);
  C.dateDL_Expiry.Value(record.DL_Expiry);

  // Image Summary
  if (record.ImageSummaryHtml) {
    C.wbImageSummary.SetContent(record.ImageSummaryHtml, false);
    C.lblExistingHeading.VisibleRow(true);
  }
  else {
    C.lblExistingHeading.VisibleRow(false);
  }

  // Update Controls
  chkPostalAndPhysicalAddressSame_Change();

  // Other
  mClientIdOriginal = record.ClientId;

  // Update Loan Summary
  UpdateAccountSummary();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Eligibility
  mAccountApp.EligibilityOver18 = C.chkEligibilityOver18.Value();
  mAccountApp.EligibilityResident = C.chkEligibilityResident.Value();
  mAccountApp.EligibilityCreditCheck = C.chkEligibilityCreditCheck.Value();
  mAccountApp.EligibilityTermsConditions = C.chkEligibilityTermsConditions.Value();

  // Loan Details
  mAccountApp.Purpose = C.cboPurpose.Text();
  mAccountApp.PreferredLoanAmount = C.numPreferredLoanAmount.Value();
  mAccountApp.PreferredNumberOfPayments = C.numPreferredNumberOfPayments.Value();
  mAccountApp.PreferredPaymentFrequency = C.cboPreferredPaymentFrequency.Text();

  // Applicant
  mAccountApp.ClientId = C.cboClient.Text();

  mAccountApp.Title = C.cboTitle.Text();
  mAccountApp.FirstName = C.txtFirstName.Text();
  mAccountApp.MiddleNames = C.txtMiddleNames.Text();
  mAccountApp.LastName = C.txtLastName.Text();
  mAccountApp.PreferredName = C.txtPreferredName.Text();

  mAccountApp.DateOfBirth = C.dateDateOfBirth.Value();
  mAccountApp.Gender = C.cboGender.Text();

  mAccountApp.Phone = C.txtPhone.Text();
  mAccountApp.Mobile = C.txtMobile.Text();
  mAccountApp.Email = C.txtEmail.Text();

  mAccountApp.StreetAddress_Postal = C.txtStreetAddress_Postal.Text();
  mAccountApp.Suburb_Postal = C.txtSuburb_Postal.Text();
  mAccountApp.City_Postal = C.txtCity_Postal.Text();
  mAccountApp.State_Postal = C.txtState_Postal.Text();
  mAccountApp.Postcode_Postal = C.txtPostcode_Postal.Text();
  mAccountApp.Country_Postal = C.txtCountry_Postal.Text();

  mAccountApp.PostalAndPhysicalAddressSame = C.chkPostalAndPhysicalAddressSame.Value();

  mAccountApp.StreetAddress_Physical = C.txtStreetAddress_Physical.Text();
  mAccountApp.Suburb_Physical = C.txtSuburb_Physical.Text();
  mAccountApp.City_Physical = C.txtCity_Physical.Text();
  mAccountApp.State_Physical = C.txtState_Physical.Text();
  mAccountApp.Postcode_Physical = C.txtPostcode_Physical.Text();
  mAccountApp.Country_Physical = C.txtCountry_Physical.Text();

  // Applicant - Drivers Licence
  mAccountApp.DL_SpecialType = C.cboDL_SpecialType.Text();
  mAccountApp.DL_NameFamily = C.txtDL_NameFamily.Text();
  mAccountApp.DL_NameOther = C.txtDL_NameOther.Text();
  mAccountApp.DL_Value = C.txtDL_Value.Text();
  mAccountApp.DL_State = C.cboDL_State.Text();
  mAccountApp.DL_Version = C.txtDL_Version.Text();
  mAccountApp.DL_DateOfBirth = C.dateDL_DateOfBirth.Value();
  mAccountApp.DL_Expiry = C.dateDL_Expiry.Value();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading

  // Information Lists
  C.cboTitle.SetComboFromInformationList("Titles", true);

  // Lists
  if (mRecord) {
    C.cboGender.ListFromCsvString(mRecord.List_Genders);
    C.cboPurpose.ListFromCsvString(mRecord.List_Purposes);
    C.cboPreferredPaymentFrequency.ListFromCsvString(mRecord.List_Payments);
    C.cboClient.RefreshFromStandardRange("Clients", "", false, mRecord.ClientId);
    C.cboDL_SpecialType.ListFromCsvString(mRecord.List_LicenceSpecialTypes);
    C.cboDL_SpecialType.ReadOnly(!mRecord.DriversLicenceSpecialTypeAllowUpdate);
  }

  // Controls
  if (mRecord) {
    C.chkEligibilityResident.Caption("Are you a resident of " + mRecord.DefaultCountry + "?");
  }

  // Update Buttons
  tabWizard_UpdateButtons();

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) frmMain.FormReadOnly(C, true);

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

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// ======
// Finish
// ======
function Finish() {
  // Validate
  tabWizard_Validate(function() {
    // Save Fields
    Fields_Save();

    // Confirm Message
    var s;
    if (mAccountApp.IsNew) {
      s = "Add a new Account Application record?";
    }
    else {
      s = "Update Account Application '" + mAccountApp.AccountAppId + "'?";
    }

    // Confirm
    widget.UI.MsgBoxConfirm(s, {}, function() {
      // Disable Form
      frmMain.FormDisable("Saving");

      // Files to upload?
      var files = [];
      if (C.fileImageFile[0].GetFiles().length != 0) {
        files.push(C.fileImageFile[0].GetFiles()[0]);
        files[files.length - 1].tag = "ClientImage";
      }
      if (C.fileIdImage[0].GetFiles().length != 0) {
        files.push(C.fileIdImage[0].GetFiles()[0]);
        files[files.length - 1].tag = "IdImage_DL";
      }

      // Add/ Update Account Application
      // NOTE: Use UploadFiles rather that GetString so that the Image files are uploaded
      widget.UploadFiles("Finish", mAccountApp, files, Finish_Done, Finish_Fail);
    });    
  });
}

function Finish_Done(data) {
  // Enable Form
  frmMain.FormEnable();

  // Parse Data
  var o = {};
  if (data) o = JSON.parse(data);

  // Notify
  var s;
  if (mAccountApp.IsNew || o.ImageError) {
    if (mAccountApp.IsNew) {
      s = "New Account Application '" + o.AccountAppId + "' has been added.";
    }
    else {
      s = "Account Application '" + o.AccountAppId + "' has been updated.";
    }
    if (o.ImageError) s += "\n\nWARNING: Applicant image was not saved. The following reason was given:\n\n" + o.ImageError;
    
    // Alert
    widget.UI.MsgBoxAlert(s, {}, tabWizard_Cancel);
  }
  else {
    // Close/ Reset
    tabWizard_Cancel(); 
  }  

  // Show Account Application record (after closing Widget to avoid notification on Web)
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountApps&amp;id=" + o.AccountAppId);
}

function Finish_Fail(errorMessage) {
  // Error Message
  widget.UI.MsgBoxAlert(errorMessage);

  // Enable Form
  frmMain.FormEnable();
}

// ===========================
// Page Identification Refresh
// ===========================
function pageIdentification_Refresh() {
  // Change Events
  dateDL_DateOfBirth_Change();
  cboDL_SpecialType_Change();
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "Application":
      // Application
      C.cboPurpose.WidthResizeFromParent();
      C.wbAccountSummary.ResizeFromParent();
      break;

    case "Applicant":
      // Applicant
      C.txtPreferredName.WidthResizeFromParent();

      C.txtPhone.WidthResizeFromParent();
      C.txtMobile.WidthResizeFromParent();
      C.txtEmail.WidthResizeFromParent();

      C.txtStreetAddress_Postal.WidthResizeFromParent();
      C.txtSuburb_Postal.WidthResizeFromParent();
      C.txtCity_Postal.WidthResizeFromParent();
      C.txtState_Postal.WidthResizeFromParent();
      C.txtPostcode_Postal.WidthResizeFromParent();
      C.txtCountry_Postal.WidthResizeFromParent();

      C.txtStreetAddress_Physical.WidthResizeFromParent();
      C.txtSuburb_Physical.WidthResizeFromParent();
      C.txtCity_Physical.WidthResizeFromParent();
      C.txtState_Physical.WidthResizeFromParent();
      C.txtPostcode_Physical.WidthResizeFromParent();
      C.txtCountry_Physical.WidthResizeFromParent();
      break;

    case "Identification":
      // Identification
      C.cboDL_SpecialType.WidthResizeFromParent();
      C.txtDL_NameFamily.WidthResizeFromParent();
      C.txtDL_NameOther.WidthResizeFromParent();
      C.txtDL_Value.WidthResizeFromParent();
      break;

    case "Image":
      // Image
      break;
  }
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

function tabWizard_UpdateButtons() {
  // Back, Next, Finish Buttons Valid?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 0);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
  cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

  // Exceptions
  if (!mAllowImageUpload &amp;&amp; tabIndex == 1) {
    cmdNext.prop("disabled", true);
  }
  cmdFinish.prop("disabled", false);
  if (mAccountApp &amp;&amp; !mAccountApp.IsNew) cmdFinish.text("Update")
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "Image":
          // Only allow Image Upload if Document Manager is available
          if (mAllowImageUpload) found = true;
          break;

        default:
          found = true;
          break;
      }

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

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

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

      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 "Client":
        // Has server-side validation
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "Client":
        params = {
          clientId: C.cboClient.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()) {
      default:
        break;
    }

    // Callback
    validCallback();
  }
}

function tabWizard_ValidateFail(errorMessage)
{
  // Error Message
  widget.UI.MsgBoxAlert(errorMessage);

  // Enable form
  frmMain.FormEnable();
}

// ======================
// Update Account Summary
// ======================
function UpdateAccountSummary() {
  // Save Fields
  Fields_Save();

  // Clear Summary
  C.wbAccountSummary.Clear();

  // Fetch Summary
  widget.GetString("GetAccountSummary", mAccountApp, UpdateAccountSummary_Done);
}

function UpdateAccountSummary_Done(data) {
  C.wbAccountSummary.SetContent(data, false);
}

// ==============
// Preload Client
// ==============
function ClientPreload() {
  var clientId = C.cboClient.Text();
  var message = "";

  // Validate
  if (!clientId) {
    widget.UI.MsgBoxAlert("Please enter the Id of an existing Client.", {}, function() { C.cboClient.Focus(); });
    return;
  }

  // Confirm
  if (mClientIdOriginal &amp;&amp; mClientIdOriginal != clientId) {
    message = "Applicant was previously preloaded from Client '" + mClientIdOriginal + "'.\n\nOverwrite existing Applicant details with details from Client '" + clientId + "'?";
  }
  else {
    message = "Overwrite existing Applicant details with details from Client '" + clientId + "'?";
  }

  // Confirm
  widget.UI.MsgBoxConfirm(message, {}, ClientPreload_Post);
}

function ClientPreload_Post() {
  // Block UI
  widget.UI.Block("Preloading details from Client.");

  // Preload Client
  widget.GetString("ClientPreload", { clientId: C.cboClient.Text() }, ClientPreload_Done, ClientPreload_Fail);
}

function ClientPreload_Done(data) {
  // Preload
  Fields_Load_Applicant(JSON.parse(data));

  // Unblock
  widget.UI.Unblock();

  // Move Next
  tabWizard_Move(1);
}

function ClientPreload_Fail(errorMessage) {
  // Reset
  C.cboClient.Text(mClientIdOriginal);

  // Unblock
  widget.UI.Unblock();

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

// ==================
// dateDL_DateOfBirth
// ==================
function dateDL_DateOfBirth_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  if (!C.dateDateOfBirth.Value() || !C.dateDL_DateOfBirth.Value()) {
    C.lblDOBWarning.Visible(false);
  }
  else if (widget.CompareDates(C.dateDateOfBirth.Value(), C.dateDL_DateOfBirth.Value()) == 0) {
    C.lblDOBWarning.Visible(false);
  }
  else {
    C.lblDOBWarning.Visible(true);
  }
}

// ==========
// Scan Image
// ==========
function ScanImage() {
  if (C.fileIdImage[0].GetFiles().length == 0) {
    // Nothing selected
  }
  else {
    // Block UI
    widget.UI.Block("Scanning Identification Image...");

    // Scan Image
    widget.UploadFiles("ScanImage", {}, C.fileIdImage[0], ScanImage_Done, ScanImage_Fail);
  }
}

function ScanImage_Done(data) {
  // Enable Form
  widget.UI.Unblock();

  // Parse Data
  var o = {};
  if (data) o = JSON.parse(data);

  // Prompt to Update
  if (o.FirstName || o.LastName) {
    widget.UI.MsgBoxConfirm("Do you want to update Applicant and Identification details with those detected on the scanned image?", {}, function() {
      // Applicant
      if (o.FirstName) C.txtFirstName.Text(o.FirstName);
      if (o.MiddleNames) C.txtMiddleNames.Text(o.MiddleNames);
      if (o.LastName) C.txtLastName.Text(o.LastName);
      if (o.DateOfBirth) C.dateDateOfBirth.Value(o.DateOfBirth);
      if (o.Gender) C.cboGender.Text(o.Gender);
      if (o.StreetAddressFull) {
        C.txtStreetAddress_Postal.Text(o.StreetAddressFull);
        C.txtSuburb_Postal.Text(o.Suburb);
        C.txtCity_Postal.Text(o.City);
        C.txtState_Postal.Text(o.State);
        C.txtPostcode_Postal.Text(o.Postcode);
        C.txtCountry_Postal.Text(o.Country);
      }

      // Applicant - Drivers Licence
      C.cboDL_SpecialType.Text(o.DL_SpecialType);
      C.txtDL_NameFamily.Text(o.DL_NameFamily);
      C.txtDL_NameOther.Text(o.DL_NameOther);
      C.txtDL_Value.Text(o.DL_Value);
      C.cboDL_State.Text(o.DL_State);
      C.txtDL_Version.Text(o.DL_Version);
      C.dateDL_DateOfBirth.Value(o.DL_DateOfBirth);
      C.dateDL_Expiry.Value(o.DL_Expiry);

      // Change Events
      cboDL_SpecialType_Change();

      // Move Next
      tabWizard_Move(1);
    });
  }
}

function ScanImage_Fail(errorMessage) {
  // Error Message
  widget.UI.MsgBoxAlert(errorMessage);

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

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

  // Hide all country-specific fields
  C.cboDL_State.VisibleRow(false);
  C.txtDL_Version.VisibleRow(false);

  // Clear all country-specific fields
  if (e) {
    C.cboDL_State.Text("");
    C.txtDL_Version.Text("");
  }

  // Change
  switch (C.cboDL_SpecialType.Text().toUpperCase()) {
    case "":
    case "NONE":
      C.tbLicenceDetails.hide();
      break;

    case "AU DRIVERS LICENCE":
      C.cboDL_State.VisibleRow(true);
      if (mRecord) C.cboDL_State.RefreshFromCodeDescriptionList(mRecord.List_States_AU);
      C.tbLicenceDetails.show();
      break;

    case "NZ DRIVERS LICENCE":
      C.txtDL_Version.VisibleRow(true);
      C.tbLicenceDetails.show();
      break;

    case "US DRIVERS LICENCE":
      C.cboDL_State.VisibleRow(true);
      if (mRecord) C.cboDL_State.RefreshFromCodeDescriptionList(mRecord.List_States_US);
      C.tbLicenceDetails.show();
      break;
  }
}

// ===============================
// chkPostalAndPhysicalAddressSame
// ===============================
function chkPostalAndPhysicalAddressSame_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Change
  if (C.chkPostalAndPhysicalAddressSame.Value())
    $("#tbodyPhysicalAddress").hide();
  else
    $("#tbodyPhysicalAddress").show();

  // Resize Tab
  tabWizard_Resize();
}

&lt;/script&gt;</TemplateText>
  <TemplateTextBookmarks />
  <TimeoutSeconds>60</TimeoutSeconds>
  <UniqueId>pPnjpSutMkmB5hifHiHCpQ</UniqueId>
  <AllowRefresh>true</AllowRefresh>
  <Caption>Sample Account Application</Caption>
  <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
  <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
  <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
  <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
  <HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2>
  <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
  <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
  <HtmlWidgetResourceJQueryVersion />
  <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
  <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="ReadOnly" type="Boolean">
          <BlankTip />
          <Caption />
          <StandaloneOnly>false</StandaloneOnly>
          <TooltipText />
          <DefaultValueExpression />
          <Enabled>true</Enabled>
          <HideDescription>false</HideDescription>
          <IndentLevel>0</IndentLevel>
          <NonPersistable>false</NonPersistable>
          <ReadOnly>false</ReadOnly>
          <ReadOnly2>false</ReadOnly2>
          <Value>False</Value>
          <Visible>true</Visible>
        </Parameter>
        <Parameter name="OcrImageMaxWidth" 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="" type="SectionStart">
          <BlankTip />
          <Caption>TESTING</Caption>
          <StandaloneOnly>false</StandaloneOnly>
          <TooltipText />
          <SectionColumns>1</SectionColumns>
          <Visible>true</Visible>
        </Parameter>
        <Parameter name="AccountAppPk" 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="AccountAppTypeId" 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.AccountAppTypes</List>
          <LimitToList>false</LimitToList>
          <MaxLength>0</MaxLength>
          <Rows>1</Rows>
        </Parameter>
      </Parameters>
    </ISParameterDefs>
  </Parameters>
</finScript></Scripts></finPOWERConnect>