<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-06-06T22:58:01.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2018-08-26T21:15:49.4870000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2022-06-06T22:56:33.1250000</UpdatedUtcDate>
    <ScriptId>AE</ScriptId>
    <Description>Account Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' HtmlWidget_AccountEdit
Option Explicit On
Option Strict On

' #################################################################
' Account Edit form HTML Widget
'
' Version: 1.08 (07/06/2022)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.07  13/04/2021  ISS                Updated
'    1.08  25/02/2022  ISS      J027949   External Id update now has Permission Key
'          09/05/2022  ISS      J028680   Mandatory Information Lists now respected
'          07/06/2022  ISS      J028452   User Defined fields not retaining indexes
' #################################################################

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

' Standard Parameters
Private mAccountId As String
Private mPage As String
Private mReadOnly As Boolean

' Other
Private mAccount As finAccount

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 mStartupParameters
    mAccountId = .GetString("AccountId") ' Always use Startup Parameters since the Account Id may be updated
  End With
  With mCombinedParameters
    mPage = .GetString("Page")
    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 "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, requestInfo, returnValue)

    Case "GetImageData"
      ' Get Image Data
      Main = GetImageData(returnValue)

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

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

End Function

''' &lt;summary&gt;
'''  Load Account.
''' &lt;/summary&gt;
Private Function GetAccount() As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Shortcut
  If mAccount IsNot Nothing Then
    Return Success
  End If

  ' Validate
  If Len(mAccountId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Id not specified.")
  ElseIf Not finBL.CurrentUser.Permissions.Allow("Account.Update") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to update Accounts.")
  End If

  ' Create and Load Account
  If Success Then
    ' Create Account
    mAccount = finBL.CreateAccount()

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

  ' Clear Account if failed
  If Not Success Then
    mAccount = Nothing
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Retrieves Image data for a specific Resource Id
''' &lt;/summary&gt;
Public Function GetImageData(ByRef returnValue As String) As Boolean

  Dim DataUri As String
  Dim obj As Object
  Dim ResourceId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Validate
  If Len(ResourceId) = 0 Then
    ' No Parameter value
  ElseIf Not finBL.Resources.Exists(ResourceId) Then
    ' Resource does not exist
  ElseIf Not finBL.Resources(ResourceId).IsImage Then
    ' Resource is not an Image
  Else
    DataUri = finBL.Resources(ResourceId).GetImageDataUri(200)
  End If

  ' Create response object
  obj = New With {
    .DataUri = DataUri
  }

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

  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 FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Get Account
  If Success Then
    Success = GetAccount()
  End If

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

      ' Record
      .Pk = mAccount.Pk
      .Timestamp = mAccount.Timestamp

      ' Page Permissions (defined here since they are used below)
      .AllowPageGeneral = finBL.CurrentUser.Permissions.Allow("Account.Form.Page.General")
      .AllowPageDetails = finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Details")
      .AllowPageUserDefined = finBL.CurrentUser.Permissions.Allow("Account.Form.Page.UserDefined") AndAlso finBL.Settings.HasAccountUser(True)
      .AllowPageWeb = finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Web") AndAlso finBL.Settings.AddOns.WebAutomation

      ' General
      .AccountId = mAccount.AccountId ' Always need to return Account Id
      If .AllowPageGeneral Then
        .Name = mAccount.Name
        .Description = mAccount.Description
        .ExternalId = mAccount.ExternalId
        .PassCode = mAccount.PassCode

        .ProductTypeId = mAccount.ProductTypeId
        .ProductTypeDescription = mAccount.ProductType.Description
        .AccountTypeId = mAccount.AccountTypeId
        .AccountTypePromotionId = mAccount.AccountTypePromotionId

        .AccountManagerUserId = mAccount.AccountManagerUserId
        .DateReview = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(mAccount.DateReview)
        .AlertMessage = mAccount.AlertMessage

        .Ledger = mAccount.Ledger
        .Purpose = mAccount.Purpose
        .Source = mAccount.Source
        .Region = mAccount.Region

        .Notes = mAccount.Notes
      End If

      ' Details
      If .AllowPageDetails Then
        .BranchId = mAccount.BranchId
        .DepartmentId = mAccount.DepartmentId

        .BdmUserId = mAccount.BdmUserId
        If mAccount.BdmUserPk &lt;&gt; 0 Then .BdmUserName = finBL.Users(mAccount.BdmUserId).Name
        .BdmOriginalUserId = mAccount.BdmOriginalUserId
        .BdmCommissionUserId = mAccount.BdmCommissionUserId

        .DealerExternalPartyId = mAccount.DealerExternalPartyId
        .DealerExternalPartyEmployeeClientEmploymentId = mAccount.DealerExternalPartyEmployeeClientEmploymentId
        .DealerEmployeeWarning = "TODO:"

        .BrokerExternalPartyId = mAccount.BrokerExternalPartyId
        .BrokerExternalPartyEmployeeClientEmploymentId = mAccount.BrokerExternalPartyEmployeeClientEmploymentId
        .BrokerEmployeeWarning = "TODO:"

        .BulkFunderExternalPartyId = mAccount.BulkFunderExternalPartyId
        If mAccount.BulkFunderExternalPartyPk &lt;&gt; 0 Then .BulkFunderName = finBL.ExternalParties(mAccount.BulkFunderExternalPartyId).DescriptionResolved

        .InsuranceInsurerExternalPartyId = mAccount.InsuranceInsurerExternalPartyId
        .InsurancePolicyType = mAccount.InsurancePolicyType
        .InsurancePolicyNumber = mAccount.InsurancePolicyNumber

        .PoolId = mAccount.PoolId
      End If

      ' User Defined
      If .AllowPageUserDefined Then
        .UserDefinedParameters = finBL.CreateWsParameters(finBL.AccountFunctions.CreateUserDefinedParameters(mAccount.AccountType.UserDefinedParameterSetPk))
        .UserDataJson = mAccount.UserData.ToSimpleJsonString()
      End If

      ' Web
      If .AllowPageWeb Then
        .WebFriendlyName = mAccount.WebFriendlyName
        .WebResourceImageId = mAccount.WebResourceImageId
      End If

      ' Other
      .BdmTooltip = String.Format("The current BDM is determined from this Account's {0}.", finBL.Settings.AccountBdmResolveMethodText)
      .IncludeAccountLevelInsurance = mAccount.AccountType.IncludeAccountLevelInsurance

      ' Permissions
      If .ReadOnly Then
        .CanUpdateAccountType = False
        .CanUpdateBdmOriginal = False
        .CanUpdateBdmCommission = False
        .CanUpdateBranch = False
        .CanUpdateBroker = False
        .CanUpdateBrokerEmployee = False
        .CanUpdateCode = False
        .CanUpdateDealer = False
        .CanUpdateDealerEmployee = False
        .CanUpdateDepartment = False
        .CanUpdateExternalId = False
        .CanUpdateInsurer = False
        .CanUpdateLedger = False
        .CanUpdateManager = False
        .CanUpdatePool = False
      Else
        .CanUpdateAccountType = finBL.CurrentUser.Permissions.Allow("Account.AccountTypeUpdate")
        .CanUpdateBdmOriginal = finBL.CurrentUser.Permissions.Allow("Account.BdmOriginalUpdate")
        .CanUpdateBdmCommission = finBL.CurrentUser.Permissions.Allow("Account.BdmCommissionUpdate")
        .CanUpdateBranch = finBL.CurrentUser.Permissions.Allow("Account.BranchUpdate")
        .CanUpdateBroker = finBL.CurrentUser.Permissions.Allow("Account.BrokerUpdate")
        .CanUpdateBrokerEmployee = finBL.CurrentUser.Permissions.Allow("Account.BrokerEmployeeUpdate")
        .CanUpdateCode = finBL.CurrentUser.Permissions.Allow("Account.UpdateCode")
        .CanUpdateDealer = finBL.CurrentUser.Permissions.Allow("Account.DealerUpdate")
        .CanUpdateDealerEmployee = finBL.CurrentUser.Permissions.Allow("Account.DealerEmployeeUpdate")
        .CanUpdateDepartment = finBL.CurrentUser.Permissions.Allow("Account.DepartmentUpdate")
        .CanUpdateExternalId = finBL.CurrentUser.Permissions.Allow("Account.ExternalIdUpdate")
        .CanUpdateInsurer = finBL.CurrentUser.Permissions.Allow("Account.InsurerUpdate")
        .CanUpdateLedger = finBL.CurrentUser.Permissions.Allow("Account.LedgerUpdate")
        .CanUpdateManager = finBL.CurrentUser.Permissions.Allow("Account.ManagerUpdate")
        .CanUpdatePool = finBL.CurrentUser.Permissions.Allow("Account.PoolUpdate")
      End If

      ' Lists
      .PurposeInformationListId = mAccount.ProductType.AccountPurposeInformationListIdResolved
      .SourceInformationListId = mAccount.ProductType.AccountSourceInformationListIdResolved

      ' Configuration
      .AccountShowExternalId = finBL.SettingsUser.AccountShowExternalId
      .AddOnBranch = finBL.Settings.AddOns.Branch
      .AddOnExternalParty = finBL.Settings.AddOns.ExternalParty
      .AddOnExternalPartyAdvancedBdms = finBL.Settings.AddOns.ExternalPartyAdvancedBdms
      .AddOnExternalPartyBrokers = finBL.Settings.AddOns.ExternalPartyBrokers
      .AddOnExternalPartyDealers = finBL.Settings.AddOns.ExternalPartyDealers
      .AddOnExternalPartyInsurers = finBL.Settings.AddOns.ExternalPartyInsurers
      .AddOnPool = finBL.Settings.AddOns.Pool
      .AddOnPromotions = finBL.Settings.AddOns.Promotions
      .AddOnSecuritisation = finBL.Settings.AddOns.Securitisation

      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave

      .Terminology_SecurityStmtInsuranceBroker = finBL.Settings.SecurityStmtInsuranceBrokerTerminology
    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 Account.
''' &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 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 Account
  If Success Then
    Success = GetAccount()
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; mAccount.Timestamp Then
      Success = False
      finBL.Error.ErrorBegin("This record has been updated by another User.")
    End If
  End If

  ' Update and Save
  ' NOTE: Recheck Permissions in addition to the 'AllowPage' properties before updating to prevent spoofing
  If Success Then
    ' Begin Transaction
    If finBL.Database.TransactionBegin() Then
      ' Update Client
      With mAccount
        ' General
        If Record.AllowPageGeneral AndAlso finBL.CurrentUser.Permissions.Allow("Account.Form.Page.General") Then
          .AccountId = Record.AccountId

          .Name = Record.Name
          .Description = Record.Description
          .ExternalId = Record.ExternalId
          .PassCode = Record.PassCode

          .AccountTypeId = Record.AccountTypeId
          .AccountTypePromotionId = Record.AccountTypePromotionId

          .AccountManagerUserId = Record.AccountManagerUserId
          .DateReview = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateReview)
          .AlertMessage = Record.AlertMessage

          .Ledger = Record.Ledger
          .Purpose = Record.Purpose
          .Source = Record.Source
          .Region = Record.Region

          .Notes = Record.Notes
        End If

        ' Details
        If Record.AllowPageDetails AndAlso finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Details") Then
          .BranchId = Record.BranchId
          .DepartmentId = Record.DepartmentId

          .BdmOriginalUserId = Record.BdmOriginalUserId
          .BdmCommissionUserId = Record.BdmCommissionUserId

          .DealerExternalPartyId = Record.DealerExternalPartyId
          .DealerExternalPartyEmployeeClientEmploymentId = Record.DealerExternalPartyEmployeeClientEmploymentId

          .BrokerExternalPartyId = Record.BrokerExternalPartyId
          .BrokerExternalPartyEmployeeClientEmploymentId = Record.BrokerExternalPartyEmployeeClientEmploymentId

          .InsuranceInsurerExternalPartyId = Record.InsuranceInsurerExternalPartyId
          .InsurancePolicyType = Record.InsurancePolicyType
          .InsurancePolicyNumber = Record.InsurancePolicyNumber

          .PoolId = Record.PoolId
        End If

        ' User Defined
        If Record.AllowPageUserDefined AndAlso finBL.CurrentUser.Permissions.Allow("Account.Form.Page.UserDefined") AndAlso finBL.Settings.HasAccountUser(True) Then
          .UserData.FromHtmlWidgetParametersJsonString(Record.UserDataJson)
        End If

        ' Web
        If Record.AllowPageWeb AndAlso finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Web") AndAlso finBL.Settings.AddOns.WebAutomation Then
          .WebFriendlyName = Record.WebFriendlyName
          .WebResourceImageId = Record.WebResourceImageId
        End If
      End With

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

      ' Commit/ Rollback Transaction
      If Success Then
        finBL.Database.TransactionCommit()
      Else
        finBL.Database.TransactionRollback()
      End If
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&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 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
  End Select

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

  Return Success

End Function


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

  ' Form
  Public PageId As String
  Public [ReadOnly] As Boolean

  ' Record
  Public Pk As Integer
  Public Timestamp As Integer

  ' General
  Public AccountId As String

  Public Name As String
  Public Description As String
  Public ExternalId As String
  Public PassCode As String

  Public ProductTypeId As String
  Public ProductTypeDescription As String
  Public AccountTypeId As String
  Public AccountTypePromotionId As String

  Public AccountManagerUserId As String
  Public DateReview As Date?
  Public AlertMessage As String

  Public Ledger As String
  Public Purpose As String
  Public Source As String
  Public Region As String

  Public Notes As String

  ' Details
  Public BranchId As String
  Public DepartmentId As String

  Public BdmUserId As String
  Public BdmUserName As String
  Public BdmOriginalUserId As String
  Public BdmCommissionUserId As String

  Public DealerExternalPartyId As String
  Public DealerExternalPartyEmployeeClientEmploymentId As String
  Public DealerEmployeeWarning As String

  Public BrokerExternalPartyId As String
  Public BrokerExternalPartyEmployeeClientEmploymentId As String
  Public BrokerEmployeeWarning As String

  Public BulkFunderExternalPartyId As String
  Public BulkFunderName As String

  Public InsuranceInsurerExternalPartyId As String
  Public InsurancePolicyType As String
  Public InsurancePolicyNumber As String

  Public PoolId As String

  ' User Defined
  Public UserDefinedParameters As ISWsParameters
  Public UserDataJson As String

  ' Web
  Public WebFriendlyName As String
  Public WebResourceImageId As String

  ' Other
  Public BdmTooltip As String
  Public IncludeAccountLevelInsurance As Boolean

  ' Permissions
  Public AllowPageGeneral As Boolean
  Public AllowPageDetails As Boolean
  Public AllowPageUserDefined As Boolean
  Public AllowPageWeb As Boolean

  Public CanUpdateAccountType As Boolean
  Public CanUpdateBdmOriginal As Boolean
  Public CanUpdateBdmCommission As Boolean
  Public CanUpdateBranch As Boolean
  Public CanUpdateBroker As Boolean
  Public CanUpdateBrokerEmployee As Boolean
  Public CanUpdateCode As Boolean
  Public CanUpdateDealer As Boolean
  Public CanUpdateDealerEmployee As Boolean
  Public CanUpdateDepartment As Boolean
  Public CanUpdateExternalId As Boolean
  Public CanUpdateInsurer As Boolean
  Public CanUpdateLedger As Boolean
  Public CanUpdateManager As Boolean
  Public CanUpdatePool As Boolean

  ' Lists
  Public PurposeInformationListId As String ' Theoretically this can change based on Account Type
  Public SourceInformationListId As String ' Theoretically this can change based on Account Type

  ' Configuration
  Public AccountShowExternalId As Boolean
  Public AddOnBranch As Boolean
  Public AddOnExternalParty As Boolean
  Public AddOnExternalPartyAdvancedBdms As Boolean
  Public AddOnExternalPartyBrokers As Boolean
  Public AddOnExternalPartyDealers As Boolean
  Public AddOnExternalPartyInsurers As Boolean
  Public AddOnPool As Boolean
  Public AddOnPromotions As Boolean
  Public AddOnSecuritisation As Boolean

  Public HideOtherPages As Boolean
  Public PromptOnSave As Boolean

  Public Terminology_SecurityStmtInsuranceBroker As Boolean

  ' Other

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</Code>
    <Language>VisualBasic</Language>
    <Notes>System-supplied HTML Widget to edit an Account.</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;!-- Tabs --&gt;
    &lt;div id="tabDetails" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General"&gt;General&lt;/li&gt;
        &lt;li tabId="Details"&gt;Details&lt;/li&gt;
        &lt;li tabId="UserDefined"&gt;User Defined&lt;/li&gt;
        &lt;li tabId="Web"&gt;Web&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&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="lblCodeAndName"&gt;Code, Name and Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAccountId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAccountId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtDescription"&gt;Description:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDescription"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtExternalId"&gt;External Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtExternalId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPassCode"&gt;Pass Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPassCode"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;th colspan="2"&gt;&lt;label id="lblAccountType"&gt;Product and Account Type&lt;/label&gt;&lt;/th&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboProductType"&gt;Product Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboProductType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountType"&gt;Account Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountTypePromotion"&gt;Promotion:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountTypePromotion"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;th colspan="2"&gt;&lt;label id="lblAccountManager"&gt;Account Manager&lt;/label&gt;&lt;/th&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountManagerUser"&gt;Manager:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountManagerUser"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateDateReview"&gt;Review Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateDateReview"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAlertMessage"&gt;Alert&amp;nbsp;Message:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAlertMessage"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;th colspan="2"&gt;&lt;label id="lblLedger"&gt;Ledger, Purpose, Source and Region&lt;/label&gt;&lt;/th&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboLedger"&gt;Ledger:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboLedger"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboPurpose"&gt;Purpose:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboPurpose"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboSource"&gt;Source:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboSource"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRegion"&gt;Region:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRegion"/&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;/table&gt;
    &lt;/div&gt;



    &lt;!-- Details --&gt;
    &lt;div id="pageDetails"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBranch"&gt;Branch and Department&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBranch"&gt;Branch:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBranch"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboDepartment"&gt;Department:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboDepartment"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBdm"&gt;Business Development Manager&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBdmUser"&gt;BDM:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBdmUser"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBdmOriginalUser"&gt;Original BDM:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBdmOriginalUser"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBdmCommissionUser"&gt;Commissions:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBdmCommissionUser"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDealer"&gt;Dealer and Employee&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboDealer"&gt;Dealer:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboDealer"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboDealerEmployee"&gt;Employee:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboDealerEmployee"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBroker"&gt;Broker and Employee&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBroker"&gt;Broker:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBroker"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBrokerEmployee"&gt;Employee:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBrokerEmployee"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBulkFunder"&gt;Bulk Funder&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboBulkFunder"&gt;Bulk Funder:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboBulkFunder"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblInsurance"&gt;Insurance details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboInsInsurer"&gt;Insurer:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInsInsurer"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboInsPolicyType"&gt;Policy Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInsPolicyType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtInsPolicyNumber"&gt;Policy&amp;nbsp;Number:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtInsPolicyNumber"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPool"&gt;Pool&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboPool"&gt;Pool:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboPool"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- User Defined --&gt;
    &lt;div id="pageUserDefined"&gt;
      &lt;div id="phUserDefined" class="is-dock-fill"&gt;&lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Web --&gt;
    &lt;div id="pageWeb"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:6em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblWeb"&gt;Friendly Name (Nickname) and Image&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtWebFriendlyName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtWebFriendlyName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboWebResourceImageId"&gt;Image:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboWebResourceImageId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trResourceImagePreview"&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td&gt;&lt;img id="imgResourceImagePreview" style="margin-top:8px;" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Save&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;


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

var mOriginalJson;

// Controls
var C = {
  //   General
  lblCodeAndName: null,
  txtAccountId: null,
  txtName: null,
  txtDescription: null,
  txtExternalId: null,
  txtPassCode: null,

  lblAccountType: null,
  cboProductType: null,
  cboAccountType: null,
  cboAccountTypePromotion: null,

  lblAccountManager: null,
  cboAccountManagerUser: null,
  dateDateReview: null,
  cboAlertMessage: null,

  lblLedger: null,
  cboLedger: null,
  cboPurpose: null,
  cboSource: null,
  cboRegion: null,

  lblNotes: null,
  txtNotes: null,

  //   Details
  lblBranch: null,
  cboBranch: null,
  cboDepartment: null,

  lblBdm: null,
  cboBdmUser: null,
  cboBdmOriginalUser: null,
  cboBdmCommissionUser: null,

  lblDealer: null,
  cboDealer: null,
  cboDealerEmployee: null,

  lblBroker: null,
  cboBroker: null,
  cboBrokerEmployee: null,

  lblBulkFunder: null,
  cboBulkFunder: null,

  lblInsurance: null,
  cboInsInsurer: null,
  cboInsPolicyType: null,
  txtInsPolicyNumber: null,

  lblPool: null,
  cboPool: null,

  //   User Defined
  phUserDefined: null,

  //   Web
  lblWeb: null,
  txtWebFriendlyName: null,
  cboWebResourceImageId: null,
  trResourceImagePreview: null,
  imgResourceImagePreview: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

// Other

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

  // --------
  // Controls
  // --------
  //   General
  C.lblCodeAndName = widget.UI.Label("lblCodeAndName", {
    tooltipText: "The Pass Code is used to challenge and identify a person before providing information regarding the Account."
  });
  C.txtAccountId = widget.UI.TextBox("txtAccountId", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.txtName = widget.UI.TextBox("txtName", {
    allowBlank: false,
    maxLength: 100,
  });
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 255,
    multiLine: true,
    rows: 3,
  });
  C.txtExternalId = widget.UI.TextBox("txtExternalId", {
    maxLength: 40,
  });
  C.txtPassCode = widget.UI.TextBox("txtPassCode", {
    maxLength: 20,
  });

  C.lblAccountType = widget.UI.Label("lblAccountType", {});
  C.cboProductType = widget.UI.DBCombo("cboProductType", {
    autoReadOnly: true,
    readOnly: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.cboAccountType = widget.UI.DBCombo("cboAccountType", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    onChange: cboAccountType_Change,
  });
  C.cboAccountTypePromotion = widget.UI.DBCombo("cboAccountTypePromotion", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblAccountManager = widget.UI.Label("lblAccountManager", {});
  C.cboAccountManagerUser = widget.UI.DBCombo("cboAccountManagerUser", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.dateDateReview = widget.UI.DateBox("dateDateReview", {});
  C.cboAlertMessage = widget.UI.InformationListComboBox("cboAlertMessage", {
    maxLength: 100,
  });

  C.lblLedger = widget.UI.Label("lblLedger", {});
  C.cboLedger = widget.UI.InformationListComboBox("cboLedger", {
    maxLength: 20,
  });
  C.cboPurpose = widget.UI.InformationListComboBox("cboPurpose", {
    maxLength: 50,
  });
  C.cboSource = widget.UI.InformationListComboBox("cboSource", {
    maxLength: 50,
  });
  C.cboRegion = widget.UI.InformationListComboBox("cboRegion", {
    maxLength: 20,
  });

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

  //   Details
  C.lblBranch = widget.UI.Label("lblBranch", {});
  C.cboBranch = widget.UI.DBCombo("cboBranch", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.cboDepartment = widget.UI.DBCombo("cboDepartment", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblBdm = widget.UI.Label("lblBdm", {});
  C.cboBdmUser = widget.UI.DBCombo("cboBdmUser", {
    autoReadOnly: false,
    readOnly: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.cboBdmOriginalUser = widget.UI.DBCombo("cboBdmOriginalUser", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.cboBdmCommissionUser = widget.UI.DBCombo("cboBdmCommissionUser", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

  C.lblDealer = widget.UI.Label("lblDealer", {});
  C.cboDealer = widget.UI.DBCombo("cboDealer", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    onChange: cboDealer_Change,
  });
  C.cboDealerEmployee = widget.UI.DBCombo("cboDealerEmployee", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

  C.lblBroker = widget.UI.Label("lblBroker", {});
  C.cboBroker = widget.UI.DBCombo("cboBroker", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    onChange: cboBroker_Change,
  });
  C.cboBrokerEmployee = widget.UI.DBCombo("cboBrokerEmployee", {
    allowBlank: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

  C.lblBulkFunder = widget.UI.Label("lblBulkFunder", {});
  C.cboBulkFunder = widget.UI.DBCombo("cboBulkFunder", {
    autoReadOnly: false,
    readOnly: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblInsurance = widget.UI.Label("lblInsurance", {});
  C.cboInsInsurer = widget.UI.DBCombo("cboInsInsurer", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.cboInsPolicyType = widget.UI.InformationListComboBox("cboInsPolicyType", {
    maxLength: 50,
  });
  C.txtInsPolicyNumber = widget.UI.TextBox("txtInsPolicyNumber", {
    maxLength: 20,
  });

  C.lblPool = widget.UI.Label("lblPool", {});
  C.cboPool = widget.UI.DBCombo("cboPool", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  //   User Defined
  C.phUserDefined = widget.UI.ParametersHost("phUserDefined", {});

  //   Web
  C.lblWeb = widget.UI.Label("lblWeb", {});
  C.txtWebFriendlyName = widget.UI.TextBox("txtWebFriendlyName", {
    maxLength: 50
  });
  C.cboWebResourceImageId = widget.UI.DBCombo("cboWebResourceImageId", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,

    onChange: cboWebResourceImageId_Change
  });
  C.trResourceImagePreview = $("#trResourceImagePreview");
  C.imgResourceImagePreview = $("#imgResourceImagePreview");

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

  // Create Tabs
  tabDetails = new widget.UI.Tabs("tabDetails", {
    style: "normal",
    onSelectedTabChanged: tabDetails_Refresh,
  });

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

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

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabDetails_Cancel);
  cmdFinish.click(Form_ExecuteAction_Finish);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // 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);

  // Set Tab
  if (mRecord &amp;&amp; mRecord.PageId) {
    tabDetails.SelectedTabId(mRecord.PageId);

    // Hide other Pages
    if (mRecord.HideOtherPages) {
      tabDetails.ShowSingleTab(mRecord.PageId);
    }
  }
  else {
    tabDetails.SelectedTabId("General");
  }

  // Page Permissions
  if (mRecord) {
    if (!mRecord.AllowPageGeneral) tabDetails.TabVisible("General", false);
    if (!mRecord.AllowPageDetails) tabDetails.TabVisible("Details", false);
    if (!mRecord.AllowPageUserDefined) tabDetails.TabVisible("UserDefined", false);
    if (!mRecord.AllowPageWeb) tabDetails.TabVisible("Web", false);
  }

  // Load Fields
  Fields_Load();

  // Save Fields (so UserData is in correct format for mOriginalJson)
  Fields_Save();

  // Save original JSON for Form_IsDirty
  mOriginalJson = JSON.stringify(mRecord);
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    if (mRecord.AllowPageGeneral) {
      C.txtAccountId.Text(mRecord.AccountId);
      C.txtName.Text(mRecord.Name);
      C.txtDescription.Text(mRecord.Description);
      C.txtExternalId.Text(mRecord.ExternalId);
      C.txtPassCode.Text(mRecord.PassCode);

      C.cboProductType.RefreshUnbound(mRecord.ProductTypeId, mRecord.ProductTypeDescription);
      C.cboAccountType.Text(mRecord.AccountTypeId);
      C.cboAccountTypePromotion.Text(mRecord.AccountTypePromotionId);

      C.cboAccountManagerUser.Text(mRecord.AccountManagerUserId);
      C.dateDateReview.Value(mRecord.DateReview);
      C.cboAlertMessage.Text(mRecord.AlertMessage);

      C.cboLedger.Text(mRecord.Ledger);
      C.cboPurpose.Text(mRecord.Purpose);
      C.cboSource.Text(mRecord.Source);
      C.cboRegion.Text(mRecord.Region);

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

    // Details
    if (mRecord.AllowPageDetails) {
      C.cboBranch.Text(mRecord.BranchId);
      C.cboDepartment.Text(mRecord.DepartmentId);

      C.cboBdmUser.RefreshUnbound(mRecord.BdmUserId, mRecord.BdmUserName);
      C.cboBdmOriginalUser.Text(mRecord.BdmOriginalUserId);
      C.cboBdmCommissionUser.Text(mRecord.BdmCommissionUserId);

      C.cboDealer.Text(mRecord.DealerExternalPartyId);
      C.cboDealerEmployee.Text(mRecord.DealerExternalPartyEmployeeClientEmploymentId);

      C.cboBroker.Text(mRecord.BrokerExternalPartyId);
      C.cboBrokerEmployee.Text(mRecord.BrokerExternalPartyEmployeeClientEmploymentId);

      C.cboBulkFunder.RefreshUnbound(mRecord.BulkFunderExternalPartyId, mRecord.BulkFunderName);

      C.cboInsInsurer.Text(mRecord.InsuranceInsurerExternalPartyId);
      C.cboInsPolicyType.Text(mRecord.InsurancePolicyType);
      C.txtInsPolicyNumber.Text(mRecord.InsurancePolicyNumber);

      C.cboPool.Text(mRecord.PoolId);
    }

    // User Defined
    if (mRecord.AllowPageUserDefined) {
      C.phUserDefined.Initialise(mRecord.UserDefinedParameters);
      C.phUserDefined.UpdateParameterValues(JSON.parse(mRecord.UserDataJson));
    }

    // Web
    if (mRecord.AllowPageWeb) {
      C.txtWebFriendlyName.Text(mRecord.WebFriendlyName);
      C.cboWebResourceImageId.Text(mRecord.WebResourceImageId);
    }
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabDetails_Refresh();
  tabDetails_Resize();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  if (mRecord.AllowPageGeneral) {
    mRecord.AccountId = C.txtAccountId.Text();
    mRecord.Name = C.txtName.Text();
    mRecord.Description = C.txtDescription.Text();
    mRecord.ExternalId = C.txtExternalId.Text();
    mRecord.PassCode = C.txtPassCode.Text();

    mRecord.AccountTypeId = C.cboAccountType.Text();
    mRecord.AccountTypePromotionId = C.cboAccountTypePromotion.Text();

    mRecord.AccountManagerUserId = C.cboAccountManagerUser.Text();
    mRecord.DateReview = C.dateDateReview.Value();
    mRecord.AlertMessage = C.cboAlertMessage.Text();

    mRecord.Ledger = C.cboLedger.Text();
    mRecord.Purpose = C.cboPurpose.Text();
    mRecord.Source = C.cboSource.Text();
    mRecord.Region = C.cboRegion.Text();

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

  // Details
  if (mRecord.AllowPageDetails) {
    mRecord.BranchId = C.cboBranch.Text();
    mRecord.DepartmentId = C.cboDepartment.Text();

    mRecord.BdmOriginalUserId = C.cboBdmOriginalUser.Text();
    mRecord.BdmCommissionUserId = C.cboBdmCommissionUser.Text();

    mRecord.DealerExternalPartyId = C.cboDealer.Text();
    mRecord.DealerExternalPartyEmployeeClientEmploymentId = C.cboDealerEmployee.Text();

    mRecord.BrokerExternalPartyId = C.cboBroker.Text();
    mRecord.BrokerExternalPartyEmployeeClientEmploymentId = C.cboBrokerEmployee.Text();

    mRecord.InsuranceInsurerExternalPartyId = C.cboInsInsurer.Text();
    mRecord.InsurancePolicyType = C.cboInsPolicyType.Text();
    mRecord.InsurancePolicyNumber = C.txtInsPolicyNumber.Text();

    mRecord.PoolId = C.cboPool.Text();
  }

  // User Defined
  if (mRecord.AllowPageUserDefined) {
    mRecord.UserDataJson = JSON.stringify(C.phUserDefined.GetParameterValuesWithTypes());
  }

  // Web
  if (mRecord.AllowPageWeb) {
    mRecord.WebFriendlyName = C.txtWebFriendlyName.Text();
    mRecord.WebResourceImageId = C.cboWebResourceImageId.Text();
  }
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    widget.SetHeading("Account (" + mRecord.AccountId + ")");
  }

  // Information Lists
  if (mRecord) {
    // General
    if (mRecord.AllowPageGeneral) {
      C.cboAlertMessage.SetComboFromInformationList("AccountAlertMessages", true);
      C.cboLedger.SetComboFromInformationList("AccountLedger", true);
      C.cboPurpose.SetComboFromInformationList(mRecord.PurposeInformationListId, true);
      C.cboSource.SetComboFromInformationList(mRecord.SourceInformationListId, true);
      C.cboRegion.SetComboFromInformationList("AccountRegion", true);
    }

    // Details
    if (mRecord.AllowPageDetails) {
      if (mRecord.AddOnExternalPartyInsurers) C.cboInsPolicyType.SetComboFromInformationList("InsurancePolicyTypes", true);
    }
  }

  // Lists
  if (mRecord) {
    // General
    if (mRecord.AllowPageGeneral) {
      C.cboAccountType.RefreshFromStandardRange("AccountTypes", "ProductTypeId='" + mRecord.ProductTypeId + "'");
      C.cboAccountManagerUser.RefreshFromStandardRange("AccountManagers");
    }

    // Details
    if (mRecord.AllowPageDetails) {
      if (mRecord.AddOnBranch) C.cboBranch.RefreshFromStandardRange("Branches");
      C.cboDepartment.RefreshFromStandardRange("Departments");

      C.cboBdmOriginalUser.RefreshFromStandardRange("Bdms");
      C.cboBdmCommissionUser.RefreshFromStandardRange("Bdms");

      if (mRecord.AddOnExternalPartyDealers) C.cboDealer.RefreshFromStandardRange("ExternalPartiesDealers");
      if (mRecord.AddOnExternalPartyBrokers) C.cboBroker.RefreshFromStandardRange("ExternalPartiesBrokers");
      if (mRecord.AddOnExternalPartyInsurers) C.cboInsInsurer.RefreshFromStandardRange("ExternalPartiesInsurers");

      if (mRecord.AddOnPool) C.cboPool.RefreshFromStandardRange("Pools");
    }

    // Web
    if (mRecord.AllowPageWeb) {
      C.cboWebResourceImageId.RefreshFromStandardRange("ResourcesAccountImages");
    }
  }

  // Controls
  if (mRecord) {
    // General
    if (mRecord.AllowPageGeneral) {
      C.txtAccountId.ReadOnly(!mRecord.CanUpdateCode);
      C.txtExternalId.ReadOnly(!mRecord.CanUpdateExternalId);
      C.cboAccountType.ReadOnly(!mRecord.CanUpdateAccountType);
      cboAccountType_Change();
      C.cboAccountManagerUser.ReadOnly(!mRecord.CanUpdateManager);
      C.cboLedger.ReadOnly(!mRecord.CanUpdateLedger);
    }

    // Details
    if (mRecord.AllowPageDetails) {
      C.cboBranch.ReadOnly(!mRecord.CanUpdateBranch);
      C.lblBdm.TooltipText(mRecord.BdmTooltip);

      if (mRecord.AddOnExternalPartyDealers) {
        C.cboDealer.ReadOnly(!mRecord.CanUpdateDealer);
        C.cboDealerEmployee.ReadOnly(!mRecord.CanUpdateDealerEmployee);
        cboDealer_Change();
      }

      if (mRecord.AddOnExternalPartyBrokers) {
        C.cboBroker.ReadOnly(!mRecord.CanUpdateBroker);
        C.cboBrokerEmployee.ReadOnly(!mRecord.CanUpdateBrokerEmployee);
        cboBroker_Change();
      }

      if (mRecord.AddOnPool) {
        C.cboPool.ReadOnly(!mRecord.CanUpdatePool);
      }
    }

    // Web
    if (mRecord.AllowPageWeb) {
      C.lblWeb.TooltipText("The Client-selected Name and Image for their Account. These can be used by Portals or External Applications.");
    }
  }

  // Pages
  if (mRecord) {
    // NOTE: Even though many pages are updated in tabDetails_Refresh, we must update them here to ensure controls are hidden since this is not a wizard and all pages are validated on "Finish"
    if (mRecord.AllowPageGeneral) pageGeneral_Refresh();
    if (mRecord.AllowPageDetails) pageDetails_Refresh();
    if (mRecord.AllowPageWeb) pageWeb_Refresh();
  }

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) {
    cmdFinish.prop("disabled", true);
    frmMain.FormReadOnly(C, true);
  }

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

  // Resize Tab
  tabDetails_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Mobile Optimisations
  var el = $(".mobile-indent th.indent1, .mobile-indent th.no-indent1");
  if (window.innerWidth &lt; 500) {
    el.addClass("no-indent1").removeClass("indent1");
  }
  else {
    el.addClass("indent1").removeClass("no-indent1");
  }

  // General

  // Tab
  tabDetails_Resize();
}

// ========
// Is Dirty
// ========
function Form_IsDirty() {
  if (mRecord) {
    // Save Fields
    Fields_Save();

    // Is Dirty?
    return mOriginalJson != JSON.stringify(mRecord);
  }
  else {
    return false;
  }
}

// ==============
// Wizard Buttons
// ==============
function tabDetails_Cancel() {
  if (Form_IsDirty()) {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form without saving your changes?", { heading: "Close Form" }, tabDetails_Cancel_Finalise);
  }
  else {
    // Cancel immediately
    tabDetails_Cancel_Finalise();
  }
}

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

// ==========
// Resize Tab
// ==========
function tabDetails_Resize() {
  switch (tabDetails.SelectedTabId()) {
    case "General":
      // General
      C.txtName.WidthResizeFromParent();
      C.txtDescription.WidthResizeFromParent();
      C.txtExternalId.WidthResizeFromParent();
      C.txtPassCode.WidthResizeFromParent();

      C.cboProductType.WidthResizeFromParent();
      C.cboAccountType.WidthResizeFromParent();
      C.cboAccountTypePromotion.WidthResizeFromParent();

      C.cboAccountManagerUser.WidthResizeFromParent();
      C.cboAlertMessage.WidthResizeFromParent();

      C.txtNotes.WidthResizeFromParent();
      break;

    case "Details":
      // Details
      C.txtInsPolicyNumber.WidthResizeFromParent();
      break;

    case "UserDefined":
      // User Defined
      C.phUserDefined.ResizeFromParent();

    case "Web":
      // Web
      C.txtWebFriendlyName.WidthResizeFromParent();
      C.cboWebResourceImageId.WidthResizeFromParent();
  }
}

// ===========
// Refresh Tab
// ===========
function tabDetails_Refresh() {
   // Load details
  switch (tabDetails.SelectedTabId()) {
    case "General":
      pageGeneral_Refresh();
      break;

    case "Details":
      pageDetails_Refresh();
      break;

    case "Web":
      pageWeb_Refresh();
      break;

    default:
      break;
  }

  // Resize
  tabDetails_Resize();

  // Focus
  switch (tabDetails.SelectedTabId()) {
    default:
      tabDetails.FocusFirst();
      break;
  }
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch(actionId) {
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Assume Success
  var Ok = true;

  // Validate
  Ok = tabDetails.Validate();

  // Prompt
  if (Ok) {
    if (mRecord.PromptOnSave) {
      // Confirm
      widget.UI.MsgBoxConfirm("Are you sure you want to save this record?",
                              { heading: "Save" },
                              Form_ExecuteAction_FinishPost);

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

function Form_ExecuteAction_FinishPost() {
  // 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.GendersList = null;

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      // Close Form
      widget.Close();

      // Refresh Parent (to show updated details)
      // NOTE: Pass in Account Id just in case this has changed
      widget.RefreshParent(C.txtAccountId.Text());
    },

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

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

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  if (!mRecord) return;

  // Controls
  C.txtExternalId.VisibleRow(mRecord.AccountShowExternalId);
  C.cboAccountTypePromotion.VisibleRow(mRecord.AddOnPromotions);
}

// ===========
// pageDetails
// ===========
function pageDetails_Refresh() {
  if (!mRecord) return;

  // Controls
  if (!mRecord.AddOnBranch) {
    C.cboBranch.VisibleRow(false);
    C.lblBranch.Text("Department");
  }

  if (!mRecord.AddOnExternalPartyDealers) {
    C.lblDealer.VisibleRow(false);
    C.cboDealer.VisibleRow(false);
    C.cboDealerEmployee.VisibleRow(false);
  }

  if (!mRecord.AddOnExternalPartyBrokers) {
    C.lblBroker.VisibleRow(false);
    C.cboBroker.VisibleRow(false);
    C.cboBrokerEmployee.VisibleRow(false);
  }

  if (!mRecord.AddOnSecuritisation) {
    C.lblBulkFunder.VisibleRow(false);
    C.cboBulkFunder.VisibleRow(false);
  }

  if (!mRecord.IncludeAccountLevelInsurance) {
    C.lblInsurance.VisibleRow(false);
    C.cboInsInsurer.VisibleRow(false);
    C.cboInsPolicyType.VisibleRow(false);
    C.txtInsPolicyNumber.VisibleRow(false);
  }
  else if(!mRecord.AddOnExternalPartyInsurers) {
    C.cboInsInsurer.VisibleRow(false);
  }

  if (!mRecord.AddOnPool) {
    C.lblPool.VisibleRow(false);
    C.cboPool.VisibleRow(false);
  }
}

// =======
// pageWeb
// =======
function pageWeb_Refresh() {
  // Controls
  cboWebResourceImageId_Change();
}

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

  // Update Promotions
  if (mRecord.AddOnPromotions &amp;&amp; C.cboAccountType.Text()) {
    C.cboAccountTypePromotion.RefreshFromStandardRange("AccountTypePromotions", "AccountTypeId='" + C.cboAccountType.Text() + "'");
  }
}

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

  // Update Employees
  if (C.cboDealer.Text()) {
    C.cboDealerEmployee.RefreshFromStandardRange("ExternalPartiesDealerEmployees", "ExternalPartyId='" + C.cboDealer.Text() + "'");
  }

  // Refresh BDM
  if (e) cboBdm_Refresh();
}

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

  // Update Employees
  if (C.cboBroker.Text()) {
    C.cboBrokerEmployee.RefreshFromStandardRange("ExternalPartiesBrokerEmployees", "ExternalPartyId='" + C.cboBroker.Text() + "'");
  }

  // Refresh BDM
  if (e) cboBdm_Refresh();
}

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

  // Clear to prevent an old image taking a while to disappear
  C.trResourceImagePreview.hide();
  C.imgResourceImagePreview.attr("src", "");

  // Get Image Data
  if (C.cboWebResourceImageId.Text()) {
    widget.GetString("GetImageData", { resourceId: C.cboWebResourceImageId.Text() }, cboWebResourceImageId_Change_Done, function(errorMessage) {
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }
}

function cboWebResourceImageId_Change_Done(data) {
  var o = JSON.parse(data);

  // Set Image from Data URI
  C.imgResourceImagePreview.attr("src", o.DataUri);
  C.trResourceImagePreview.show();
}

// ======
// cboBdm
// ======
function cboBdm_Refresh() {
  //TODO: Refresh read-only BDM
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId) {
     case "FormClose":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabDetails_Cancel();
      break;
   }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>dYgwbAk4XU2bK95aVPrK9Q</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Account</Caption>
    <HtmlWidgetMaxHeight>1024</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <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="HideOtherPages" type="Boolean">
            <BlankTip />
            <Caption>Hide pages other than the one being edited?</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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Configuration options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AccountId" 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.Accounts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="Page" 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>General,Details,UserDefined,Web</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </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>