<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-08-18T00:10:08.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-07-17T03:42:06.9700000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2023-08-18T00:09:16.9230000</UpdatedUtcDate>
    <ScriptId>CONTACTADDRESS</ScriptId>
    <Description>Client Contact Address</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ClientContactAddress
Option Explicit On
Option Strict On

' #################################################################
' Client Contact Address wizard HTML Widget
'
' Version: 1.13 (18/08/2023)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.11  19/07/2021  ISS                Updated
'    1.12  11/05/2022  ISS      J028706   Parameter reordered
'    1.13  18/08/2023  ISS      J031820   Added showInstructions: true on the AddressDetails control
' #################################################################

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

' Standard Parameters
Private mClientId As String
Private mClientContactAddressPk As Integer
Private mReadOnly As Boolean
Private mReplaceRecordPk As Integer

' Other
Private mClient As finClient

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 Standard Parameters
  With mCombinedParameters
    mClientId = .GetString("ClientId")
    mClientContactAddressPk = .GetInteger("ClientContactAddressPk")
    mReadOnly = .GetBoolean("ReadOnly")
    mReplaceRecordPk = .GetInteger("ReplaceRecordPk")
  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 Contact Address
      Main = Delete(returnValue)

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

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

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

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

End Function

''' &lt;summary&gt;
'''  Load Client.
''' &lt;/summary&gt;
Private Function GetClient() As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Shortcut
  If mClient IsNot Nothing Then
    Return Success
  End If

  ' Validate
  If Len(mClientId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Client Id not specified.")
  ElseIf finBL.CurrentUserInformation.IsClientFilteredOut(mClientId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Client.")
  End If

  ' Create and Load Client
  If Success Then
    ' Create Client
    mClient = finBL.CreateClient()

    ' Load Client
    If mClient.Load(mClientId) Then
      ' Validate
      If mClient.IsNew Then
        Success = False
        finBL.Error.ErrorBeginFormat("Client '{0}' not found.", mClientId)
      End If
    Else
      Success = False
    End If
  End If

  ' Load Addresses
  If Success Then
    Success = mClient.ContactAddressesLoad()
  End If

  ' Clear Client if failed
  If Not Success Then
    mClient = Nothing
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Load Client Contact Address.
''' &lt;/summary&gt;
Private Function GetClientContactAddress(recordPk As Integer,
                                         ByRef clientContactAddress As finClientContactAddress) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Intialise ByRef
  clientContactAddress = Nothing

  ' Validate
  If recordPk = 0 OrElse recordPk &lt; -1 Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Contact Address Pk {0}.", recordPk)
  End If

  ' Load Client
  If Success Then
    Success = GetClient()
  End If

  ' Get Contact Address
  If Success Then
    If recordPk = -1 Then
      ' New
      clientContactAddress = mClient.ContactAddresses.CreateClientContactAddress()
      mClient.ContactAddresses.Insert(0, clientContactAddress)
    Else
      ' Existing
      If mClient.ContactAddresses.ExistsPk(recordPk) Then
        clientContactAddress = mClient.ContactAddresses.ItemByPk(recordPk)
      Else
        Success = False
        finBL.Error.ErrorBeginFormat("Contact Address {0} not found.", recordPk)
      End If
    End If
  End If

  Return Success

End Function

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

  Dim ClientContactAddress As finClientContactAddress
  Dim ClientContactAddressReplace As finClientContactAddress
  Dim ContactMethod As finContactMethodRO
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Priority As Boolean
  Dim PriorityIndex As Integer
  Dim PriorityList As ISList
  Dim strTemp As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If mReplaceRecordPk &lt;&gt; 0 Then
    If mClientContactAddressPk &lt;&gt; -1 Then
      Success = False
      finBL.Error.ErrorBegin("When replacing an Address, ClientContactAddressPk must be -1.")
    ElseIf mReplaceRecordPk &lt; 0 Then
      Success = False
      finBL.Error.ErrorBeginFormat("Invalid Replace Record Pk {0}.", mReplaceRecordPk)
    End If
  End If

  ' Get Contact Address
  If Success Then
    Success = GetClientContactAddress(mClientContactAddressPk, ClientContactAddress)
  End If

  ' Get record being replaced
  If Success AndAlso mReplaceRecordPk &lt;&gt; 0 Then
    Success = GetClientContactAddress(mReplaceRecordPk, ClientContactAddressReplace)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Read Only?
      If finBL.Database.IsReadOnly OrElse mReadOnly Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .IsNew = ClientContactAddress.IsNew
      .Timestamp = ClientContactAddress.Timestamp

      ' Client
      .ClientId = mClient.ClientId
      .ClientName = mClient.Name

      ' General
      .ContactMethodId = ClientContactAddress.ContactMethodId
      .ValueType = ClientContactAddress.ValueType

      .AddressPhysical = ClientContactAddress.AddressPhysical
      .AddressPostal = ClientContactAddress.AddressPostal

      .AddressJson = ClientContactAddress.ToAddressDetailsHtmlWidgetJsonString()

      .DateStart = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(ClientContactAddress.DateStart)
      .DateStop = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(ClientContactAddress.DateStop)
      .Historic = ClientContactAddress.Historic
      .AddressStatus = ClientContactAddress.AddressStatus
      .Notes = ClientContactAddress.Notes

      ' Replacing Record details
      If ClientContactAddressReplace IsNot Nothing Then
        .ReplaceRecordDetails = finBL.Addressing.FormatAddressFromAddressDetails(ClientContactAddressReplace.ToAddressDetails())

        .ContactMethodId = ClientContactAddressReplace.ContactMethodId
        .AddressPhysical = ClientContactAddressReplace.AddressPhysical
        .AddressPostal = ClientContactAddressReplace.AddressPostal
        .DateStart = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())

        strTemp = "Moved from:" &amp; vbNewLine &amp; .ReplaceRecordDetails
        If Len(.Notes) &lt;&gt; 0 Then strTemp &amp;= vbNewLine &amp; vbNewLine &amp; .Notes
        .Notes = strTemp
      End If

      ' Contact Methods List
      PriorityList = New ISList(mCombinedParameters.GetString("PriorityContactMethods"))
      For Each ContactMethod In finBL.ContactMethods
        If (ContactMethod.Active OrElse ContactMethod.ContactMethodId = .ContactMethodId) AndAlso ContactMethod.ContactType = isefinContactType.Address Then
          ' Priority?
          PriorityIndex = PriorityList.IndexOf(ContactMethod.ContactMethodId, True)
          Priority = PriorityIndex &lt;&gt; -1

          ' Add
          .ContactMethods.Add(New ContactMethodInfo(ContactMethod, Priority, PriorityIndex))
        End If
      Next

      ' Other Lists

      ' Settings

      ' Configuration Options
      .AlwaysShowAdvanced = mCombinedParameters.GetBoolean("AlwaysShowAdvanced", False)
      If .ReadOnly OrElse .IsNew Then
        .CanDelete = False
      Else
        .CanDelete = finBL.CurrentUser.Permissions.Allow("Client.ContactAddresses.Delete")
      End If
      .IconListStyle = LCase(mCombinedParameters.GetString("IconListStyle", "grid"))
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .ShowCity = mCombinedParameters.GetString("ShowCity")
      If Len(.ShowCity) = 0 Then .ShowCity = "True"
    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., Save Contact Address.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted record (FormInitialisationInfo) object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim ClientContactAddress As finClientContactAddress
  Dim ClientContactAddressReplace As finClientContactAddress
  Dim Index As Integer
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Contact Address
  If Success Then
    Success = GetClientContactAddress(mClientContactAddressPk, ClientContactAddress)
  End If

  ' Get record being replaced
  If Success AndAlso mReplaceRecordPk &lt;&gt; 0 Then
    Success = GetClientContactAddress(mReplaceRecordPk, ClientContactAddressReplace)
  End If

  ' Update and Save Client
  If Success Then
    With ClientContactAddress
      ' Contact Method Id Changed?
      If Record.ContactMethodId &lt;&gt; .ContactMethodId Then
        .ContactMethodIdSet(Record.ContactMethodId)
      End If

      ' General
      .ValueType = Record.ValueType
      .AddressPhysical = Record.AddressPhysical
      .AddressPostal = Record.AddressPostal

      .FromAddressDetailsHtmlWidgetJsonString(Record.AddressJson)

      .DateStart = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateStart)
      .DateStop = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateStop)
      .Historic = Record.Historic
      .AddressStatus = Record.AddressStatus
      .Notes = Record.Notes

      ' Tweaks
      If Not .AddressPostal Then
        .PostalId = ""
      End If
    End With

    ' Postal Address Validation
    ' NOTE: User has already accepted unvalidated Address so we must change the Delivery Type to "Unspecified (Validated)"
    If finBL.Settings.AddOns.AddressFullVerification AndAlso finBL.Settings.AddressValidatePostal AndAlso ClientContactAddress.AddressPostal AndAlso finBL.Addressing.AddressInterface.IsAddressDatabaseInitialised Then
      If Len(ClientContactAddress.Country) = 0 OrElse ClientContactAddress.Country = finBL.CurrentCountry.CountryName Then
        If Not finBL.Addressing.AddressValidate(ClientContactAddress.ToAddressDetails()) Then
          ClientContactAddress.DeliveryType = iseAddressDeliveryType.UnspecifiedValidated
        End If
      End If
    End If

    ' Move?
    Select Case Record.MoveAction
      Case "MoveTop"
        Index = mClient.ContactAddresses.IndexOf(ClientContactAddress)
        mClient.ContactAddresses.Move(Index, 0)
    End Select

    ' Replace Record?
    If Success AndAlso ClientContactAddressReplace IsNot Nothing Then
      ' Expire
      If ClientContactAddress.DateStart = Nothing Then
        ClientContactAddressReplace.DateStop = DateAdd(DateInterval.Day, -1, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
      Else
        ClientContactAddressReplace.DateStop = DateAdd(DateInterval.Day, -1, ClientContactAddress.DateStart)
      End If

      ' Ensure new record is directly before old one
      If Success Then Success = mClient.ContactAddresses.Remove(ClientContactAddress)
      If Success Then Success = mClient.ContactAddresses.Insert(mClient.ContactAddresses.IndexOf(ClientContactAddressReplace), ClientContactAddress)
    End If

    ' Save
    If Success Then
      Success = mClient.Save()
    End If
  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 ConfirmList As List(Of String)
  Dim ContactMethod As finContactMethodRO
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
      If WizardValidate_General(parametersJson, ConfirmList) Then
        Data = ConfirmList
      Else
        Success = False
      End If

    Case "New"
      ' New (Contact Method select)
      If finBL.ContactMethods.Exists(mCombinedParameters.GetString("ContactMethodId")) Then
        ' Get defaults for new Client Contact Address
        ContactMethod = finBL.ContactMethods(mCombinedParameters.GetString("ContactMethodId"))

        Data = New With {
          .AddressPhysical = ContactMethod.AddressPhysical,
          .AddressPostal = ContactMethod.AddressPostal
        }
      Else
        FailedMessage = String.Format("Invalid Contact Method '{0}'.", mCombinedParameters.GetString("ContactMethodId"))
      End If
  End Select

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

  Return Success

End Function

Private Function WizardValidate_General(parametersJson As String,
                                        ByRef confirmList As List(Of String)) As Boolean

  Dim ClientContactAddress As finClientContactAddress
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  confirmList = New List(Of String)()

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

  ' Get Contact Address
  If Success Then
    Success = GetClientContactAddress(mClientContactAddressPk, ClientContactAddress)
  End If

  ' Postal Address Validation
  If Success AndAlso finBL.Settings.AddOns.AddressFullVerification AndAlso finBL.Settings.AddressValidatePostal AndAlso ClientContactAddress.AddressPostal AndAlso finBL.Addressing.AddressInterface.IsAddressDatabaseInitialised Then
    If Len(ClientContactAddress.Country) = 0 OrElse ClientContactAddress.Country = finBL.CurrentCountry.CountryName Then
      If Not finBL.Addressing.AddressValidate(ClientContactAddress.ToAddressDetails()) Then
        confirmList.Add("Unvalidated address." &amp; vbNewLine &amp; vbNewLine &amp; finBL.Error.Message(True, True))
      End If
    End If
  End If

  ' Timestamp
  If Success Then
    If Not ClientContactAddress.IsNew AndAlso ClientContactAddress.Timestamp &lt;&gt; Record.TimeStamp Then
      confirmList.Add("The Address has changed since it was loaded, if you continue your update may overwrite these changes.")
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Delete Contact Address.
''' &lt;/summary&gt;
Private Function Delete(ByRef returnValue As String) As Boolean

  Dim ClientContactAddress As finClientContactAddress
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Contact Address
  If Success Then
    Success = GetClientContactAddress(mClientContactAddressPk, ClientContactAddress)
  End If

  ' Delete and Save Client
  If Success Then
    ' Delete
    mClient.ContactAddresses.Remove(ClientContactAddress)

    ' Save
    Success = mClient.Save()
  End If

  Return Success

End Function



''' &lt;summary&gt;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
''' &lt;remarks&gt;
'''  This object is also used to save the Contact Address.
''' &lt;/remarks&gt;
Public Class FormInitialisationInfo

  ' Record
  Public IsNew As Boolean
  Public Timestamp As Integer

  ' Client Properties
  Public ClientId As String
  Public ClientName As String

  ' General
  Public ContactMethodId As String
  Public ValueType As String

  Public AddressPhysical As Boolean
  Public AddressPostal As Boolean
  Public AddressJson As String

  Public DateStart As Date?
  Public DateStop As Date?
  Public Historic As Boolean
  Public AddressStatus As String
  Public Notes As String

  ' Replace Record details
  Public ReplaceRecordDetails As String

  ' Lists
  Public ContactMethods As New List(Of ContactMethodInfo)

  ' Settings

  ' Configuration
  Public AlwaysShowAdvanced As Boolean
  Public CanDelete As Boolean
  Public IconListStyle As String
  Public PromptOnSave As Boolean
  Public [ReadOnly] As Boolean
  Public ShowCity As String

  ' Other
  Public MoveAction As String

End Class


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

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

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

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

  End Sub

End Class


''' &lt;summary&gt;
'''  Simple information about a Contact Method.
''' &lt;/summary&gt;
Public Class ContactMethodInfo

  Public Caption As String
  Public ContactMethodId As String
  Public Icon As String
  Public Priority As Boolean
  Public PriorityIndex As Integer
  Public SubTypeInformationListId As String

  Public Sub New(contactMethod As finContactMethodRO,
                 priority As Boolean,
                 priorityIndex As Integer)

    With contactMethod
      Me.Priority = priority
      Me.PriorityIndex = priorityIndex

      Me.Caption = .Description
      Me.ContactMethodId = .ContactMethodId
      If Len(.Icon) = 0 Then
        Me.Icon = "House"
      Else
        Me.Icon = "ContactMethod_" &amp; .Icon
      End If
      Me.SubTypeInformationListId = .SubTypeInformationListId
    End With

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System-supplied HTML Widget to add, edit or delete a Client Contact Address.

ADDRESS LOOKUPS
=============
For Google address lookups to work, Google Maps API settings must be configured under Global Settings, Clients, Addressing.

For Post Address Validation to occur, the database country must support it (e.g., New Zealand) and it must be configured correctly. Also, the Web Configuration must have Addressing enabled.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="New"&gt;Contact Address&lt;/li&gt;
        &lt;li tabId="General"&gt;Address Details&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- New --&gt;
    &lt;div id="pageNew" style="text-align:center !important"&gt;
      &lt;div id="blContactMethods"&gt;&lt;/div&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:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tbody&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="cboValueType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboValueType"/&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;
              &lt;table&gt;
                &lt;tr&gt;
                  &lt;td style="padding-right:12px"&gt;&lt;input id="chkAddressPostal" type="checkbox" /&gt;&lt;/td&gt;
                  &lt;td&gt;&lt;input id="chkAddressPhysical" type="checkbox" /&gt;&lt;/td&gt;
                &lt;/tr&gt;
              &lt;/table&gt;
            &lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAddressDetails"&gt;Address details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="adAddress"&gt;&lt;/tbody&gt;

        &lt;tbody&gt;
          &lt;tr class="advanced" id="trOther"&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblOther"&gt;Other details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr class="advanced" id="trDateStart"&gt;
            &lt;th&gt;&lt;label for="dateStart"&gt;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 class="advanced" id="trHistoric"&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkHistoric" type="checkbox" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr class="advanced" id="trAddressStatus"&gt;
            &lt;th&gt;&lt;label for="cboAddressStatus"&gt;Status:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboAddressStatus"/&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;th colspan="2"&gt;&lt;label id="lblNotes"&gt;Notes&lt;/label&gt;&lt;/th&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="txtNotes" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&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="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

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

&lt;/div&gt;


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

// Controls
var C = {
  //   New
  blContactMethods: null,

  //   General
  lblContactDetails: null,
  cboValueType: null,
  chkAddressPostal: null,
  chkAddressPhysical: null,

  lblAddressDetails: null,
  adAddress: null,

  trOther: null,
  lblOther: null,
  trAddressStatus: null,
  cboAddressStatus: null,
  trDateStart: null,
  dateStart: null,
  dateStop: null,
  trHistoric: null,
  chkHistoric: null,

  lblNotes: null,
  txtNotes: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdAdvanced;

// Other
var mAdvancedVisible = false;
var mContactMethod;
var mHasAdvancedOptions = false;
var mRequiresRefresh = false;

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   New
  C.blContactMethods = widget.UI.ButtonList("blContactMethods", {
    onChange: blContactMethods_Change
  });

  //   General
  C.lblContactDetails = widget.UI.Label("lblContactDetails", {});
  C.cboValueType = widget.UI.InformationListComboBox("cboValueType", {});
  C.chkAddressPostal = widget.UI.CheckBox("chkAddressPostal", {
    caption: "Postal",
    onChange: function () { chkAddressPostal_Change(); Address_Changed(); },
  });
  C.chkAddressPhysical = widget.UI.CheckBox("chkAddressPhysical", {
    caption: "Physical",
  });

  C.lblAddressDetails = widget.UI.Label("lblAddressDetails", {});
  C.adAddress = widget.UI.AddressDetails("adAddress", {
    allowBlank: false,
    autoValidateAddress: true,
    showDeliveryType: true,
    showPostalId: true,
    showPropertyName: true,
    showInstructions: true,

    onDeliveryTypeChange: UpdateAddressControls,
  });

  C.trOther = $("#trOther");
  C.lblOther = widget.UI.Label("lblOther", {});
  C.trDateStart = $("#trDateStart");
  C.dateStart = widget.UI.DateBox("dateStart", {});
  C.dateStop = widget.UI.DateBox("dateStop", {});
  C.trHistoric = $("#trHistoric");
  C.chkHistoric = widget.UI.CheckBox("chkHistoric", {
    caption: "Historic (dates not available or are estimates)?",
  });
  C.trAddressStatus = $("#trAddressStatus");
  C.cboAddressStatus = widget.UI.InformationListComboBox("cboAddressStatus", {});

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

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

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

  // Handle 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(function() { Form_ExecuteAction("Finish"); });

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(function () {
    // Toggle Advanced
    mAdvancedVisible = !mAdvancedVisible;
    pageGeneral_Refresh();
  });

  // Reset
  Form_Reset();
});

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

  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

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

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

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

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

  // 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 Address to top of List", icon: "Move_Up" });

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

  // If only one Contact Method then use this
  if(mRecord &amp;&amp; mRecord.IsNew &amp;&amp; mRecord.ContactMethods.length == 1) {
    mRecord.ContactMethodId = mRecord.ContactMethods[0].ContactMethodId;
  }

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboValueType.Text(mRecord.ValueType);
    C.chkAddressPostal.Value(mRecord.AddressPostal);
    C.chkAddressPhysical.Value(mRecord.AddressPhysical);

    C.adAddress.FromAddressDetailsJson(mRecord.AddressJson);

    C.txtNotes.Text(mRecord.Notes);

    C.cboAddressStatus.Text(mRecord.AddressStatus);

    C.dateStart.Value(mRecord.DateStart);
    C.dateStop.Value(mRecord.DateStop);
    C.chkHistoric.Value(mRecord.Historic);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord.ValueType = C.cboValueType.Text();
  mRecord.AddressPostal = C.chkAddressPostal.Value();
  mRecord.AddressPhysical = C.chkAddressPhysical.Value();

  mRecord.AddressJson = C.adAddress.ToAddressDetailsJson();

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

  mRecord.AddressStatus = C.cboAddressStatus.Text();

  mRecord.DateStart = C.dateStart.Value();
  mRecord.DateStop = C.dateStop.Value();
  mRecord.Historic = C.chkHistoric.Value();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  var heading = "Contact Address";
  if (mRecord &amp;&amp; mRecord.ReplaceRecordDetails) {
    heading = "Replace " + heading;
  }
  else if (mRecord &amp;&amp; mRecord.IsNew) {
    heading = "New " + heading;
  }
  widget.SetHeading(heading);

  // Information Lists
  C.cboAddressStatus.SetComboFromInformationList("AddressStatus", true);

  // Lists
  if (mRecord) {
  }

  // Controls
  if (mRecord) {
    C.blContactMethods.Style(mRecord.IconListStyle);
  }

  // Check for Advanced options
  mHasAdvancedOptions = true;
  if (mRecord) {
    mHasAdvancedOptions = !mRecord.AlwaysShowAdvanced;
  }

  // Controls
  if (mRecord) {
    C.blContactMethods.Style(mRecord.IconListStyle);

    // Advanced
    if (!mHasAdvancedOptions) {
      C.adAddress.AdvancedPostalId(false);
      C.trOther.removeClass("advanced");
      C.trDateStart.removeClass("advanced");
      C.trHistoric.removeClass("advanced");
      C.trAddressStatus.removeClass("advanced");
    }

    switch(mRecord.ShowCity.toUpperCase()) {
      case "TRUE":
        C.adAddress.AdvancedCity(false);
        break;

      case "FALSE":
        C.adAddress.ShowCity(false);
        break;

      case "ADVANCED":
        C.adAddress.AdvancedCity(mHasAdvancedOptions);
        break;
    }
  }

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

  // "New" page tweaks
  if (tabIndex == 0 &amp;&amp; (!mRecord || mRecord.IsNew) &amp;&amp; !mContactMethod) {
    cmdNext.prop("disabled", true); // Disable on "New" page if this is a new record
  }

  // Only show Advanced button on relevant pages
  cmdAdvanced.hide()
  if (mHasAdvancedOptions) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        cmdAdvanced.show();
        break;
    }
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // General
      C.cboValueType.WidthResizeFromParent();
      C.adAddress.WidthResizeFromParent();
      C.cboAddressStatus.WidthResizeFromParent();
      C.txtNotes.WidthResizeFromParent();
      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)) {
        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 "New":
        // New
        pageNew_Refresh();
        break;

      case "General":
        // General
        pageGeneral_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "New":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Select a Contact Method for Client '" + mRecord.ClientId + "', " + mRecord.ClientName + ".");
      break;

    case "General":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter Address details for Client '" + mRecord.ClientId + "', " + mRecord.ClientName + ".");
      break;

    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

  // Back, Next command buttons valid?
  tabWizard_UpdateButtons();

  // Resize Wizard
  tabWizard_Resize();

  // Focus
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.adAddress.Focus();
      break;

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

// ===============
// Validate Wizard
// ===============
function tabWizard_Validate(validCallback) {
  // Validate
  var Ok = tabWizard.Validate(true);

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // Server side validation required
        break;

      case "New":
        if (C.blContactMethods.SelectedItemIndex() == -1) {
          Ok = false;
        }
        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));
        params.ContactMethods = null;
        params.CountriesList = null;
        break;

      case "New":
        // Fetch default parameters for Contact Method change
        if (mRequiresRefresh) {
          params = { contactMethodId: mRecord.ContactMethodId };
        }
        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":
        // 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 "New":
        // New
        o = o.Data;

        // Set defaults based on new Contact Method
        if (mRecord.IsNew) {
          C.chkAddressPostal.Value(o.AddressPostal);
          C.chkAddressPhysical.Value(o.AddressPhysical);
        }

        // Clear flags
        mRequiresRefresh = false;
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  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("Unhandled action '" + actionId + "'");
  }
}

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

      widget.UI.MsgBoxConfirm(message,
                              { heading: heading },
                              Form_ExecuteAction_FinishPost);

    }
    else {
      // Save without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishPost(moveAction) {
  // Disable Form
  widget.UI.Block("Saving, 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));
  params.ContactMethods = null;
  params.CountriesList = null;

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

  // Finish
  widget.GetString("Finish", params,
    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();
    }
  );
}

// =============
// Delete Action
// =============
function Form_ExecuteAction_Delete() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    widget.UI.MsgBoxConfirmDelete("Are you sure you want to delete this Address?",
                            {},
                            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("Move the Address to the top of the list?\n\nNote, this will also update your changes.",
                              { heading: "Update and Promote Address" },
                              function () {
                                // Save and Move
                                Form_ExecuteAction_FinishPost("MoveTop");
                              });
    }
    else {
      // Save and Move without prompting
      Form_ExecuteAction_FinishPost("MoveTop");
    }
  });
}

// =======
// pageNew
// =======
function pageNew_Refresh() {
  // Build Contact Methods List
  if (mRecord) {
    // Define buttons
    var buttons = [];
    for(var i = 0; i &lt; mRecord.ContactMethods.length; i++) {
      var item = mRecord.ContactMethods[i];

      buttons.push({ id: item.ContactMethodId,
                     caption: item.Caption,
                     icon: item.Icon,
                     priority: item.Priority });

      // Get current Contact Method
      if (item.ContactMethodId == mRecord.ContactMethodId) {
        mContactMethod = item;
      }
    }
    C.blContactMethods.ButtonsDefine(buttons);

    // Select
    C.blContactMethods.SelectedItemId(mRecord.ContactMethodId);
  }
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Controls
  if (mContactMethod) {
    C.lblContactDetails.Text(mContactMethod.Caption + " options");

    if (mContactMethod.SubTypeInformationListId) {
      C.cboValueType.VisibleRow(true);
      C.cboValueType.SetComboFromInformationList(mContactMethod.SubTypeInformationListId, true);
    } else
    {
      C.cboValueType.VisibleRow(false);
    }
  }

  // Address Controls
  UpdateAddressControls();

  // Advanced Button visible?
  if (mRecord &amp;&amp; mRecord.AlwaysShowAdvanced) {
    // Hide button
    cmdAdvanced.hide();

    // Remove advanced section styling for everything
    $("tr").removeClass("advanced");
  }
  else if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }

  // Resize
  tabWizard_Resize();
}

// ================
// blContactMethods
// ================
function blContactMethods_Change(sender, e) {
  if (C.blContactMethods.SelectedItemIndex() != -1) {
    // Select Contact Method
    mContactMethod = mRecord.ContactMethods[C.blContactMethods.SelectedItemIndex()];
    mRecord.ContactMethodId = mContactMethod.ContactMethodId;

    // Move to next page
    mRequiresRefresh = true;
    tabWizard_Move(1);
  }
}

// ================
// chkAddressPostal
// ================
function chkAddressPostal_Change() {
  // Only auto-validate if this is a Postal Address
  C.adAddress.AutoValidateAddress(C.chkAddressPostal.Value());

  // Refresh Page
  pageGeneral_Refresh();
}

// =======================
// Update Address Controls
// =======================
function UpdateAddressControls() {
  // Delivery Type and Country-specific
  C.adAddress.ShowDeliveryType(C.chkAddressPostal.Value());
  if (C.adAddress.IsDeliveryTypeBagOrBox()) {
    C.lblAddressDetails.TooltipText("When entering Box or Bag details, specify these in the 'Details' field, e.g:\n\nPO BOX 707");
  }
  else {
    C.lblAddressDetails.TooltipText("");
  }

  // Postal-only
  if (mRecord) {
    if (C.chkAddressPostal.Value()) {
      C.adAddress.ShowPostalId(true);
      C.adAddress.AutoValidateAddress(C.chkAddressPostal.Value());
    }
    else {
      C.adAddress.ShowPostalId(false);
    }
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>efBydnKeb0OIoQSxcC37cw</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 />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IconListStyle" 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>Grid</Value>
            <Visible>true</Visible>
            <List>Grid,Vertical</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="PriorityContactMethods" type="Text">
            <BlankTip />
            <Caption>Priority Contact Methods</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>A comma-separated list of Contact Method Ids to highlight and show first.</TooltipText>
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AlwaysShowAdvanced" type="Boolean">
            <BlankTip />
            <Caption>Always show "Advanced" details?</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="ShowCity" 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>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <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="ClientContactAddressPk" 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="ReplaceRecordPk" 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="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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>