<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-08-23T04:41:59.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-09-10T04:39:37.4070000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2023-08-23T04:41:21.6970000</UpdatedUtcDate>
    <ScriptId>CBD</ScriptId>
    <Description>Client Banking Details</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ClientBankAccount
Option Explicit On
Option Strict On

' #################################################################
' Client Banking Details wizard HTML Widget
'
' Version: 1.09 (23/08/2023)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.04  23/08/2021  ISS      J027108   Added Icons to Split buttons
'    1.05  10/09/2021  ISS      J027343   Rebranded 'Split' to 'Zepto'
'    1.06  20/10/2021  ISS      J027605   Bank Sort Code review
'    1.07  01/04/2022  ISS      J028509   Improved Zepto functionality
'    1.08  12/01/2023  ISS      J030299   Added support for Zepto NZ
'                      ISS      J030301   Added support for cancelling a Zepto Contract
'          10/02/2023  ISS      J030332   Zepto Account Numbers are now formatted on entry
'    1.09  04/07/2023  ISS      J030481   New Bank Accounts will be prompted if a Zepto contact has been created but the wizard is being cancelled
'          23/08/2023  ISS      J030467   Fixed control resizing issue when creating a new Zepto contact
' #################################################################

' Constants
Private Const FORM_KEY As String = "ClientBankAccount"

' Common Parameters
Private mClientBankAccountPk As Integer
Private mClientId As String
Private mReadOnly As Boolean

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

Public Function Main(eventId As String, parametersJson As String, startUpParametersJson As String, hostingContext As isefinHtmlWidgetHostingContext, requestInfo As finScriptRequestInfo, ByRef returnValue As String) As Boolean

  ' Assume Success
  Main = True

  ' Get Parameters
  mParameters = finBL.CreateKeyValueList()
  mParameters.FromSimpleJsonString(parametersJson)
  mStartupParameters = finBL.CreateKeyValueList()
  mStartupParameters.FromSimpleJsonString(startUpParametersJson)

  ' Get Combined Parameters (Startup Parameters updated with event Parameters)
  mCombinedParameters = mStartupParameters.Clone()
  mCombinedParameters.UpdateFromKeyValueList(mParameters, True)

  ' Get Common Parameters
  With mCombinedParameters
    mClientId = .GetString("ClientId")
    mClientBankAccountPk = .GetInteger("ClientBankAccountPk")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

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

    Case "Delete"
      ' Delete Bank Account
      Main = Delete()

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

    Case "GetBankInterfaceDetails_Zepto"
      ' Get Bank Interface Details - Zepto
      Main = GetBankInterfaceDetails_Zepto(returnValue)

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

    Case "Zepto_CreateContact"
      ' Zepto - Create Contact
      Main = Zepto_CreateContact(returnValue)

    Case "Zepto_DeleteContact"
      ' Zepto - Delete Contact
      Main = Zepto_DeleteContact(returnValue)
      
    Case "Zepto_VerifyContact"
      ' Zepto - Verify Contact      
      Main = Zepto_VerifyContact(returnValue, Nothing)

    Case "ValidateBankingDetails"
      ' Validate Banking Details
      Main = ValidateBankingDetails(returnValue)

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

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

End Function

''' &lt;summary&gt;
'''  Delete Bank Account.
''' &lt;/summary&gt;
Private Function Delete() As Boolean

  Dim Client As finClient
  Dim ClientBankAccount As finClientBankAccount
  Dim OriginalTimestamp As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Bank Account and Client
  Success = GetClientBankAccount(ClientBankAccount, Client)

  ' Remove Banking Details
  If Success Then
    Success = Client.BankAccounts.Remove(ClientBankAccount)
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Commit changes.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        ByRef returnValue As String) As Boolean

  Dim BankingDetails As finBankingDetails
  Dim Client As finClient
  Dim ClientBankAccount As finClientBankAccount
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Index As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, FormInitialisationInfo)

  ' Get Bank Account and Client
  If Success Then
    Success = GetClientBankAccount(ClientBankAccount, Client)
  End If

  ' Get Banking Details
  If Success Then
    BankingDetails = finBL.CreateBankingDetails()
    Success = BankingDetails.FromHtmlWidgetJsonString(FormInitialisationInfo.BankingDetailsJson)
  End If

    ' Move?
  If Success Then
    Select Case FormInitialisationInfo.MoveAction
      Case "MoveTop"
        Index = Client.BankAccounts.IndexOf(ClientBankAccount)
        If Index &gt; 0 Then Success = Client.BankAccounts.Move(Index, 0)
    End Select
  End If

  ' Update and Save
  If Success Then
    With ClientBankAccount
      .FromBankingDetails(BankingDetails)
      .AccountClosed = FormInitialisationInfo.AccountClosed
      .CreditLimit = FormInitialisationInfo.CreditLimit
      .DateStart = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(FormInitialisationInfo.DateStart)
      .DateStop = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(FormInitialisationInfo.DateStop)
      .DebitLimit = FormInitialisationInfo.DebitLimit
      .FriendlyName = FormInitialisationInfo.FriendlyName
      .Notes = FormInitialisationInfo.Notes
      .ShowExternally = FormInitialisationInfo.ShowExternally
    End With

    ' Add new
    If mClientBankAccountPk = -1 Then
      Success = Client.BankAccounts.Insert(0, ClientBankAccount)
    End If
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Retrieve Bank Interface Details for Zepto (formerly Split Payments).
''' &lt;/summary&gt;
Private Function GetBankInterfaceDetails_Zepto(ByRef returnValue As String) As Boolean

  Dim BankingInterfacePaymentMethods As List(Of BankingInterfacePaymentMethod)
  Dim Client As finClient
  Dim Data As Object
  Dim EmailAddresses As String
  Dim MessagingContacts As finMessagingContacts
  Dim PaymentMethodRO As finPaymentMethodRO
  Dim PhoneNumbers As String
  Dim Success As Boolean
  Dim ValidationData As String

  ' Assume Success
  Success = True

  ' Initialise
  BankingInterfacePaymentMethods = New List(Of BankingInterfacePaymentMethod)
  MessagingContacts = finBL.CreateMessagingContacts()

  ' Get Client
  Success = GetClientBankAccount(Nothing, Client)

  ' Get list of Email addresses
  If Success Then
    With MessagingContacts
      If .LoadClient_Email(Client) Then
        EmailAddresses = .GetListReadonly().ToCsvString()
      End If
    End With
  End If

  ' Get list of Phone Numbers (NZ only)
  If Success AndAlso finBL.CountryCode = "NZ" Then
    With MessagingContacts
      If .LoadClient_Sms(Client) Then
        PhoneNumbers = .GetListReadonly().ToCsvString()
      End If
    End With
  End If
  
  ' Get Zepto Payment Methods
  If Success Then
    For Each PaymentMethodRO In finBL.PaymentMethods
      If PaymentMethodRO.Active Then                
        Select Case PaymentMethodRO.PaymentTypeCategory
          Case isefinPaymentTypeCategory.Split, isefinPaymentTypeCategory.ZeptoNZ
            BankingInterfacePaymentMethods.Add(New BankingInterfacePaymentMethod(PaymentMethodRO))
        End Select
      End If
    Next
  End If

  ' Initial Validation
  If Success Then
    Success = ValidateBankingDetails(ValidationData)
  End If

  ' Get Data
  If Success Then
    Data = New With {
      .EmailAddresses = EmailAddresses,
      .PhoneNumbers = PhoneNumbers,
      .ZeptoPaymentMethods = BankingInterfacePaymentMethods,
      .ValidationData = ValidationData
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Returns a Client Bank Account.
''' &lt;/summary&gt;
Private Function GetClientBankAccount(ByRef clientBankAccount As finClientBankAccount,
                             Optional ByRef client As finClient = Nothing) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  client = Nothing
  clientBankAccount = Nothing

  If mClientBankAccountPk &lt;&gt; 0 Then
    ' Load Client
    client = finBL.CreateClient()
    If client.Load(mClientId) Then
      If client.IsNew Then
        Success = False
        finBL.Error.ErrorBegin("Client must be saved before adding Banking Details.")
      End If
    Else
      Success = False
    End If

    ' Get Bank Account Pk
    If Success Then
      If mClientBankAccountPk &gt; 0 Then
        If client.BankAccounts.ExistsPk(mClientBankAccountPk) Then
          clientBankAccount = client.BankAccounts.ItemByPk(mClientBankAccountPk)
        Else
          Success = False
          finBL.Error.ErrorBegin("Failed to retrieve Client Banking Details. This record may have been deleted by another User.")
        End If
      Else
        clientBankAccount = client.BankAccounts.CreateClientBankAccount()
      End If
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Initialisation Information required for this wizard.
''' &lt;/summary&gt;
Private Function GetInitialisationInfo(ByRef returnValue As String) As Boolean

  Dim BankInterfaceList As ISList
  Dim ClientBankAccount As finClientBankAccount
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  BankInterfaceList = New ISList()

  ' Validate
  If Len(mClientId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Client Id not specified.")
  ElseIf mClientBankAccountPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Client Bank Account Pk not specified.")
  ElseIf mClientBankAccountPk &lt; -1 Then
    Success = False
    finBL.Error.ErrorBegin("Invalid Bank Account Pk.")
  ElseIf finBL.CurrentUserInformation.IsClientFilteredOut(mClientId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Client.")
  End If

  ' Get Client Bank Account
  If Success Then
    Success = GetClientBankAccount(ClientBankAccount)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      If (finBL.Database.IsReadOnly OrElse mReadOnly) AndAlso Not finBL.CurrentUser.Permissions.Allow("Banking.ShowUnmaskedAccountDetails") Then
        ' Not editing so obfuscate details
        .BankingDetailsJson = ClientBankAccount.ToBankingDetailsForDisplay(True).ToHtmlWidgetJsonString()
        .BankingDetailsObfuscated = True
      Else
        .BankingDetailsJson = ClientBankAccount.ToBankingDetails().ToHtmlWidgetJsonString()
      End If
      .AccountClosed = ClientBankAccount.AccountClosed
      .CreditLimit = ClientBankAccount.CreditLimit
      .DateStart = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(ClientBankAccount.DateStart)
      .DateStop = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(ClientBankAccount.DateStop)
      .DebitLimit = ClientBankAccount.DebitLimit
      .FriendlyName = ClientBankAccount.FriendlyName
      .IsNew = ClientBankAccount.IsNew
      .Notes = ClientBankAccount.Notes
      .ShowExternally = ClientBankAccount.ShowExternally
      .Timestamp = ClientBankAccount.Timestamp

      ' Default Bank Interface
      If ClientBankAccount.PaymentType IsNot Nothing AndAlso ClientBankAccount.PaymentType.IsBankInterface Then
        Select Case ClientBankAccount.PaymentType.PaymentTypeCategory
          Case isefinPaymentTypeCategory.Split, isefinPaymentTypeCategory.ZeptoNZ
            .BankingInterface = "ZEPTO"

          Case Else
            Success = False
            finBL.Error.ErrorBeginFormat("Bank Interface '{0}' is not supported.", finBL.Enums.isefinPaymentTypeCategory_ToString(ClientBankAccount.PaymentMethod.PaymentType.PaymentTypeCategory))
        End Select
      Else
        .BankingInterface = "STANDARD"
      End If

      ' Lists
      .BankingInterfaces.Add(New BankingInterface("Standard Bank", "STANDARD"))
      If finBL.PaymentMethods.HasPaymentType(isefinPaymentTypeCategory.Split) OrElse finBL.PaymentMethods.HasPaymentType(isefinPaymentTypeCategory.ZeptoNZ) OrElse .BankingInterface = "ZEPTO" Then
        If finBL.CountryCode = "AU" Then
          .BankingInterfaces.Add(New BankingInterface("Zepto (formerly Split Payments) Bank Account Contact", "ZEPTO"))
        Else 
          .BankingInterfaces.Add(New BankingInterface("Zepto Bank Account Contact", "ZEPTO"))
        End If        
      End If

      ' Terminology
      .SupportsBankSortCode = finBL.CurrentCountry.SupportsBankSortCode
      .TerminologyAccountSortCode = finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode)

      ' Configuration

      ' Read only
      If finBL.Database.IsReadOnly OrElse mReadOnly Then
        .ReadOnly = True
      ElseIf .IsNew Then
        .ReadOnly = (Not finBL.CurrentUser.Permissions.Allow("Client.BankAccounts.Add"))
      Else
        .ReadOnly = (Not finBL.CurrentUser.Permissions.Allow("Client.BankAccounts.Update"))
      End If

      ' Can Delete
      .CanDelete = finBL.CurrentUser.Permissions.Allow("Client.BankAccounts.Delete")
      .CountryCode = finBL.CountryCode
      If .ReadOnly OrElse .IsNew Then .CanDelete = False

      ' Form Heading
      .FormHeading = ScriptInfo.ScriptCaption
      If Len(.FormHeading) = 0 Then .FormHeading = "Client Banking Details"
      If .IsNew Then .FormHeading = "New " &amp; .FormHeading

      ' Other
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Wizard Finish Parameters
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef formInitialisationInfo As FormInitialisationInfo) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  formInitialisationInfo = Nothing

  ' Wizard Finish Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(FormInitialisationInfo), obj) Then
    formInitialisationInfo = DirectCast(obj, FormInitialisationInfo)
  Else
    Success = False
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Creates a Zepto Contact.
''' &lt;/summary&gt;
Private Function Zepto_CreateContact(ByRef returnValue As String) As Boolean
  
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Create Contact
  Select Case finBL.CountryCode
    Case "AU": Success = Zepto_CreateContact_AU(returnValue)
    Case "NZ": Success = Zepto_CreateContact_NZ(returnValue)
  End Select
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Creates a Zepto AU Contact.
''' &lt;/summary&gt;
Private Function Zepto_CreateContact_AU(ByRef returnValue As String) As Boolean

  Dim AccountName As String
  Dim AccountNumber As String
  Dim AccountSortCode As String
  Dim Client As finClient
  Dim ContactId As String
  Dim Data As Object
  Dim Email As String
  Dim PaymentMethod As finPaymentMethodRO
  Dim PaymentMethodId As String
  Dim Success As Boolean
  Dim ValidationData As String

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    AccountName = .GetString("AccountName")
    AccountNumber = .GetString("AccountNumber")
    AccountSortCode = .GetString("AccountSortCode")
    Email = .GetString("Email")
    PaymentMethodId = .GetString("PaymentMethodId")
  End With

  ' Payment Method
  If finBL.PaymentMethods.Exists(PaymentMethodId) Then
    PaymentMethod = finBL.PaymentMethods(PaymentMethodId)
  End If

  ' Validate
  If finBL.BankingInterface.Service_Split Is Nothing Then
    Success = False
    finBL.Error.ErrorBegin("The 'Zepto' Service is not available.")  
  ElseIf PaymentMethod Is Nothing Then
    Success = False
    finBL.Error.ErrorBegin("Payment Method not specified.")
  ElseIf Len(PaymentMethod.BankAccountId) = 0 OrElse PaymentMethod.PaymentTypeCategory &lt;&gt; isefinPaymentTypeCategory.Split Then
    Success = False
    finBL.Error.ErrorBegin("Invalid Payment Method.")
  ElseIf Len(AccountNumber) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Bank Account Number not specified.")
  End If

  ' Get Client
  If Success Then
    Success = GetClientBankAccount(Nothing, Client)
  End If

  ' Create Contact
  If Success Then
    Select Case PaymentMethod.PaymentFlowDirection
      Case isefinPaymentMethodPaymentFlowDirection.Incoming
        Success = finBL.BankingInterface.Service_Split.CreateKycAgreementFromClient(Client, PaymentMethod, AccountName, AccountSortCode, AccountNumber, Email, True, ContactId)

      Case isefinPaymentMethodPaymentFlowDirection.Outgoing
        Success = finBL.BankingInterface.Service_Split.CreateAnyoneContactFromClient(Client, PaymentMethod, AccountName, AccountSortCode, AccountNumber, Email, ContactId)
    End Select
  End If

  ' Re-validate
  If Success Then
    ' Set Parameters
    With mCombinedParameters
      .SetString("AccountName", AccountName)
      .SetString("AccountNumber", AccountNumber)
      .SetString("AccountSortCode", AccountSortCode)
      .SetString("AccountEmail", Email)
      .SetString("ExternalId", ContactId)
      .SetString("PaymentMethodId", PaymentMethodId)
    End With

    ' Ignore if this fails
    ValidateBankingDetails(ValidationData)
  End If

  ' Build Object
  If Success Then
    Data = New With {
      .AccountName = AccountName,
      .Email = Email,
      .ContactId = ContactId,
      .ValidationData = ValidationData,
      .ValidFromDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Deletes a Zepto Contact.
''' &lt;/summary&gt;
Private Function Zepto_DeleteContact(ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Verify
  Select Case finBL.CountryCode
    Case "AU": Success = Zepto_DeleteContact_AU(returnValue)
    Case "NZ": Success = Zepto_DeleteContact_NZ(returnValue)
  End Select
  
  Return Success
                                     
End Function

''' &lt;summary&gt;
'''  Deletes a Zepto AU Contact.
''' &lt;/summary&gt;
Private Function Zepto_DeleteContact_AU(ByRef returnValue As String) As Boolean
  
  Dim ClientPk As Integer
  Dim ContactId As String
  Dim Data As Object
  Dim PaymentMethodId As String
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise

  ' Parameters
  With mCombinedParameters
    PaymentMethodId = .GetString("PaymentMethodId")
    ContactId = .GetString("ContactId")
  End With

  ' Validate
  If Success Then
    If finBL.BankingInterface.Service_Split Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("The 'Zepto' Service is not available.")
    ElseIf Not finBL.PaymentMethods.Exists(PaymentMethodId) Then
      Success = False
      finBL.Error.ErrorBegin("Invalid Payment Method.")
    End If
  End If

  ' Get Details
  If Success Then
    Success = finBL.Database.GetPkFromId("Client", mClientId, ClientPk)
  End If
  
  ' Delete
  If Success Then
    Success = finBL.BankingInterface.Service_Split.DeleteContact(finBL.PaymentMethods(PaymentMethodId).BankAccountPk, ContactId, 0, ClientPk)
  End If
  
  ' Get return data
  If Success Then
    Data = New With {
      .ValidToDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Deletes a Zepto NZ Contact.
''' &lt;/summary&gt;
Private Function Zepto_DeleteContact_NZ(ByRef returnValue As String) As Boolean
  
  Dim ClientPk As Integer
  Dim ContactId As String
  Dim Data As Object
  Dim PaymentMethodId As String
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise

  ' Parameters
  With mCombinedParameters
    PaymentMethodId = .GetString("PaymentMethodId")
    ContactId = .GetString("ContactId")
  End With

  ' Validate
  If Success Then
    If finBL.BankingInterface.Service_ZeptoNZ Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("The 'Zepto' Service is not available.")
    ElseIf Not finBL.PaymentMethods.Exists(PaymentMethodId) Then
      Success = False
      finBL.Error.ErrorBegin("Invalid Payment Method.")
    End If
  End If

  ' Get Details
  If Success Then
    Success = finBL.Database.GetPkFromId("Client", mClientId, ClientPk)
  End If
  
  ' Delete
  If Success Then
    Success = finBL.BankingInterface.Service_ZeptoNZ.DeleteContact(finBL.PaymentMethods(PaymentMethodId).BankAccountPk, ContactId, 0, ClientPk)
  End If
  
  ' Get return data
  If Success Then
    Data = New With {
      .ValidToDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Verifies a Zepto Contact.
''' &lt;/summary&gt;
Private Function Zepto_VerifyContact(ByRef returnValue As String,
                                     ByRef validationItems As ISValidationItems) As Boolean

  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Verify
  Select Case finBL.CountryCode
    Case "AU": Success = Zepto_VerifyContact_AU(returnValue, validationItems)
    Case "NZ": Success = Zepto_VerifyContact_NZ(returnValue, validationItems)
  End Select
  
  Return Success
                                     
End Function

''' &lt;summary&gt;
'''  Verifies a Zepto AU Contact.
''' &lt;/summary&gt;
Private Function Zepto_VerifyContact_AU(ByRef returnValue As String,
                                        ByRef validationItems As ISValidationItems) As Boolean

  Dim BankingDetails As finBankingDetails
  Dim BankingDetailsJson As String
  Dim ServiceLogPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  BankingDetails = finBL.CreateBankingDetails()

  ' Parameters
  With mCombinedParameters
    BankingDetailsJson = .GetString("BankingDetailsJson")
  End With

  ' Validate
  If Success Then
    If finBL.BankingInterface.Service_Split Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("The 'Zepto' Service is not available.")
    End If
  End If

  ' Build Banking Details
  If Success Then
    Success = BankingDetails.FromHtmlWidgetJsonString(BankingDetailsJson)
  End If

  ' Verify and return result
  If Success Then
    If finBL.BankingInterface.Service_Split.VerifyContact(BankingDetails, True, ServiceLogPk, validationItems, "", mClientId) Then
      Success = finBL.BankingInterface.GetHtmlFromServiceLog(ServiceLogPk, returnValue)
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Creates a Zepto NZ Contact.
''' &lt;/summary&gt;
Private Function Zepto_CreateContact_NZ(ByRef returnValue As String) As Boolean

  Dim AccountName As String
  Dim AccountNumber As String
  Dim Client As finClient
  Dim ContactId As String
  Dim Data As Object
  Dim Email As String
  Dim PaymentMethod As finPaymentMethodRO
  Dim PaymentMethodId As String
  Dim Phone As String
  Dim Success As Boolean
  Dim ValidationData As String

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    AccountName = .GetString("AccountName")
    AccountNumber = .GetString("AccountNumber")    
    Email = .GetString("Email")
    Phone = .GetString("Phone")
    PaymentMethodId = .GetString("PaymentMethodId")
  End With

  ' Payment Method
  If finBL.PaymentMethods.Exists(PaymentMethodId) Then
    PaymentMethod = finBL.PaymentMethods(PaymentMethodId)
  End If

  ' Validate
  If finBL.BankingInterface.Service_ZeptoNZ Is Nothing Then
    Success = False
    finBL.Error.ErrorBegin("The 'Zepto' Service is not available.")  
  ElseIf PaymentMethod Is Nothing Then
    Success = False
    finBL.Error.ErrorBegin("Payment Method not specified.")
  ElseIf Len(PaymentMethod.BankAccountId) = 0 OrElse PaymentMethod.PaymentTypeCategory &lt;&gt; isefinPaymentTypeCategory.ZeptoNZ Then
    Success = False
    finBL.Error.ErrorBegin("Invalid Payment Method.")
  ElseIf Len(AccountNumber) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Bank Account Number not specified.")
  End If

  ' Get Client
  If Success Then
    Success = GetClientBankAccount(Nothing, Client)
  End If

  ' Create Contact
  If Success Then
    Select Case PaymentMethod.PaymentFlowDirection
      Case isefinPaymentMethodPaymentFlowDirection.Incoming
        Success = finBL.BankingInterface.Service_ZeptoNZ.CreateKycAgreementFromClient(Client, PaymentMethod, AccountName, AccountNumber, Email, Phone, True, ContactId)

      Case isefinPaymentMethodPaymentFlowDirection.Outgoing
        Success = finBL.BankingInterface.Service_ZeptoNZ.CreateAnyoneContactFromClient(Client, PaymentMethod, AccountName, AccountNumber, Email, Phone, ContactId)
    End Select
  End If

  ' Re-validate
  If Success Then
    ' Set Parameters
    With mCombinedParameters
      .SetString("AccountName", AccountName)
      .SetString("AccountNumber", AccountNumber)
      .SetString("AccountEmail", Email)
      .SetString("AccountPhone", Phone)
      .SetString("ExternalId", ContactId)
      .SetString("PaymentMethodId", PaymentMethodId)
    End With

    ' Ignore if this fails
    ValidateBankingDetails(ValidationData)
  End If

  ' Build Object
  If Success Then
    Data = New With {
      .AccountName = AccountName,
      .Email = Email,
      .Phone = Phone,
      .ContactId = ContactId,
      .ValidationData = ValidationData,
      .ValidFromDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Verifies a Zepto NZ Contact.
''' &lt;/summary&gt;
Private Function Zepto_VerifyContact_NZ(ByRef returnValue As String,
                                        ByRef validationItems As ISValidationItems) As Boolean

  Dim BankingDetails As finBankingDetails
  Dim BankingDetailsJson As String
  Dim ServiceLogPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  BankingDetails = finBL.CreateBankingDetails()

  ' Parameters
  With mCombinedParameters
    BankingDetailsJson = .GetString("BankingDetailsJson")
  End With

  ' Validate
  If Success Then
    If finBL.BankingInterface.Service_ZeptoNZ Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("The 'Zepto' Service is not available.")
    End If
  End If

  ' Build Banking Details
  If Success Then
    Success = BankingDetails.FromHtmlWidgetJsonString(BankingDetailsJson)
  End If

  ' Verify and return result
  If Success Then
    If finBL.BankingInterface.Service_ZeptoNZ.VerifyContact(BankingDetails, True, ServiceLogPk, validationItems, "", mClientId) Then
      Success = finBL.BankingInterface.GetHtmlFromServiceLog(ServiceLogPk, returnValue)
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validates Banking Details.
''' &lt;/summary&gt;
Private Function ValidateBankingDetails(ByRef returnValue As String) As Boolean

  Dim AccountEmail As String
  Dim AccountName As String
  Dim AccountNumber As String
  Dim AccountPhone As String
  Dim AccountSortCode As String
  Dim BankingDetails As finBankingDetails
  Dim Data As Object
  Dim ExternalId As String
  Dim IsValid As Boolean
  Dim Message As String
  Dim PaymentMethodId As String
  Dim strTemp As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  BankingDetails = finBL.CreateBankingDetails()

  ' Parameters
  With mCombinedParameters
    AccountName = .GetString("AccountName")
    AccountNumber = .GetString("AccountNumber")
    AccountPhone = .GetString("AccountPhone")
    AccountSortCode = .GetString("AccountSortCode")
    AccountEmail = .GetString("AccountEmail")
    ExternalId = .GetString("ExternalId")
    PaymentMethodId = .GetString("PaymentMethodId")
  End With

  ' Build Banking Details and validate
  With BankingDetails
    .AccountEmail = AccountEmail
    .AccountName = AccountName
    .AccountNumber = AccountNumber
    .AccountPhone = AccountPhone
    .AccountSortCode = AccountSortCode
    .ExternalId = ExternalId
    .PaymentMethodId = PaymentMethodId

    IsValid = .IsValid(False)
  End With

  ' Attempt to format Bank Account
  finBL.CurrentCountry.ValidateBankBranch(BankingDetails, "")
  finBL.CurrentCountry.ValidateBankAccount(BankingDetails, "") 
  If finBL.CurrentCountry.SupportsBankSortCode Then
    finBL.CurrentCountry.ValidateBankAccountSortCode(BankingDetails, "") 
  End If
  
  ' Format Message
  If IsValid Then    
    With BankingDetails
      If Len(.BankName) = 0 Then
        Message = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankNameShort, .BankBranchName)
      Else
        Message = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankName &amp; " (" &amp; .BankNameShort &amp; ")", .BankBranchName)
      End If
    End With
  Else
    Message = finBL.Error.Message(True, False, True)
  End If

  ' Clear rogue new lines for string comparison
  strTemp = Replace(Message, vbNewLine, "")

  ' Build Object
  If Success Then
    Data = New With {
      .AccountNumberFormatted = BankingDetails.AccountNumber,
      .AccountSortCodeFormatted = BankingDetails.AccountSortCode,
      .IsError = (Not IsValid),
      .Message = Message,
      .ErrorIsOnlyContactId = (strTemp = "Zepto Contact Id is blank" OrElse strTemp = "1. Zepto Contact Id is blank")
    }
  End If

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

  Return Success

End Function

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

  Dim BankingDetailsForValidation As finBankingDetails
  Dim BankingDetailsJson As String
  Dim ClientBankAccount As finClientBankAccount
  Dim ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Html As String
  Dim PageId As String
  Dim Success As Boolean
  Dim Timestamp As Integer
  Dim Warning As ISValidationItem
  Dim Warnings As ISValidationItems

  ' Assume Success
  Success = True

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    BankingDetailsJson = .GetString("BankingDetailsJson")
    PageId = .GetString("PageId")
    Timestamp = .GetInteger("Timestamp")
  End With

  ' Validate Page
  Select Case PageId
    Case "General"
      ConfirmList = New List(Of String)
      Success = GetWizardFinishParameters(parametersJson, FormInitialisationInfo)

      ' Validate Banking Details
      If Success Then
        BankingDetailsForValidation = finBL.CreateBankingDetails()

        ' Validate Banking Details
        If Success Then
          If BankingDetailsForValidation.FromHtmlWidgetJsonString(FormInitialisationInfo.BankingDetailsJson) Then
            If Not BankingDetailsForValidation.IsValid(Warnings) Then
              For Each Warning In Warnings
                ConfirmList.Add(Warning.Message)
              Next
            End If
          Else
            Success = False
          End If
        End If

        ' Timestamp
        If mClientBankAccountPk &lt;&gt; -1 Then
          If GetClientBankAccount(ClientBankAccount) Then
            If ClientBankAccount.Timestamp &lt;&gt; Timestamp Then
              FailedMessage = "Cannot update Client Banking Details. This record may have been deleted by another User."
            End If
          Else
            Success = False
          End If
        End If

        Data = ConfirmList
      End If

    Case "BankInterface_Zepto"
      ConfirmList = New List(Of String)

      ' Verify Contact
      Success = Zepto_VerifyContact(Html, Warnings)   

      If Success Then
        For Each Warning In Warnings
          ConfirmList.Add(Warning.Message)
        Next
      End If

      Data = ConfirmList
  End Select

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardValidateResponse(Data, FailedMessage, FailedControlId, Html), returnValue)
  End If

  Return Success

End Function


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

  ' Record
  Public AccountClosed As Boolean
  Public BankingDetailsJson As String
  Public BankingDetailsObfuscated As Boolean
  Public BankingInterface As String
  Public CreditLimit As Decimal
  Public DateStart As Date?
  Public DateStop As Date?
  Public DebitLimit As Decimal
  Public FriendlyName As String
  Public IsNew As Boolean
  Public MoveAction As String
  Public Notes As String
  Public ShowExternally As Boolean
  Public Timestamp As Integer

  ' Lists
  Public BankingInterfaces As New List(Of BankingInterface)

  ' Terminology
  Public SupportsBankSortCode As Boolean
  Public TerminologyAccountSortCode As String

  ' Configuration
  Public [ReadOnly] As Boolean
  Public CanDelete As Boolean
  Public CountryCode As String
  Public FormHeading As String
  Public PromptOnSave As Boolean

End Class


''' &lt;summary&gt;
'''  Banking Interface.
''' &lt;/summary&gt;
Public Class BankingInterface

  ' Variables must remain lower case to work with the Radio Button List control
  Public caption As String
  Public value As String

  Public Sub New(caption As String,
                 value As String)

    Me.caption = caption
    Me.value = value

  End Sub

End Class


''' &lt;summary&gt;
'''  Banking Interface Payment Method.
''' &lt;/summary&gt;
Public Class BankingInterfacePaymentMethod

  Public Description As String
  Public Incoming As Boolean
  Public PaymentMethodId As String

  Public Sub New(paymentMethodRO As finPaymentMethodRO)

    With paymentMethodRO
      Me.PaymentMethodId = .PaymentMethodId
      Me.Description = .Description
      Me.Incoming = (.PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Incoming)
    End With

  End Sub

End Class


''' &lt;summary&gt;
'''  Validation details.
''' &lt;/summary&gt;
Public Class WizardValidateResponse

  Public Data As Object
  Public FailedControlId As String
  Public FailedMessage As String
  Public Html As String

  Public Sub New(data As Object,
                 failedMessage As String,
                 failedControlId As String,
                 html As String)

    Me.Data = data
    Me.FailedMessage = failedMessage
    Me.FailedControlId = failedControlId
    Me.Html = html

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes />
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;

.banking-warnings {
  margin-bottom: 0 !important;
  margin-top: 0 !important;
  width: 100%;
}

&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;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="BankingMethod" tooltipText="Select the type of Bank Connection."&gt;Banking Method&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Enter Bank Account/ Credit Card details."&gt;Banking Details&lt;/li&gt;
        &lt;li tabId="BankInterface_Zepto" tooltipText="Enter Zepto Banking and Contact details."&gt;Zepto&lt;/li&gt;
        &lt;li tabId="Summary" tooltipText="Review the information below from the Bank Interface."&gt;Bank Interface Summary&lt;/li&gt;
        &lt;li tabId="Options" tooltipText="Enter other options."&gt;Options&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Banking Method --&gt;
    &lt;div id="pageBankingMethod"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th&gt;&lt;label id="lblBankingMethod"&gt;Select the type of Bank Account&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;div id="rblBankingMethods"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblBankingDetails"&gt;Banking Details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="cbdBankingDetails"&gt;&lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Bank Interface - Zepto --&gt;
    &lt;div id="pageBankInterface_Zepto"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblZepto"&gt;Zepto Banking Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboZepto_PaymentMethod"&gt;Method:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboZepto_PaymentMethod" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboZepto_AccountSortCode"&gt;Sort Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboZepto_AccountSortCode" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtZepto_AccountNumber"&gt;Account No:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtZepto_AccountNumber" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtZepto_Name"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtZepto_Name" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trZepto_Warnings"&gt;
          &lt;th colspan="2"&gt;&lt;div id="divZepto_Warnings" class="is-info-text info banking-warnings"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblZeptoContactDetails"&gt;Zepto Contact Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboZepto_Email"&gt;Email:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboZepto_Email" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboZepto_Phone"&gt;Phone:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboZepto_Phone" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtZepto_Contact"&gt;Contact:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtZepto_Contact" /&gt;&lt;/td&gt;
        &lt;/tr&gt;        
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Summary --&gt;
    &lt;div id="pageSummary"&gt;
      &lt;div id="wbSummary" class="is-dock-fill"&gt;&lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Options --&gt;
    &lt;div id="pageOptions"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblFriendlyName"&gt;Select a Friendly Name to identify these Banking Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFriendlyName"&gt;Friendly&amp;nbsp;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFriendlyName" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblValid"&gt;Specify the period for which these details are valid&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateDateStart"&gt;Valid From:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateStart"/&gt; &lt;small&gt;to&lt;/small&gt; &lt;input id="dateStop"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAccountClosed" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOther"&gt;Specify other options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkShowExternally" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numCreditLimit"&gt;Credit Limit:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numCreditLimit" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numDebitLimit"&gt;Debit Limit:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numDebitLimit" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label for="txtNotes"&gt;Enter Notes&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="txtNotes" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdActions"/&gt;

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

&lt;script&gt;
// Properties
var mRecord;

// Controls
var C = {
  //   Banking Method
  lblBankingMethod: null,
  rblBankingMethods: null,

  //   General
  lblBankingDetails: null,
  cbdBankingDetails: null,

  //   Bank Interface - Zepto
  lblZepto: null,
  cboZepto_PaymentMethod: null,
  cboZepto_AccountSortCode: null,
  txtZepto_AccountNumber: null,
  txtZepto_Name: null,
  trZepto_Warnings: null,
  divZepto_Warnings: null,

  lblZeptoContactDetails: null,
  cboZepto_Email: null,
  cboZepto_Phone: null,
  txtZepto_Contact: null,

  //   Summary
  wbSummary: null,

  //   Options
  lblFriendlyName: null,
  txtFriendlyName: null,

  lblValid: null,
  dateStart: null,
  dateStop: null,
  chkAccountClosed: null,

  lblOther: null,
  chkShowExternally: null,
  numCreditLimit: null,
  numDebitLimit: null,

  txtNotes: null
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mBankInterfaceConfirmList;
var mBankInterfaceSummaryPageHtml;
var mKeepFormOpen;
var mShowBankInterfaceSummaryPage;
var mZeptoPaymentMethods;
var mZeptoContactCreated;
var mRefreshTimerValidateBankingDetails;

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

  // Controls
  //   Banking Method
  C.lblBankingMethod = widget.UI.Label("lblBankingMethod", {});
  C.rblBankingMethods = widget.UI.RadioButtonList("rblBankingMethods", {
    allowBlank: false,
    layout: "vertical",
  });

  //   General
  C.lblBankingDetails = widget.UI.Label("lblBankingDetails", {});
  C.cbdBankingDetails = widget.UI.BankingDetails("cbdBankingDetails", {});

  //   Bank Interface - Zepto
  C.lblZepto = widget.UI.Label("lblZepto", {});
  C.cboZepto_PaymentMethod = widget.UI.DBCombo("cboZepto_PaymentMethod", {
    allowBlank: false,
    limitToList: true,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: ValidateBankingDetails,
  });
  C.cboZepto_AccountSortCode = widget.UI.DBCombo("cboZepto_AccountSortCode", {
    allowBlank: false,
    maxLength: 10,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: ValidateBankingDetails,
  });
  C.txtZepto_AccountNumber = widget.UI.TextBox("txtZepto_AccountNumber", {
    allowBlank: false,
    maxLength: 30,

    onChange: ValidateBankingDetails,
  });
  C.txtZepto_Name = widget.UI.TextBox("txtZepto_Name", {
    allowBlank: false,
    maxLength: 100,

    onChange: ValidateBankingDetails,
  });
  C.trZepto_Warnings = $("#trZepto_Warnings");
  C.divZepto_Warnings = $("#divZepto_Warnings");

  C.lblZeptoContactDetails = widget.UI.Label("lblZeptoContactDetails", {});
  C.cboZepto_Email = widget.UI.ComboBox("cboZepto_Email", {
    allowBlank: false,
    maxLength: 255,

    onChange: ValidateBankingDetails,
  });
  C.cboZepto_Phone = widget.UI.ComboBox("cboZepto_Phone", {
    allowBlank: false,
    maxLength: 255,

    onChange: ValidateBankingDetails,
  });
  C.txtZepto_Contact = widget.UI.TextBox("txtZepto_Contact", {
    allowBlank: false,
    maxLength: 50,

    onButtonClick: txtZepto_Contact_ButtonClick,
    onChange: ValidateBankingDetails,
  });

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

  //   Options
  C.lblFriendlyName = widget.UI.Label("lblFriendlyName", {});
  C.txtFriendlyName = widget.UI.TextBox("txtFriendlyName", {
    maxLength: 50
  });

  C.lblValid = widget.UI.Label("lblValid", {});
  C.dateStart = widget.UI.DateBox("dateStart", {});
  C.dateStop = widget.UI.DateBox("dateStop", {});
  C.chkAccountClosed = widget.UI.CheckBox("chkAccountClosed", {
    caption: "This Account is now closed",
    captionWrap: true
  });

  C.lblOther = widget.UI.Label("lblOther", {});
  C.chkShowExternally = widget.UI.CheckBox("chkShowExternally", {
    caption: "Make these details visible to External applications?",
    captionWrap: true
  });
  C.numCreditLimit = widget.UI.NumberBox("numCreditLimit", {});
  C.numDebitLimit = widget.UI.NumberBox("numDebitLimit", {});

  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 5
  });

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

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

  // Disable Close Button (this causes the 'FormClose' notification action to be invoked instead)
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler)

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

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mZeptoPaymentMethods = null;
  mShowBankInterfaceSummaryPage = false;
  mBankInterfaceSummaryPageHtml = null;
  mBankInterfaceConfirmList = null;
  mKeepFormOpen = false;
  mZeptoContactCreated = false;

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);

      // Define Actions
      var actions = [];
      if (!mRecord.ReadOnly &amp;&amp; mRecord.CanDelete) actions.push({ groupId: "Record", actionId: "Delete", caption: "Delete", icon: "Delete" });
      if (!mRecord.ReadOnly &amp;&amp; !mRecord.IsNew) actions.push({ groupId: "Other", actionId: "MoveTop", caption: "Promote Banking Details to top of List", icon: "Move_Up" });

      frmMain.ActionsDefine(actions, "cmdActions", Form_ExecuteAction);

      // Skip pages if Banking Interfaces are not configured
      if (mRecord.BankingInterfaces.length == 1) {
        tabWizard.SelectedTabId("General");
      }

      // Fields Load
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // Banking Method
    C.rblBankingMethods.Value(mRecord.BankingInterface);

    // Standard
    C.cbdBankingDetails.Initialise({ showWarnings: !mRecord.BankingDetailsObfuscated});
    if (mRecord.BankingInterface == "STANDARD") {
      C.cbdBankingDetails.FromBankingDetailsJson(mRecord.BankingDetailsJson);
    }

    // Banking Details for Banking Interfaces
    var o = JSON.parse(mRecord.BankingDetailsJson);

    // Zepto
    if (BankInterfaceAvailable("ZEPTO")) {
      C.cboZepto_PaymentMethod.Text(o.PaymentMethodId);
      C.cboZepto_AccountSortCode.Text(o.AccountSortCode);
      C.txtZepto_AccountNumber.Text(o.AccountNumber);
      C.txtZepto_Name.Text(o.AccountName);
      C.cboZepto_Email.Text(o.AccountEmail);
      C.cboZepto_Phone.Text(o.AccountPhone);
      C.txtZepto_Contact.Text(o.ExternalId);
    }

    // Options
    C.txtFriendlyName.Text(mRecord.FriendlyName);

    C.dateStart.Value(mRecord.DateStart);
    C.dateStop.Value(mRecord.DateStop);
    C.chkAccountClosed.Value(mRecord.AccountClosed);

    C.chkShowExternally.Value(mRecord.ShowExternally);
    C.numCreditLimit.Value(mRecord.CreditLimit);
    C.numDebitLimit.Value(mRecord.DebitLimit);

    C.txtNotes.Text(mRecord.Notes);
  }

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

  // Update Controls
  if (mRecord.BankingInterfaces.length &gt; 1 &amp;&amp; !mRecord.IsNew) {
    tabWizard_Move(1);
  }

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// =========================================
// Create a Banking Details object for Zepto
// =========================================
function CreateBankingDetails_Zepto() {
  var params = {
    paymentMethodId: C.cboZepto_PaymentMethod.Text(),
    accountSortCode: C.cboZepto_AccountSortCode.Text(),
    accountNumber: C.txtZepto_AccountNumber.Text(),
    accountName: C.txtZepto_Name.Text(),
    accountEmail: C.cboZepto_Email.Text(),
    externalId: C.txtZepto_Contact.Text(),
    cardExpiryMonthIndex: -1,
    cardExpiryYear: -1,
  };

  if (mRecord.CountryCode == "NZ") {
    params.accountPhone = C.cboZepto_Phone.Text();
  }

  return params;
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Banking Interfaces
  mRecord.BankingInterface = C.rblBankingMethods.Value();
  switch (mRecord.BankingInterface) {
    case "STANDARD":
      mRecord.BankingDetailsJson = C.cbdBankingDetails.ToBankingDetailsJson();
      break;

    case "ZEPTO":
      // Zepto
      mRecord.BankingDetailsJson = JSON.stringify(CreateBankingDetails_Zepto());
      break;

    default:
      console.warn("Fields_Save, unhandled Banking Interface '" + mRecord.BankingInterface + "'.");
  }

  // Options
  mRecord.FriendlyName = C.txtFriendlyName.Text();

  mRecord.DateStart = C.dateStart.Value();
  mRecord.DateStop = C.dateStop.Value();
  mRecord.AccountClosed = C.chkAccountClosed.Value();

  mRecord.ShowExternally = C.chkShowExternally.Value();
  mRecord.CreditLimit = C.numCreditLimit.Value();
  mRecord.DebitLimit = C.numDebitLimit.Value();

  mRecord.Notes = C.txtNotes.Text();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    widget.SetHeading(mRecord.FormHeading);
  }

  // Controls
  if (mRecord) {
    // General
    C.rblBankingMethods.ListFromArray(mRecord.BankingInterfaces);

    // Bank Interface - Zepto
    if (mRecord.SupportsBankSortCode) {
      C.cboZepto_AccountSortCode.Caption(mRecord.TerminologyAccountSortCode + ":");
    }
    else {
      C.cboZepto_AccountSortCode.VisibleRow(false);
    }
    
    // Zepto Actions
    var buttons = [];
    buttons.push({ id: "Zepto_Create", tooltipText: "Create", icon: "Add" });
    buttons.push({ id: "Zepto_Verify", tooltipText: "Verify", icon: "Check" });
    buttons.push({ id: "Zepto_Delete", tooltipText: "Delete", icon: "Delete" });
    C.txtZepto_Contact.ButtonsDefine(buttons);
  }

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

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (mZeptoContactCreated &amp;&amp; mRecord &amp;&amp; mRecord.IsNew) {
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form?\n\nThe Zepto Contact created will not be saved.", {}, tabWizard_Cancel_Post);
  }
  else {
    tabWizard_Cancel_Post();
  }
}

function tabWizard_Cancel_Post() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

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

  // Cancel/ Finish Button
  if (mRecord &amp;&amp; mRecord.ReadOnly) {
    cmdCancel.hide();
    cmdFinish.text("Close");
  }
  else {
    if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
    cmdFinish.text("Save");
  }

  // Special
  switch (tabWizard.SelectedTabId()) {
    case "BankingMethod":
    case "Summary":
    case "Options":
      break;

    case "General":
      if (mRecord.BankingInterfaces.length == 1) {
        cmdBack.prop("disabled", true);
      }
      break;

    case "BankInterface_Zepto":        
      if (mRecord &amp;&amp; mRecord.ReadOnly) C.txtZepto_Contact.Buttons().ButtonVisible("Zepto_Create", false);
      C.txtZepto_Contact.Buttons().ButtonVisible("Zepto_Verify", (!mRecord.BankingDetailsObfuscated &amp;&amp; C.txtZepto_Contact.Text()));
      C.txtZepto_Contact.Buttons().ButtonVisible("Zepto_Delete", (!mRecord.BankingDetailsObfuscated &amp;&amp; C.txtZepto_Contact.Text()));
      
      // Resize
      tabWizard_Resize();
      break;

    default:
      console.warn("tabWizard_UpdateButtons, unhandled tab '" + tabWizard.SelectedTabId() + "'.");
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "BankInterface_Zepto":
      C.cboZepto_PaymentMethod.WidthResizeFromParent();
      C.cboZepto_AccountSortCode.WidthResizeFromParent();
      C.txtZepto_AccountNumber.WidthResizeFromParent();
      C.txtZepto_Name.WidthResizeFromParent();

      C.cboZepto_Email.WidthResizeFromParent();
      C.txtZepto_Contact.WidthResizeFromParent();
      break;

    case "Options":
      C.txtFriendlyName.WidthResizeFromParent();
      C.numCreditLimit.WidthResizeFromParent();
      C.numDebitLimit.WidthResizeFromParent();
      C.txtNotes.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "General":
          found = (C.rblBankingMethods.Value() == "STANDARD");
          break;

        case "BankInterface_Zepto":
          found = (C.rblBankingMethods.Value() == "ZEPTO");
          break;

        case "Summary":
          // mShowBankInterfaceSummaryPage is set in tabWizard_Validate for the previous Bank Interface page
          found = mShowBankInterfaceSummaryPage;
          break;

        default:
          found = true;
          break;
      }

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

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

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

      case "Summary":
        pageSummary_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    default:
      if (mRecord.CountryCode == "AU" &amp;&amp; tabWizard.SelectedTabId() == "BankInterface_Zepto") {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter Zepto (formerly Split Payments) Banking and Contact Details.");
      }
      else {
        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()) {
    case "General":
      C.cbdBankingDetails.Focus();
      break;

    default:
      tabWizard.FocusFirst();
      break;
  }
}

// ===============
// Validate Wizard
// ===============
function tabWizard_Validate(validCallback) {
  // Read-Only
  if (mRecord.ReadOnly) {
    // No validation because form is Read Only
    validCallback();
    return;
  }

  // Validate
  var Ok = tabWizard.Validate(true);

  // Other client-side validation
  // NOTE: Non-standard for this HTML Widget due to Bank Interface pages
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // Has server-side validation
        break;

      case "BankInterface_Zepto":        
        if (C.chkAccountClosed.Value()) {
          validCallback();
          return;
        }
        else {
          // Only has server-side validation if the Account is current
        }
        break;

      case "Summary":
        // No need to always refetch confirmation list since this will generally have been fetched when validating a Bank Interface page
        if (mBankInterfaceConfirmList &amp;&amp; mBankInterfaceConfirmList.length != 0) {
          tabWizard_ValidatePost(validCallback, JSON.stringify({ Data: mBankInterfaceConfirmList }));
          return;
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        Fields_Save();
        params = JSON.parse(JSON.stringify(mRecord));
        break;

      case "BankInterface_Zepto":
        // Reset
        mShowBankInterfaceSummaryPage = false;
        mBankInterfaceSummaryPageHtml = null;
        mBankInterfaceConfirmList = null;

        // Parameters
        params = {
          bankingDetailsJson: JSON.stringify(CreateBankingDetails_Zepto()),
        };
        break;

      default:
        break;
    }

    if (params) {
      // Disable Form
      frmMain.FormDisable("Validating");

      // Extend parameters
      params.pageId = tabWizard.SelectedTabId();

      // Call WizardValidate method in Script
      widget.GetString("WizardValidate",
                       params,
                       function (data) { tabWizard_ValidatePost(validCallback, data); },
                       tabWizard_ValidateFail);
    }
    else {
      // No server-side validation
      validCallback();
    }
  }
}

function tabWizard_ValidatePost(validCallback, data) {
  // Enable form
  frmMain.FormEnable();

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

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
      case "Summary":
        // General
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };

        break;

      case "BankInterface_Zepto":
        // Zepto
        mShowBankInterfaceSummaryPage = (o.Data &amp;&amp; o.Data.length &gt; 0 &amp;&amp; o.Html);
        if (mShowBankInterfaceSummaryPage) {
          mBankInterfaceSummaryPageHtml = o.Html;
          mBankInterfaceConfirmList = o.Data;
        }
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "DELETE":
      Form_ExecuteAction_Delete();
      break;

    case "FINISH":
      // Finish
      if (mRecord.ReadOnly) {
        tabWizard_Cancel();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;

    case "MOVETOP":
      Form_ExecuteAction_MoveTop();
      break;

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

// =============
// Delete Action
// =============
function Form_ExecuteAction_Delete() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    widget.UI.MsgBoxConfirmDelete("Are you sure you want to delete these Banking Details?",
                            {},
                            Form_ExecuteAction_DeletePost);
  });
}

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

  // Delete
  widget.GetString("Delete", {},
    function (data) {
      // Close Form
      widget.Close();

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

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

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

// ==================
// Move to Top Action
// ==================
function Form_ExecuteAction_MoveTop() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    if (mRecord.PromptOnSave) {
      widget.UI.MsgBoxConfirm("Update the Banking Details and move to the top of the list?",
                              { heading: "Update and Promote Banking Details" },
                              function () {
                                // Save and Move
                                Form_ExecuteAction_FinishPost("MoveTop");
                              });
    }
    else {
      // Save and Move without prompting
      Form_ExecuteAction_FinishPost("MoveTop");
    }
  });
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mRecord.PromptOnSave) {
      // Confirm
      if (mRecord.IsNew) {
        var heading = "Add Banking Details?";
        var message = "Are you sure you want to add the Banking Details to this Client?";
      }
      else {
        var heading = "Update Banking Details?";
        var message = "Are you sure you want to update the Banking Details for this Client?";
      }

      widget.UI.MsgBoxConfirm(message,
                              {heading: heading},
                              Form_ExecuteAction_FinishPost,
                              null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

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

  // Create Parameters
  // NOTE: We will simply update mRecord, clone this and send back (less some information)
  Fields_Save();
  var params = JSON.parse(JSON.stringify(mRecord));

  // Move?
  if (moveAction) {
    params.MoveAction = moveAction;
  }

  // Finish
  widget.GetString("Finish", params,
    function () {
      // Close Form
      if (mKeepFormOpen) {
        // Reset Form instead of closing
        Form_Reset();
      }
      else {
        widget.Close();
      }

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

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

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

// =======================
// pageBankInterface_Zepto
// =======================
function pageBankInterface_Zepto_Refresh() {
  // Block UI
  widget.UI.Block("Initialising, please wait...");

  // Hide warnings / labels
  C.trZepto_Warnings.hide();
  C.divZepto_Warnings.html("");

  // Update Controls
  if (!C.cboZepto_AccountSortCode.isRefreshed) {
    C.cboZepto_AccountSortCode.isRefreshed = true;

    // NOTE: Do not include BankName column for performance (this collection can get very large)
    C.cboZepto_AccountSortCode.RefreshFromStandardRange("BankBranches", "", false, "", "BankBranchId,DescriptionFull");
  }
  C.cboZepto_Phone.VisibleRow(mRecord.CountryCode == "NZ");

  // Parameters
  var params = CreateBankingDetails_Zepto();

  // Get Server-side options
  widget.GetString("GetBankInterfaceDetails_Zepto", params, pageBankInterface_Zepto_Refresh_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();

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

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

  // Zepto Payment Methods
  mZeptoPaymentMethods = data.ZeptoPaymentMethods;

  // Update Controls
  C.cboZepto_PaymentMethod.RefreshFromCollection(mZeptoPaymentMethods, "PaymentMethodId", "Description")
  C.cboZepto_Email.ListFromCsvString(data.EmailAddresses);
  C.cboZepto_Phone.ListFromCsvString(data.PhoneNumbers);

  // Initial Validation
  if (data.ValidationData) {
    ValidateBankingDetails_Done(data.ValidationData);
  }
}

// ===================
// pageSummary_Refresh
// ===================
function pageSummary_Refresh() {
  // Show Bank Interface Summary
  C.wbSummary.SetContent(mBankInterfaceSummaryPageHtml, false);
}

// ========================
// Validate Banking Details
// ========================
function ValidateBankingDetails(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Obfuscated so cannot validate?
  if (mRecord.BankingDetailsObfuscated) {
    C.divZepto_Warnings.hide();
    return;
  }

  // Clear Contact if Zepto fields updated
  if (C.txtZepto_Contact.Text()) {
    if (sender == C.cboZepto_AccountSortCode || sender == C.txtZepto_AccountNumber || sender == C.txtZepto_Name || sender == C.cboZepto_Email || sender == C.cboZepto_Phone) {
      C.txtZepto_Contact.Text("");
    }
  }

  // Clear Timer
  if (mRefreshTimerValidateBankingDetails) {
    window.clearTimeout(mRefreshTimerValidateBankingDetails);
    mRefreshTimerValidateBankingDetails = null;
  }

  // Refresh after 500ms
  mRefreshTimerValidateBankingDetails = window.setTimeout(ValidateBankingDetails_Execute, 500);
}

function ValidateBankingDetails_Execute() {
  // Get Params
  switch(tabWizard.SelectedTabId()) {
    case "BankInterface_Zepto":
      var params = CreateBankingDetails_Zepto();
      break;

    default:
      console.warn("ValidateBankingDetails_Execute, unhandled tab '" + tabWizard.SelectedTabId() + "'.");
  }

  if (params) {
    widget.GetString("ValidateBankingDetails", params, ValidateBankingDetails_Done, function(errorMessage) {
      // Set error
      C.divZepto_Warnings.html(widget.UI.HtmlEncode(errorMessage));

      // Show
      C.trZepto_Warnings.show();
    });
  }
}

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

  // Update Controls
  switch(tabWizard.SelectedTabId()) {
    case "BankInterface_Zepto":
      // Formatted Account Number
      if (data.AccountSortCodeFormatted &amp;&amp; mRecord.SupportsBankSortCode) C.cboZepto_AccountSortCode.Text(data.AccountSortCodeFormatted);
      if (data.AccountNumberFormatted) C.txtZepto_AccountNumber.Text(data.AccountNumberFormatted);      
    
      // Colour
      if (data.IsError) {
        C.divZepto_Warnings.css("color", "darkred");
      }
      else {
        C.divZepto_Warnings.css("color", "green");
      }

      // Can Create Contact?
      if ((mRecord &amp;&amp; !mRecord.ReadOnly) &amp;&amp; (!data.IsError || data.ErrorIsOnlyContactId)) {
        C.txtZepto_Contact.Buttons().ButtonVisible("Zepto_Create", true);
      }
      else {
        C.txtZepto_Contact.Buttons().ButtonVisible("Zepto_Create", false);
      }     

      // Update Buttons
      tabWizard_UpdateButtons();

      // Message
      C.divZepto_Warnings.html(widget.UI.HtmlEncode(data.Message));
      if (data.Message) {
        C.trZepto_Warnings.show();
      }
      else {
        C.trZepto_Warnings.hide();
      }
      break;
  }  

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

// ========================================================
// Determines if a particular Banking Interface can be used
// ========================================================
function BankInterfaceAvailable(bankInterface) {
  for (var i = 0; i &lt; mRecord.BankingInterfaces.length; i++) {
    var item = mRecord.BankingInterfaces[i];

    if (item.value == bankInterface) return true;
  }

  return false;
}

// ======================
// Zepto - Create Contact
// ======================
function Zepto_CreateContact_Pre() {
  var isIncoming = false;

  // Custom validation
  var Ok = true;
  if (!C.cboZepto_PaymentMethod.Text()) {
    Ok = false;
    C.cboZepto_PaymentMethod.Focus();
  }
  else if (mRecord.SupportsBankSortCode &amp;&amp; !C.cboZepto_AccountSortCode.Text()) {
    Ok = false;
    C.cboZepto_AccountSortCode.Focus();
  }
  else if (!C.txtZepto_AccountNumber.Text()) {
    Ok = false;
    C.txtZepto_AccountNumber.Focus();
  }

  // Incoming Payment Methods have an additional confirmation
  if (Ok) {
    for (var i = 0; i &lt; mZeptoPaymentMethods.length; i++) {
      var item = mZeptoPaymentMethods[i];

      if (item.PaymentMethodId == C.cboZepto_PaymentMethod.Text()) {
        isIncoming = item.Incoming;
        break;
      }
    }
  }

  // Confirmation Messages
  if (Ok) {    
    var primaryMessage;
    if (mRecord.CountryCode == "AU") {
      primaryMessage = "NOTE: If a Contact with the same Bank Account, Name and Email already exists the existing Contact is returned.";
    }
    else {
      primaryMessage = "Note: If a Contact with the same Bank Account, Name, Email and Phone Number already exists the existing Contact is returned.";
    }

    // Options
    var options = {
      heading: "Add new Zepto Contact?",
      icon: "Logo_Zepto",
    };

    // Messages
    if (isIncoming) {
      var additionalMessages = [];
      additionalMessages.push("The Client has accepted the Zepto Payments Direct Debit Request Service Agreement.");

      widget.UI.MsgBoxConfirmList(primaryMessage + "\n\nConfirm the following to continue:", additionalMessages, options, Zepto_CreateContact);
    }
    else {
      widget.UI.MsgBoxConfirm(primaryMessage, options, Zepto_CreateContact);
    }
  }
}

function Zepto_CreateContact() {
  // Block UI
  widget.UI.Block("Creating Contact, please wait...");

  // Parameters
  var params = {
    paymentMethodId: C.cboZepto_PaymentMethod.Text(),
    accountSortCode: C.cboZepto_AccountSortCode.Text(),
    accountNumber: C.txtZepto_AccountNumber.Text(),
    accountName: C.txtZepto_Name.Text(),
    email: C.cboZepto_Email.Text(),
    phone: C.cboZepto_Phone.Text(),
  };

  // Create Contact
  widget.GetString("Zepto_CreateContact", params, Zepto_CreateContact_Done, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();

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

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

  // Update Flags
  mZeptoContactCreated = true;

  // Update Controls
  C.txtZepto_Name.Text(data.AccountName);
  C.cboZepto_Email.Text(data.Email);
  if (data.Phone) C.cboZepto_Phone.Text(data.Phone);
  C.txtZepto_Contact.Text(data.ContactId);

  C.chkAccountClosed.Value(false);
  if (!C.dateStart.Value()) C.dateStart.Value(data.ValidFromDate);
  C.dateStop.Value(null);
  
  // Update Buttons
  tabWizard_UpdateButtons();

  // Update validation
  if (data.ValidationData) {
    ValidateBankingDetails_Done(data.ValidationData);
  }

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

// ================
// txtZepto_Contact
// ================
function txtZepto_Contact_ButtonClick(sender, e) {
  switch (e.id) {
    case "Zepto_Create":
      Zepto_CreateContact_Pre();
      break;
    
    case "Zepto_Verify":
      Zepto_VerifyContact();
      break;
      
    case "Zepto_Delete":
      Zepto_DeleteContact();
      break;
  }
}

// ======================
// Zepto - Verify Contact
// ======================
function Zepto_VerifyContact() {
  // Block UI
  widget.UI.Block("Verifying, please wait...");

  // Parameters
  var params = {
    bankingDetailsJson: JSON.stringify(CreateBankingDetails_Zepto()),
  }

  // Verify
  widget.GetString("Zepto_VerifyContact", params, Zepto_VerifyContact_Done, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();

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

function Zepto_VerifyContact_Done(data) {
  // Display result
  if (data) {
    widget.UI.Forms.ShowHtml("Verify Zepto Contact", data);
  }

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

// ======================
// Zepto - Delete Contact
// ======================
function Zepto_DeleteContact() {
  widget.UI.MsgBoxConfirm("Delete the Zepto Contact and associated Agreements?\n\nThis will set the Bank Account to 'Closed'.", {}, Zepto_DeleteContact_Post);
}

function Zepto_DeleteContact_Post() {
  // Block UI
  widget.UI.Block("Deleting the Zepto Contact, please wait...");
  
  // Parameters
  var params = {
    paymentMethodId: C.cboZepto_PaymentMethod.Text(),
    contactId: C.txtZepto_Contact.Text(),
  }
  
  // Delete
  widget.GetString("Zepto_DeleteContact", params, Zepto_DeleteContact_Done, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();

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

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

  // Update Closed flag
  C.chkAccountClosed.Value(true);
  if (data &amp;&amp; (!C.dateStop.Value() || widget.CompareDates(C.dateStop.Value(), data.ValidToDate) == 1)) {
    C.dateStop.Value(data.ValidToDate);
  }
  
  // Unblock UI
  widget.UI.Unblock();
  
  // Save and refresh form
  if (!mRecord.IsNew) {
    // Keep form open after saving
    mKeepFormOpen = true;
    
    // Save
    Form_ExecuteAction_FinishPost();
  }
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId) {
     case "FormClose":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabWizard_Cancel();
      break;
   }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>ztDIOL1FU0O6NooAGg024Q</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>800</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>680</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</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>If you do not specify a Default Transaction Type, the Transaction Type selection will be shown regardless of the settings specified below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="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="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ClientId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Clients</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ClientBankAccountPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>For 'Quote' Accounts, this should be the 0-based index of the item in the collection</TooltipText>
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
    <Constants>
      <ISScriptConstants version="1.00">
        <ScriptConstant name="ShowClientAddressInSummary" constantType="Boolean">
          <Notes>Show the Main Client's postal address in the Summary Block.</Notes>
          <Value>true</Value>
        </ScriptConstant>
        <ScriptConstant name="LastPaymentDaysMaximum" constantType="Integer">
          <Notes>Maximum Days for warning since last Reversed Payment.</Notes>
          <Value>120</Value>
        </ScriptConstant>
      </ISScriptConstants>
    </Constants>
  </finScript>