<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-04-03T23:03:27.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2023-02-27T20:30:34.3700000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2023-04-03T21:20:37.3130000</UpdatedUtcDate>
    <ScriptId>PT</ScriptId>
    <Description>Product Type Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ProductTypeEdit
Option Explicit On
Option Strict On

' #################################################################
' Product Type Edit form HTML Widget
'
' Version: 1.00 (04/04/2023)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  04/04/2023  ISS      J030254   Created
' #################################################################

' Constants
Private Const FORM_KEY As String = "ProductTypes"

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

' Standard Parameters
Private mProductTypeId As String
Private mDuplicateRecordId As String
Private mPage As String
Private mReadOnly As Boolean

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

  ' Assume Success
  Main = True

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

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

  ' Get Standard Parameters
  With mStartupParameters
    mProductTypeId = .GetString("ProductTypeId") ' Always use Startup Parameters since the Product Type Id may be updated
  End With
  With mCombinedParameters
    mDuplicateRecordId = .GetString("DuplicateRecordId")
    mPage = .GetString("Page")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

  ' Validate
  Main = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)

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

      Case "Finish"
        ' Finish wizard
        Main = Finish(parametersJson, requestInfo, 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 If

End Function

''' &lt;summary&gt;
'''  Load Product Type.
''' &lt;/summary&gt;
Private Function GetProductType(ByRef productType As finProductType) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Product Type
  If Success Then
    ' Create Product Type
    productType = finBL.CreateProductType()

    ' Load Product Type
    If Len(mDuplicateRecordId) &lt;&gt; 0 Then
      ' New record (by duplicating existing)
      Success = productType.Load(mDuplicateRecordId)
      If Success Then productType.Duplicate()
    ElseIf Len(mProductTypeId) = 0 Then
      ' New record
    Else
      Success = productType.Load(mProductTypeId)
    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 FormInitialisationInfo As FormInitialisationInfo
  Dim ProductType As finProductType
  Dim ProductTypeAccountRole As finProductTypeAccountRole
  Dim ProductTypeAccountType As finProductTypeAccountType
  Dim ProductTypeDocument As finProductTypeDocument
  Dim ProductTypeSecurityType As finProductTypeSecurityType
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Get Product Type
  If Success Then
    Success = GetProductType(ProductType)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Form
      .PageId = mPage
      If finBL.Database.IsReadOnly OrElse mReadOnly OrElse Not finBL.CurrentUser.Permissions.Allow("Admin.ProductTypes") Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .Pk = ProductType.Pk
      .Timestamp = ProductType.Timestamp

      ' Page Permissions (defined here since they are used below)
      .AllowPageGeneral = True
      .AllowPageOther = True
      .AllowPageAccountRoles = True
      .AllowPageSecurityTypes = finBL.Settings.AddOns.SecurityRegister
      .AllowPageDocuments = True
      .AllowPageAccountTypes = True

      ' General
      .ProductTypeId = ProductType.ProductTypeId ' Always need to return Product Type Id
      If .AllowPageGeneral Then
        .Description = ProductType.Description
        
        .Icon = ProductType.Icon
        
        .ShowInMenu = ProductType.ShowInMenu
        .MenuCaption = ProductType.MenuCaption

        .NextAccountId = ProductType.NextAccountId
      End If

      ' Other
      If .AllowPageOther Then
        .AccountTypeCategoryInformationListId = ProductType.AccountTypeCategoryInformationListId
        .AccountTypeCreditReportingAccountTypeInformationListId = ProductType.AccountTypeCreditReportingAccountTypeInformationListId
        
        .AccountPurposeInformationListId = ProductType.AccountPurposeInformationListId
        .AccountSourceInformationListId = ProductType.AccountSourceInformationListId
        .AccountCloseNoteDeclinedInformationListId = ProductType.AccountCloseNoteDeclinedInformationListId
        .AccountCloseNoteUnwantedInformationListId = ProductType.AccountCloseNoteUnwantedInformationListId
        .AccountCloseNoteClosedInformationListId = ProductType.AccountCloseNoteClosedInformationListId
        .AccountCloseNoteEarlyRedemptionInformationListId = ProductType.AccountCloseNoteEarlyRedemptionInformationListId
        .AccountCloseNoteEarlySettlementInformationListId = ProductType.AccountCloseNoteEarlySettlementInformationListId
        .AccountCloseNoteRefinanceInformationListId = ProductType.AccountCloseNoteRefinanceInformationListId
        .AccountCloseNoteReinvestmentInformationListId = ProductType.AccountCloseNoteReinvestmentInformationListId
        .AccountCloseNoteCancelledInformationListId = ProductType.AccountCloseNoteCancelledInformationListId
        .AccountCloseNoteWriteOffInformationListId = ProductType.AccountCloseNoteWriteOffInformationListId
        .AccountCloseNoteBadDebtWriteOffInformationListId = ProductType.AccountCloseNoteBadDebtWriteOffInformationListId
        
        .IncludeClientLevelInsurance = ProductType.IncludeClientLevelInsurance
        
        .NewWizardValidatorScriptId = ProductType.NewWizardValidatorScriptId
        
        ' Information Lists tooltip text (licence dependant)
        .InformationListsTooltipText = "Declined:" &amp; vbNewLine &amp; "Information list for Account Close Notes when declining an Account"
        .InformationListsTooltipText &amp;= vbNewLine &amp; vbNewLine &amp; "Unwanted:" &amp; vbNewLine &amp; "Information list for Account Close Notes when unwanting an Account"
        If finBL.Settings.AddOns.DepositAccount Then .InformationListsTooltipText &amp;= vbNewLine &amp; vbNewLine &amp; "Early Redem:" &amp; vbNewLine &amp; "Information list for Account Close Notes - Deposit Early Redemption"
        If finBL.Settings.AddOns.LoansAny Then .InformationListsTooltipText &amp;= vbNewLine &amp; vbNewLine &amp; "Early Settle:" &amp; vbNewLine &amp; "Information list for Account Close Notes - Loan Early Settlement"
        If finBL.Settings.AddOns.LoansAny Then .InformationListsTooltipText &amp;= vbNewLine &amp; vbNewLine &amp; "Refinance:" &amp; vbNewLine &amp; "Information list for Account Close Notes - Loan Refinance"
        If finBL.Settings.AddOns.DepositAccount Then .InformationListsTooltipText &amp;= vbNewLine &amp; vbNewLine &amp; "Reinvestment:" &amp; vbNewLine &amp; "Information list for Account Close Notes - Deposit Reinvestment"
        If finBL.Settings.AddOns.LoansAny Then .InformationListsTooltipText &amp;= vbNewLine &amp; vbNewLine &amp; "Cancelled:" &amp; vbNewLine &amp; "Information list for Account Close Notes - Cancelled"
        .InformationListsTooltipText &amp;= vbNewLine &amp; vbNewLine &amp; "Write Off:" &amp; vbNewLine &amp; "Information list for Account Close Notes - Write-Off"
        .InformationListsTooltipText &amp;= vbNewLine &amp; vbNewLine &amp; "Bad Debt:" &amp; vbNewLine &amp; "Information list for Account Close Notes - Bad Debt Write-Off"
      End If
      
      ' Account Roles
      If .AllowPageAccountRoles Then
        .DefaultAccountRoleId = ProductType.DefaultAccountRoleId   
        
        For Each ProductTypeAccountRole In ProductType.AccountRoles
          .ProductTypeAccountRoles.Add(New ProductTypeAccountRole(ProductTypeAccountRole))
        Next    
        .ProductTypeAccountRoles.Sort(AddressOf ProductTypeAccountRoles_SortComparer)
      End If
      
      ' Security Types
      If .AllowPageSecurityTypes Then
        .UseSecurityStmts = ProductType.UseSecurityStmts
        
        .SecurityStmtGroupId = ProductType.SecurityStmtGroupId
        
        .AllowAllSecurityTypes = ProductType.AllowAllSecurityTypes
        
        For Each ProductTypeSecurityType In ProductType.SecurityTypes
          .ProductTypeSecurityTypes.Add(New ProductTypeSecurityType(ProductTypeSecurityType))
        Next          
        .ProductTypeSecurityTypes.Sort(AddressOf ProductTypeSecurityTypes_SortComparer)
      End If

      ' Documents
      If .AllowPageDocuments Then
        For Each ProductTypeDocument In ProductType.Documents
          .ProductTypeDocuments.Add(New ProductTypeDocument(ProductTypeDocument))
        Next 
        .ProductTypeDocuments.Sort(AddressOf ProductTypeDocuments_SortComparer)
      End If
      
      ' Account Types
      If .AllowPageAccountTypes Then
        .DefaultAccountTypeId = ProductType.DefaultAccountTypeId
        
         For Each ProductTypeAccountType In ProductType.AccountTypes
           .ProductTypeAccountTypes.Add(New ProductTypeAccountType(ProductTypeAccountType))
         Next 
      End If
      
      ' Other

      ' Permissions
      .AddonsCreditReporting = finBL.Settings.AddOns.CreditReporting
      .AddonsDepositAccount = finBL.Settings.AddOns.DepositAccount
      .AddonsLoansAny = finBL.Settings.AddOns.LoansAny
      .AddonsSecurityRegister = finBL.Settings.AddOns.SecurityRegister

      ' Lists
      .AccountTypesSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.AccountTypes.GetDataViewFilter_ProductTypesAdministration(ProductType.ProductTypeId))
      .IconList = finBL.Utilities.GetIconListByPrefix("AccountType_").ToCsvString()
      .WizardValidatorScriptsSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.Scripts.GetDataViewFilter_ProductTypes_WizardValidator())

      ' Configuration
      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
    End With
  End If
  
  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Product Type Account Roles Sort Comparer.
''' &lt;/summary&gt;
Private Function ProductTypeAccountRoles_SortComparer(x As ProductTypeAccountRole,
                                                      y As ProductTypeAccountRole) As Integer

  If x.RoleType &gt; y.RoleType Then
    Return 1
  ElseIf x.RoleType &lt; y.RoleType Then
    Return -1
  Else
    If x.AccountRoleId &gt; y.AccountRoleId Then
      Return 1
    ElseIf x.AccountRoleId &lt; y.AccountRoleId Then
      Return -1
    Else 
      Return 0
    End If
  End If

End Function

''' &lt;summary&gt;
'''  Product Type Security Types Sort Comparer.
''' &lt;/summary&gt;
Private Function ProductTypeSecurityTypes_SortComparer(x As ProductTypeSecurityType,
                                                       y As ProductTypeSecurityType) As Integer

  If x.BaseType &gt; y.BaseType Then
    Return 1
  ElseIf x.BaseType &lt; y.BaseType Then
    Return -1
  Else
    If x.SecurityTypeId &gt; y.SecurityTypeId Then
      Return 1
    ElseIf x.SecurityTypeId &lt; y.SecurityTypeId Then
      Return -1
    Else 
      Return 0
    End If
  End If

End Function

''' &lt;summary&gt;
'''  Product Type Documents Sort Comparer.
''' &lt;/summary&gt;
Private Function ProductTypeDocuments_SortComparer(x As ProductTypeDocument,
                                                   y As ProductTypeDocument) As Integer

  Dim XCategory As String
  Dim YCategory As String
  
  XCategory = x.Category
  YCategory = y.Category
                    
  ' Ensure (no category) always appears at the top
  If XCategory = "(no category)" Then XCategory = "AAAAAAAAA"
  If YCategory = "(no category)" Then YCategory = "AAAAAAAAA"
  
  If XCategory &gt; YCategory Then
    Return 1
  ElseIf XCategory &lt; YCategory Then
    Return -1
  Else
    If x.DocumentId &gt; y.DocumentId Then
      Return 1
    ElseIf x.DocumentId &lt; y.DocumentId Then
      Return -1
    Else 
      Return 0
    End If
  End If

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Save Product Type.
''' &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 AccountRole As ProductTypeAccountRole
  Dim Document As ProductTypeDocument
  Dim obj As Object
  Dim ProductType As finProductType
  Dim ProductTypeAccountRole As finProductTypeAccountRole
  Dim ProductTypeDocument As finProductTypeDocument
  Dim ProductTypeSecurityType As finProductTypeSecurityType
  Dim Record As FormInitialisationInfo
  Dim SecurityType As ProductTypeSecurityType
  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 Product Type
  If Success Then
    Success = GetProductType(ProductType)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; ProductType.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 Product Type
      With ProductType
        ' General
        If Record.AllowPageGeneral Then
          .ProductTypeId = Record.ProductTypeId
          .Description = Record.Description
          
          .Icon = Record.Icon
          
          .ShowInMenu = Record.ShowInMenu
          .MenuCaption = Record.MenuCaption
          
          .NextAccountId = Record.NextAccountId
        End If

        ' Other
        If Record.AllowPageOther Then
          .AccountTypeCategoryInformationListId = Record.AccountTypeCategoryInformationListId
          .AccountTypeCreditReportingAccountTypeInformationListId = Record.AccountTypeCreditReportingAccountTypeInformationListId
          
          .AccountPurposeInformationListId = Record.AccountPurposeInformationListId
          .AccountSourceInformationListId = Record.AccountSourceInformationListId
          .AccountCloseNoteDeclinedInformationListId = Record.AccountCloseNoteDeclinedInformationListId
          .AccountCloseNoteUnwantedInformationListId = Record.AccountCloseNoteUnwantedInformationListId
          .AccountCloseNoteClosedInformationListId = Record.AccountCloseNoteClosedInformationListId
          .AccountCloseNoteEarlyRedemptionInformationListId = Record.AccountCloseNoteEarlyRedemptionInformationListId
          .AccountCloseNoteEarlySettlementInformationListId = Record.AccountCloseNoteEarlySettlementInformationListId
          .AccountCloseNoteRefinanceInformationListId = Record.AccountCloseNoteRefinanceInformationListId
          .AccountCloseNoteReinvestmentInformationListId = Record.AccountCloseNoteReinvestmentInformationListId
          .AccountCloseNoteCancelledInformationListId = Record.AccountCloseNoteCancelledInformationListId
          .AccountCloseNoteWriteOffInformationListId = Record.AccountCloseNoteWriteOffInformationListId
          .AccountCloseNoteBadDebtWriteOffInformationListId = Record.AccountCloseNoteBadDebtWriteOffInformationListId
          
          .IncludeClientLevelInsurance = Record.IncludeClientLevelInsurance
          
          .NewWizardValidatorScriptId = Record.NewWizardValidatorScriptId
        End If
        
        ' Account Roles
        If Record.AllowPageAccountRoles Then
          .DefaultAccountRoleId = Record.DefaultAccountRoleId
          
          For Each ProductTypeAccountRole In .AccountRoles
            For Each AccountRole In Record.ProductTypeAccountRoles
              If ProductTypeAccountRole.AccountRolePk = AccountRole.AccountRolePk Then
                ProductTypeAccountRole.Available = AccountRole.Available
                Exit For
              End If
            Next 
          Next 
        End If
        
        ' Security Types
        If Record.AllowPageSecurityTypes Then
          .UseSecurityStmts = Record.UseSecurityStmts
          
          .SecurityStmtGroupId = Record.SecurityStmtGroupId
          
          .AllowAllSecurityTypes = Record.AllowAllSecurityTypes
          
          For Each ProductTypeSecurityType In .SecurityTypes
            For Each SecurityType In Record.ProductTypeSecurityTypes
              If ProductTypeSecurityType.SecurityTypePk = SecurityType.SecurityTypePk Then
                ProductTypeSecurityType.Available = SecurityType.Available
                Exit For
              End If
            Next 
          Next 
        End If
        
        ' Documents
        If Record.AllowPageDocuments Then          
          For Each ProductTypeDocument In .Documents
            For Each Document In Record.ProductTypeDocuments
              If ProductTypeDocument.DocumentPk = Document.DocumentPk Then
                ProductTypeDocument.Available = Document.Available
                Exit For
              End If
            Next 
          Next 
        End If
        
        ' Account Types
        If Record.AllowPageAccountTypes Then
          .DefaultAccountTypeId = Record.DefaultAccountTypeId          
        End If
      End With

      ' Save
      If Success Then
        Success = ProductType.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 ProductTypeId As String

  Public Description As String

  Public Icon As String
  Public ShowInMenu As Boolean
  Public MenuCaption As String

  Public NextAccountId As String

  ' Other
  Public AccountTypeCategoryInformationListId As String
  Public AccountTypeCreditReportingAccountTypeInformationListId As String
  
  Public AccountPurposeInformationListId As String
  Public AccountSourceInformationListId As String
  Public AccountCloseNoteDeclinedInformationListId As String
  Public AccountCloseNoteUnwantedInformationListId As String
  Public AccountCloseNoteClosedInformationListId As String
  Public AccountCloseNoteEarlyRedemptionInformationListId As String
  Public AccountCloseNoteEarlySettlementInformationListId As String
  Public AccountCloseNoteRefinanceInformationListId As String
  Public AccountCloseNoteReinvestmentInformationListId As String
  Public AccountCloseNoteCancelledInformationListId As String
  Public AccountCloseNoteWriteOffInformationListId As String
  Public AccountCloseNoteBadDebtWriteOffInformationListId As String
  
  Public IncludeClientLevelInsurance As Boolean
  
  Public NewWizardValidatorScriptId As String
  
  Public InformationListsTooltipText As String
  
  ' Account Roles
  Public DefaultAccountRoleId As String
  Public ProductTypeAccountRoles As New List(Of ProductTypeAccountRole)

  ' Security Types
  Public UseSecurityStmts As Boolean
  Public SecurityStmtGroupId As String
  Public AllowAllSecurityTypes As Boolean
  Public ProductTypeSecurityTypes As New List(Of ProductTypeSecurityType)
  
  ' Documents
  Public ProductTypeDocuments As New List(Of ProductTypeDocument)
  
  ' Account Types
  Public DefaultAccountTypeId As String
  Public ProductTypeAccountTypes As New List(Of ProductTypeAccountType)
  
  ' Permissions
  Public AddonsCreditReporting As Boolean
  Public AddonsDepositAccount As Boolean
  Public AddonsLoansAny As Boolean
  Public AddonsSecurityRegister As Boolean
  Public AllowPageGeneral As Boolean
  Public AllowPageOther As Boolean
  Public AllowPageAccountRoles As Boolean
  Public AllowPageSecurityTypes As Boolean
  Public AllowPageDocuments As Boolean
  Public AllowPageAccountTypes As Boolean

  ' Lists
  Public AccountTypesSqlWhere As String
  Public IconList As String
  Public WizardValidatorScriptsSqlWhere As String  

  ' Configuration
  Public HideOtherPages As Boolean
  Public PromptOnSave As Boolean

End Class



''' &lt;summary&gt;
'''  Product Type Account Type.
''' &lt;/summary&gt;
Public Class ProductTypeAccountType

  Public AccountTypeId As String
  Public Active As Boolean 
  Public Description As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(productTypeAccountType As finProductTypeAccountType)
    
    With productTypeAccountType
      Me.AccountTypeId = .AccountTypeId
      Me.Active = .Active
      Me.Description = .Description
    End With
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Product Type Account Role.
''' &lt;/summary&gt;
Public Class ProductTypeAccountRole
    
  Public AccountRoleId As String
  Public AccountRolePk As Integer
  Public Active As Boolean
  Public Available As Boolean
  Public Description As String
  Public RoleType As String
  
  Public Sub New()    
  End Sub
  
  Public Sub New(productTypeAccountRole As finProductTypeAccountRole)
    
    With productTypeAccountRole
      Me.AccountRoleId = .AccountRoleId
      Me.AccountRolePk = .AccountRolePk
      Me.Active = .Active
      Me.Available = .Available
      Me.Description = .Description  
      Me.RoleType = .RoleTypeText
    End With
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Product Type Security Type.
''' &lt;/summary&gt;
Public Class ProductTypeSecurityType
  
  Public Active As Boolean
  Public Available As Boolean
  Public BaseType As String
  Public Description As String
  Public SecurityTypeId As String
  Public SecurityTypePk As Integer
  
  Public Sub New()
  End Sub
  
  Public Sub New(productTypeSecurityType As finProductTypeSecurityType)
    
    With productTypeSecurityType
      Me.Active = .Active
      Me.Available = .Available  
      Me.BaseType = .BaseTypeText
      Me.Description = .Description
      Me.SecurityTypeId = .SecurityTypeId
      Me.SecurityTypePk = .SecurityTypePk
    End With
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Product Type Document.
''' &lt;/summary&gt;
Public Class ProductTypeDocument
  
  Public Active As Boolean
  Public Available As Boolean
  Public Category As String
  Public Description As String
  Public DocumentId As String
  Public DocumentPk As Integer
  Public Message As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(productTypeDocument As finProductTypeDocument)
    
    Dim Details As String
    
    With productTypeDocument
      Me.Active = .Active
      Me.Available = .Available       
      Me.Description = .Description
      Me.DocumentId = .DocumentId
      Me.DocumentPk = .DocumentPk   
      Me.Message = finBLShared.Documents(.DocumentId).GetObsoleteMessage(Details)
      If Len(Details) &lt;&gt; 0 Then 
        Me.Message &amp;= vbNewLine &amp; Details
      End If
      
      If Len(.Category) = 0 Then
        Me.Category = "(no category)"
      Else 
        Me.Category = .Category  
      End If
    End With
    
  End Sub
  
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 a Product Type.</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="Other"&gt;Other&lt;/li&gt;
        &lt;li tabId="AccountRoles"&gt;Account Roles&lt;/li&gt;
        &lt;li tabId="SecurityTypes"&gt;Security Types&lt;/li&gt;
        &lt;li tabId="Documents"&gt;Documents&lt;/li&gt;
        &lt;li tabId="AccountTypes"&gt;Account Types&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="lblCodeDescription"&gt;Code and Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtProductTypeId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtProductTypeId" /&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 colspan="2"&gt;&lt;label id="lblIcon"&gt;Icon&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboIcon"&gt;Icon:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboIcon" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountsMenu"&gt;Show in Accounts Menu&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkShowInMenu" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtMenuCaption"&gt;Caption:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtMenuCaption" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblNewAccountDefaults"&gt;Defaults for new Accounts&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtNextAccountId"&gt;Next Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtNextAccountId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Other --&gt;
    &lt;div id="pageOther"&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="lblAccountTypeInformationLists"&gt;Account Type Information Lists&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountTypeCategoryInformationListId"&gt;Category:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountTypeCategoryInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountTypeCreditReportingAccountTypeInformationListId"&gt;CR Acc Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountTypeCreditReportingAccountTypeInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountInformationLists"&gt;Account Information Lists&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountPurposeInformationListId"&gt;Purpose:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountPurposeInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountSourceInformationListId"&gt;Source:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountSourceInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteDeclinedInformationListId"&gt;Declined:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteDeclinedInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteUnwantedInformationListId"&gt;Unwanted:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteUnwantedInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteClosedInformationListId"&gt;Closed:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteClosedInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteEarlyRedemptionInformationListId"&gt;Early Redem:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteEarlyRedemptionInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteEarlySettlementInformationListId"&gt;Early Settle:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteEarlySettlementInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteRefinanceInformationListId"&gt;Refinance:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteRefinanceInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteReinvestmentInformationListId"&gt;Reinvestment:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteReinvestmentInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteCancelledInformationListId"&gt;Cancelled:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteCancelledInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteWriteOffInformationListId"&gt;Write Off:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteWriteOffInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountCloseNoteBadDebtWriteOffInformationListId"&gt;Bad Debt:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountCloseNoteBadDebtWriteOffInformationListId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountClientInsurance"&gt;Account Client Insurance details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeClientLevelInsurance" type="checkbox" /&gt;&lt;/th&gt;          
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblValidator"&gt;Validator Script to use in the New Account wizard&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboNewWizardValidatorScriptId"&gt;Script:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboNewWizardValidatorScriptId" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    
    &lt;!-- Account Roles --&gt;
    &lt;div id="pageAccountRoles"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&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="lblAccountRoles"&gt;Account Roles available to this Product Type&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;    
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboDefaultAccountRoleId"&gt;Default:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboDefaultAccountRoleId" /&gt;&lt;/td&gt;
            &lt;/tr&gt;    
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px; margin-top:8px;"&gt;
          &lt;div id="gridAccountRoles" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    
    
    
    &lt;!-- Security Types --&gt;
    &lt;div id="pageSecurityTypes"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&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="lblSecurityStmtsSupported"&gt;Security Statement support for new Accounts&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;    
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkUseSecurityStmts" type="checkbox" /&gt;&lt;/th&gt;          
            &lt;/tr&gt;
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblSecurityStmtGroup"&gt;Default Security Statement Group&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;  
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboSecurityStmtGroupId"&gt;Group:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboSecurityStmtGroupId" /&gt;&lt;/td&gt;
            &lt;/tr&gt; 
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblSecurityTypesAvailable"&gt;Security Types available for new Accounts&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;     
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkAllowAllSecurityTypes" type="checkbox" /&gt;&lt;/th&gt;          
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblSecurityTypesAvailableToProductType"&gt;Security Types available to this Product Type &lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt; 
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px"&gt;
          &lt;div id="gridSecurityTypes" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Documents --&gt;
    &lt;div id="pageDocuments"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&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="lblDocuments"&gt;Documents available to this Product Type&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;                
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px"&gt;
          &lt;div id="gridDocuments" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    
    
    
    &lt;!-- Account Types --&gt;
    &lt;div id="pageAccountTypes"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&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="lblAccountTypes"&gt;Account Types available to this Product Type&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;    
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboDefaultAccountTypeId"&gt;Default:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboDefaultAccountTypeId" /&gt;&lt;/td&gt;
            &lt;/tr&gt;    
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px; margin-top:8px;"&gt;
          &lt;div id="gridAccountTypes" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced Other"&gt;Advanced&lt;/button&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
  lblCodeDescription: null,
  txtProductTypeId: null,
  txtDescription: null,
  
  lblIcon: null,
  cboIcon: null,
  
  lblAccountsMenu: null,
  chkShowInMenu: null,
  txtMenuCaption: null,
  
  lblNewAccountDefaults: null,
  txtNextAccountId: null,

  //   Other
  lblAccountTypeInformationLists: null,
  cboAccountTypeCategoryInformationListId: null,
  cboAccountTypeCreditReportingAccountTypeInformationListId: null,
  
  lblAccountInformationLists: null,
  cboAccountPurposeInformationListId: null,
  cboAccountSourceInformationListId: null,
  cboAccountCloseNoteDeclinedInformationListId: null,
  cboAccountCloseNoteUnwantedInformationListId: null,
  cboAccountCloseNoteClosedInformationListId: null,
  cboAccountCloseNoteEarlyRedemptionInformationListId: null,
  cboAccountCloseNoteEarlySettlementInformationListId: null,
  cboAccountCloseNoteRefinanceInformationListId: null,
  cboAccountCloseNoteReinvestmentInformationListId: null,
  cboAccountCloseNoteCancelledInformationListId: null,
  cboAccountCloseNoteWriteOffInformationListId: null,
  cboAccountCloseNoteBadDebtWriteOffInformationListId: null,
  
  lblAccountClientInsurance: null,
  chkIncludeClientLevelInsurance: null,
  
  lblValidator: null,
  cboNewWizardValidatorScriptId: null,
  
  //   Account Roles
  lblAccountRoles: null,
  cboDefaultAccountRoleId: null,  
  gridAccountRoles: null,
  
  //   Security Types
  lblSecurityStmtsSupported: null,
  chkUseSecurityStmts: null,
  
  lblSecurityStmtGroup: null,
  cboSecurityStmtGroupId: null,
  
  lblSecurityTypesAvailable: null,
  chkAllowAllSecurityTypes: null,  
  lblSecurityTypesAvailableToProductType: null,
  gridSecurityTypes: null,
  
  //   Documents
  lblDocuments: null,
  gridDocuments: null,
  
  //   Account Types
  lblAccountTypes: null,
  cboDefaultAccountTypeId: null,
  gridAccountTypes: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

var cmdAdvanced;

// Other
var mAdvancedVisible = false;

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   General
  C.lblCodeDescription = widget.UI.Label("lblCodeDescription", {});
  C.txtProductTypeId = widget.UI.TextBox("txtProductTypeId", {
    allowBlank: false,
    maxLength: 10,
  });
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 50,
    
    onChange: txtDescription_Change,
  });
  
  C.lblIcon = widget.UI.Label("lblIcon", {});
  C.cboIcon = widget.UI.IconComboBox("cboIcon", {
    iconPrefix: "AccountType_",
    limitToList: true,
    width: "10em",
  });
  
  C.lblAccountsMenu = widget.UI.Label("lblAccountsMenu", {});
  C.chkShowInMenu = widget.UI.CheckBox("chkShowInMenu", {
    caption: "Show in Menu?",
    
    onChange: chkShowInMenu_Change,
  });
  C.txtMenuCaption = widget.UI.TextBox("txtMenuCaption", {
    maxLength: 30,
  });
  
  C.lblNewAccountDefaults = widget.UI.Label("lblNewAccountDefaults", {});
  C.txtNextAccountId = widget.UI.TextBox("txtNextAccountId", {
    maxLength: 10,
  });
  

  //   Other
  C.lblAccountTypeInformationLists = widget.UI.Label("lblAccountTypeInformationLists", {});
  C.cboAccountTypeCategoryInformationListId = widget.UI.DBCombo("cboAccountTypeCategoryInformationListId", {
    blankTip: "AccountTypeCategory",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountTypeCreditReportingAccountTypeInformationListId = widget.UI.DBCombo("cboAccountTypeCreditReportingAccountTypeInformationListId", {
    blankTip: "CreditReportAccountTypes",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  
  C.lblAccountInformationLists = widget.UI.Label("lblAccountInformationLists", {});
  C.cboAccountPurposeInformationListId = widget.UI.DBCombo("cboAccountPurposeInformationListId", {
    blankTip: "AccountPurpose",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountSourceInformationListId = widget.UI.DBCombo("cboAccountSourceInformationListId", {
    blankTip: "AccountSource",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteDeclinedInformationListId = widget.UI.DBCombo("cboAccountCloseNoteDeclinedInformationListId", {
    blankTip: "AccountCloseNoteDeclined",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteUnwantedInformationListId = widget.UI.DBCombo("cboAccountCloseNoteUnwantedInformationListId", {
    blankTip: "AccountCloseNoteUnwanted",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteClosedInformationListId = widget.UI.DBCombo("cboAccountCloseNoteClosedInformationListId", {
    blankTip: "AccountCloseNoteClosed",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteEarlyRedemptionInformationListId = widget.UI.DBCombo("cboAccountCloseNoteEarlyRedemptionInformationListId", {
    blankTip: "AccountCloseNoteEarlyRed",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteEarlySettlementInformationListId = widget.UI.DBCombo("cboAccountCloseNoteEarlySettlementInformationListId", {
    blankTip: "AccountCloseNoteEarlySet",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteRefinanceInformationListId = widget.UI.DBCombo("cboAccountCloseNoteRefinanceInformationListId", {
    blankTip: "AccountCloseNoteRefinanc",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteReinvestmentInformationListId = widget.UI.DBCombo("cboAccountCloseNoteReinvestmentInformationListId", {
    blankTip: "AccountCloseNoteReinvest",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteCancelledInformationListId = widget.UI.DBCombo("cboAccountCloseNoteCancelledInformationListId", {
    blankTip: "AccountCloseNoteCancelle",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteWriteOffInformationListId = widget.UI.DBCombo("cboAccountCloseNoteWriteOffInformationListId", {
    blankTip: "AccountCloseNoteWriteOff",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  C.cboAccountCloseNoteBadDebtWriteOffInformationListId = widget.UI.DBCombo("cboAccountCloseNoteBadDebtWriteOffInformationListId", {
    blankTip: "AccountCloseNoteBadDebt",
    limitToList: true,
    maxLength: 25,
    width: "18em",
  });
  
  C.lblAccountClientInsurance = widget.UI.Label("lblAccountClientInsurance", {
    tooltipText: "Both this and the 'Record Insurance Details' option in Account Roles must be checked for Client Insurance details on the Account to be available.",
  });
  C.chkIncludeClientLevelInsurance = widget.UI.CheckBox("chkIncludeClientLevelInsurance", {
    caption: "Include Client level Insurance details?",
    captionWrap: true,
  });
  
  C.lblValidator = widget.UI.Label("lblValidator", {});
  C.cboNewWizardValidatorScriptId = widget.UI.DBCombo("cboNewWizardValidatorScriptId", {
    limitToList: true,
    maxLength: 20,
  });

  //   Account Roles
  C.lblAccountRoles = widget.UI.Label("lblAccountRoles", {});
  C.cboDefaultAccountRoleId = widget.UI.DBCombo("cboDefaultAccountRoleId", {
    limitToList: true,
  
    onChange: cboDefaultAccountRoleId_Change,
  });

  //   Security Types
  C.lblSecurityStmtsSupported = widget.UI.Label("lblSecurityStmtsSupported", {});
  C.chkUseSecurityStmts = widget.UI.CheckBox("chkUseSecurityStmts", {
    caption: "Allow Security Statements for new Accounts?",
    captionWrap: true,
  });
  
  C.lblSecurityStmtGroup = widget.UI.Label("lblSecurityStmtGroup", {});
  C.cboSecurityStmtGroupId = widget.UI.DBCombo("cboSecurityStmtGroupId", {
    limitToList: true,
  });
  
  C.lblSecurityTypesAvailable = widget.UI.Label("lblSecurityTypesAvailable", {});
  C.chkAllowAllSecurityTypes = widget.UI.CheckBox("chkAllowAllSecurityTypes", {
    caption: "Allow all Security Types?",
    captionWrap: true,
  });
  C.lblSecurityTypesAvailableToProductType = widget.UI.Label("lblSecurityTypesAvailableToProductType", {});

  //   Documents
  C.lblDocuments = widget.UI.Label("lblDocuments", {});

  //   Account Types
  C.lblAccountTypes = widget.UI.Label("lblAccountTypes", {});
  C.cboDefaultAccountTypeId = widget.UI.DBCombo("cboDefaultAccountTypeId", {
    limitToList: true,
    
    onChange: cboDefaultAccountTypeId_Change,
  });

  // Grids  
  C.gridAccountRoles = widget.UI.Grid("gridAccountRoles", {
    groupByColumns: "RoleType",
    allowMultiRowSelect: true,
    allowGroupingsCollapse: true,
    docked: true,    
    showRowSelectors: true,
    stickyHeader: true,

    onAction: gridAccountRoles_Action,
    onAfterRowActivate: gridAccountRoles_AfterRowActivate,
    onBeforeCellUpdate: gridAccountRoles_BeforeCellUpdate,
    onInitialiseRow: gridAccountRoles_InitialiseRow,
  });  

  C.gridSecurityTypes = widget.UI.Grid("gridSecurityTypes", {
    groupByColumns: "BaseType",
    allowMultiRowSelect: true,
    allowGroupingsCollapse: true,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,

    onAction: gridSecurityTypes_Action,
    onAfterRowActivate: gridSecurityTypes_AfterRowActivate,
    onBeforeCellUpdate: gridSecurityTypes_BeforeCellUpdate,
    onInitialiseRow: gridSecurityTypes_InitialiseRow,    
  });  
  
  C.gridDocuments = widget.UI.Grid("gridDocuments", {
    groupByColumns: "Category",
    allowMultiRowSelect: true,
    allowGroupingsCollapse: true,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,

    onAction: gridDocuments_Action,
    onAfterRowActivate: gridDocuments_AfterRowActivate,
    onBeforeCellUpdate: gridDocuments_BeforeCellUpdate,
    onInitialiseRow: gridDocuments_InitialiseRow,
    onRowDrilldown: gridDocuments_RowDrilldown,
  });  
  
  C.gridAccountTypes = widget.UI.Grid("gridAccountTypes", {
    allowGroupingsCollapse: true,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,

    onBeforeCellUpdate: gridAccountTypes_BeforeCellUpdate,
    onInitialiseRow: gridAccountTypes_InitialiseRow,
  });  

  // Create Widget form
  // NOTE: Hide by default for a cleaner startup
  frmMain = new widget.UI.Form("frmMain", { 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);

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(function () {
    // Toggle Advanced
    mAdvancedVisible = !mAdvancedVisible;
    if (mAdvancedVisible) {
      // Showing
      $("body").addClass("advanced-visible");
      cmdAdvanced.attr("showing", true);
    }
    else {
      // Not showing
      $("body").removeClass("advanced-visible");
      cmdAdvanced.attr("showing", false);
    }
    Form_Resize();
  });

  // 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.AllowPageGeneral) tabDetails.TabVisible("General", false);
  if (!mRecord.AllowPageOther) tabDetails.TabVisible("Other", false);
  if (!mRecord.AllowPageAccountRoles) tabDetails.TabVisible("AccountRoles", false);
  if (!mRecord.AllowPageSecurityTypes) tabDetails.TabVisible("SecurityTypes", false);
  if (!mRecord.AllowPageDocuments) tabDetails.TabVisible("Documents", false);
  if (!mRecord.AllowPageAccountTypes) tabDetails.TabVisible("AccountTypes", 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.txtProductTypeId.Text(mRecord.ProductTypeId);
      C.txtDescription.Text(mRecord.Description);
      
      C.cboIcon.Text(mRecord.Icon);
      
      C.chkShowInMenu.Value(mRecord.ShowInMenu);
      C.txtMenuCaption.Text(mRecord.MenuCaption);
      
      C.txtNextAccountId.Text(mRecord.NextAccountId);
    }

    // Other
    if (mRecord.AllowPageOther) {
      C.cboAccountTypeCategoryInformationListId.Text(mRecord.AccountTypeCategoryInformationListId);
      C.cboAccountTypeCreditReportingAccountTypeInformationListId.Text(mRecord.AccountTypeCreditReportingAccountTypeInformationListId); 
      
      C.cboAccountPurposeInformationListId.Text(mRecord.AccountPurposeInformationListId);
      C.cboAccountSourceInformationListId.Text(mRecord.AccountSourceInformationListId);
      C.cboAccountCloseNoteDeclinedInformationListId.Text(mRecord.AccountCloseNoteDeclinedInformationListId);
      C.cboAccountCloseNoteUnwantedInformationListId.Text(mRecord.AccountCloseNoteUnwantedInformationListId);
      C.cboAccountCloseNoteClosedInformationListId.Text(mRecord.AccountCloseNoteClosedInformationListId);
      C.cboAccountCloseNoteEarlyRedemptionInformationListId.Text(mRecord.AccountCloseNoteEarlyRedemptionInformationListId);
      C.cboAccountCloseNoteEarlySettlementInformationListId.Text(mRecord.AccountCloseNoteEarlySettlementInformationListId);
      C.cboAccountCloseNoteRefinanceInformationListId.Text(mRecord.AccountCloseNoteRefinanceInformationListId);
      C.cboAccountCloseNoteReinvestmentInformationListId.Text(mRecord.AccountCloseNoteReinvestmentInformationListId);
      C.cboAccountCloseNoteCancelledInformationListId.Text(mRecord.AccountCloseNoteCancelledInformationListId);
      C.cboAccountCloseNoteWriteOffInformationListId.Text(mRecord.AccountCloseNoteWriteOffInformationListId);
      C.cboAccountCloseNoteBadDebtWriteOffInformationListId.Text(mRecord.AccountCloseNoteBadDebtWriteOffInformationListId);
      
      C.chkIncludeClientLevelInsurance.Value(mRecord.IncludeClientLevelInsurance);
      
      C.cboNewWizardValidatorScriptId.Text(mRecord.NewWizardValidatorScriptId);
    }
    
    // Account Roles
    if (mRecord.AllowPageAccountRoles) {
      C.cboDefaultAccountRoleId.Text(mRecord.DefaultAccountRoleId);
    }
    
    // Security Types
    if (mRecord.AllowPageSecurityTypes) {
      C.chkUseSecurityStmts.Value(mRecord.UseSecurityStmts);
      
      C.cboSecurityStmtGroupId.Text(mRecord.SecurityStmtGroupId);
      
      C.chkAllowAllSecurityTypes.Value(mRecord.AllowAllSecurityTypes);
    }
    
    // Account Types
    if (mRecord.AllowPageAccountTypes) {
      C.cboDefaultAccountTypeId.Text(mRecord.DefaultAccountTypeId);
    }
  }

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

  // Update Controls
  txtDescription_Change();
  chkShowInMenu_Change();

  // Update fields
  Fields_Update();

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

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  if (mRecord.AllowPageGeneral) {
    mRecord.ProductTypeId = C.txtProductTypeId.Text();
    mRecord.Description = C.txtDescription.Text();
    
    mRecord.Icon = C.cboIcon.Text();
    
    mRecord.ShowInMenu = C.chkShowInMenu.Value();
    mRecord.MenuCaption = C.txtMenuCaption.Text();
    
    mRecord.NextAccountId = C.txtNextAccountId.Text();
  }

  // Other
  if (mRecord.AllowPageOther) {
    mRecord.AccountTypeCategoryInformationListId = C.cboAccountTypeCategoryInformationListId.Text();
    mRecord.AccountTypeCreditReportingAccountTypeInformationListId = C.cboAccountTypeCreditReportingAccountTypeInformationListId.Text(); 
    
    mRecord.AccountPurposeInformationListId = C.cboAccountPurposeInformationListId.Text();
    mRecord.AccountSourceInformationListId = C.cboAccountSourceInformationListId.Text();
    mRecord.AccountCloseNoteDeclinedInformationListId = C.cboAccountCloseNoteDeclinedInformationListId.Text();
    mRecord.AccountCloseNoteUnwantedInformationListId = C.cboAccountCloseNoteUnwantedInformationListId.Text();
    mRecord.AccountCloseNoteClosedInformationListId = C.cboAccountCloseNoteClosedInformationListId.Text();
    mRecord.AccountCloseNoteEarlyRedemptionInformationListId = C.cboAccountCloseNoteEarlyRedemptionInformationListId.Text();
    mRecord.AccountCloseNoteEarlySettlementInformationListId = C.cboAccountCloseNoteEarlySettlementInformationListId.Text();
    mRecord.AccountCloseNoteRefinanceInformationListId = C.cboAccountCloseNoteRefinanceInformationListId.Text();
    mRecord.AccountCloseNoteReinvestmentInformationListId = C.cboAccountCloseNoteReinvestmentInformationListId.Text();
    mRecord.AccountCloseNoteCancelledInformationListId = C.cboAccountCloseNoteCancelledInformationListId.Text();
    mRecord.AccountCloseNoteWriteOffInformationListId = C.cboAccountCloseNoteWriteOffInformationListId.Text();
    mRecord.AccountCloseNoteBadDebtWriteOffInformationListId = C.cboAccountCloseNoteBadDebtWriteOffInformationListId.Text();
    
    mRecord.IncludeClientLevelInsurance = C.chkIncludeClientLevelInsurance.Value();
    
    mRecord.NewWizardValidatorScriptId = C.cboNewWizardValidatorScriptId.Text();
  }
  
  // Account Roles
  if (mRecord.AllowPageAccountRoles) {
    mRecord.DefaultAccountRoleId = C.cboDefaultAccountRoleId.Text();
  }  
  
  // Security Types
  if (mRecord.AllowPageSecurityTypes) {
    mRecord.UseSecurityStmts = C.chkUseSecurityStmts.Value();
      
    mRecord.SecurityStmtGroupId = C.cboSecurityStmtGroupId.Text();
        
    mRecord.AllowAllSecurityTypes = C.chkAllowAllSecurityTypes.Value(); 
  }  
  
  // Account Types
  if (mRecord.AllowPageAccountTypes) {
    mRecord.DefaultAccountTypeId = C.cboDefaultAccountTypeId.Text();
  }
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    if (mRecord.ProductTypeId) {
      widget.SetHeading("Product Type (" + mRecord.ProductTypeId + ")");
    }
    else {
      widget.SetHeading("New Product Type");
    }
  }

  // Information Lists
  if (mRecord) {
    
  }

  // Lists
  if (mRecord) {
    //   General
    if (mRecord.AllowPageGeneral) {
      C.cboIcon.ListFromCsvString(mRecord.IconList);
    }    
    
    //   Other
    if (mRecord.AllowPageOther) {
      C.cboAccountTypeCategoryInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountTypeCategoryInformationListId);
      
      if (mRecord.AddonsCreditReporting) {
        C.cboAccountTypeCreditReportingAccountTypeInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountTypeCreditReportingAccountTypeInformationListId);
      }
      else {
        C.cboAccountTypeCreditReportingAccountTypeInformationListId.VisibleRow(false);
      }    
      
      C.cboAccountPurposeInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountPurposeInformationListId);
      C.cboAccountSourceInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountSourceInformationListId);
      C.cboAccountCloseNoteDeclinedInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteDeclinedInformationListId);
      C.cboAccountCloseNoteUnwantedInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteUnwantedInformationListId);
      C.cboAccountCloseNoteClosedInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteClosedInformationListId);
      
      if (mRecord.AddonsDepositAccount) {
        C.cboAccountCloseNoteEarlyRedemptionInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteEarlyRedemptionInformationListId);
        C.cboAccountCloseNoteReinvestmentInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteReinvestmentInformationListId);    
      }
      else {
        C.cboAccountCloseNoteEarlyRedemptionInformationListId.VisibleRow(false);
        C.cboAccountCloseNoteReinvestmentInformationListId.VisibleRow(false);
      }
      
      if (mRecord.AddonsLoansAny) {
        C.cboAccountCloseNoteEarlySettlementInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteEarlySettlementInformationListId);
        C.cboAccountCloseNoteRefinanceInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteRefinanceInformationListId);
        C.cboAccountCloseNoteCancelledInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteCancelledInformationListId);
      }
      else {
        C.cboAccountCloseNoteEarlySettlementInformationListId.VisibleRow(false);
        C.cboAccountCloseNoteRefinanceInformationListId.VisibleRow(false);
        C.cboAccountCloseNoteCancelledInformationListId.VisibleRow(false);
      }
              
      C.cboAccountCloseNoteWriteOffInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteWriteOffInformationListId);
      C.cboAccountCloseNoteBadDebtWriteOffInformationListId.RefreshFromStandardRange("InformationLists", "", false, mRecord.AccountCloseNoteBadDebtWriteOffInformationListId);    
      C.cboNewWizardValidatorScriptId.RefreshFromStandardRange("Scripts", mRecord.WizardValidatorScriptsSqlWhere, false, mRecord.NewWizardValidatorScriptId);
    }    
    
    //   Account Roles
    if (mRecord.AllowPageAccountRoles) {
      C.cboDefaultAccountRoleId.RefreshFromStandardRange("AccountRoles", "", false, mRecord.DefaultAccountRoleId);
    }    
    
    //   Security Types
    if (mRecord.AllowPageSecurityTypes) {
      C.cboSecurityStmtGroupId.RefreshFromStandardRange("SecurityStmtGroups", "", false, mRecord.SecurityStmtGroupId);
    }
    
    //   Account Types
    if (mRecord.AllowPageAccountTypes) {
      C.cboDefaultAccountTypeId.RefreshFromStandardRange("AccountTypes", mRecord.AccountTypesSqlWhere, false, mRecord.DefaultAccountTypeId);
    }
  }

  // Controls
  if (mRecord) {
    //   Other
    if (mRecord.AllowPageOther) {
      if (mRecord.AddonsCreditReporting) {
        C.lblAccountTypeInformationLists.TooltipText("CR Acc Type:\nInformation list for Credit Reporting 'Account Types'");
      }
    
      C.lblAccountInformationLists.TooltipText(mRecord.InformationListsTooltipText);
    }
  }

  // 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"
    pageGeneral_Refresh();
    pageOther_Refresh();
    pageAccountRoles_Refresh();
    pageSecurityTypes_Refresh();
    pageDocuments_Refresh();
    pageAccountTypes_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
      break;

    case "Other":
      // Other
      break;
  }
}

function tabDetails_UpdateButtons() {
  // Only show Advanced button on relevant pages
  switch (tabDetails.SelectedTabId()) {
    default:
      cmdAdvanced.hide();
      break;
  }
}

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

    case "Other":
      pageOther_Refresh();
      break;

    case "AccountRoles":
      pageAccountRoles_Refresh();
      break;

    case "SecurityTypes":
      pageSecurityTypes_Refresh();
      break;

    case "Documents":
      pageDocuments_Refresh();
      break;

    case "AccountTypes":
      pageAccountTypes_Refresh();
      break;

    default:
      break;
  }

  // Resize
  tabDetails_Resize();

  // Update Buttons
  tabDetails_UpdateButtons();

  // 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 Record Id just in case this has changed
      widget.RefreshParent(C.txtProductTypeId.Text());
    },

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

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

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

  // Controls
}

// ===========
// pageOther
// ===========
function pageOther_Refresh() {
  if (!mRecord) return;

  // Controls
}

// ================
// pageAccountRoles
// ================
function pageAccountRoles_Refresh() {
  if (!mRecord) return;
  
  // Controls
  
  // Grids
  gridAccountRoles_Refresh();
}

// =================
// pageSecurityTypes
// =================
function pageSecurityTypes_Refresh() {
    if (!mRecord) return;
  
  // Controls
  
  // Grids
  gridSecurityTypes_Refresh();
}

// =============
// pageDocuments
// =============
function pageDocuments_Refresh() {
    if (!mRecord) return;
  
  // Controls
  
  // Grids
  gridDocuments_Refresh();
}

// =============
// pageDocuments
// =============
function pageAccountTypes_Refresh() {
    if (!mRecord) return;
  
  // Controls
  
  // Grids
  gridAccountTypes_Refresh();
}

// ==============
// txtDescription
// ==============
function txtDescription_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Show In Menu
  C.txtMenuCaption.BlankTip("New " + C.txtDescription.Text());
}

// =============
// chkShowInMenu
// =============
function chkShowInMenu_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.txtMenuCaption.VisibleRow(C.chkShowInMenu.Value());
}

// =======================
// cboDefaultAccountRoleId
// =======================
function cboDefaultAccountRoleId_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Refresh Grid
  C.gridAccountRoles.VirtualDataRefresh(mRecord.ProductTypeAccountRoles, true);
}

// =======================
// cboDefaultAccountTypeId
// =======================
function cboDefaultAccountTypeId_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Refresh Grid
  C.gridAccountTypes.VirtualDataRefresh(mRecord.ProductTypeAccountTypes, true);
}

// ================
// gridAccountRoles
// ================
function gridAccountRoles_Refresh() {
  // Add Columns
  C.gridAccountRoles.ClearColumns();
  C.gridAccountRoles.AddColumnString("RoleType", { caption: "Role Type", visible: false });
  C.gridAccountRoles.AddColumnBoolean("Available", { caption: "Available", allowEdit: !mRecord.ReadOnly });
  C.gridAccountRoles.AddColumnBoolean("Default", { caption: "Default", allowEdit: !mRecord.ReadOnly });
  C.gridAccountRoles.AddColumnBoolean("Active", { caption: "Active" });
  C.gridAccountRoles.AddColumnCode("AccountRoleId", { caption: "Account Role", width: "10em" });
  C.gridAccountRoles.AddColumnString("Description", { caption: "Description" });

  // Actions
  if (!mRecord.ReadOnly) {
    C.gridAccountRoles.Actions().Define([{ actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                         { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                         { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                         { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },
                                         { actionId: "SelectGroup", tooltipText:"Select all rows in the current Group", icon: "Select_Same" },
                                         {},
                                         { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                         { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
                                        ]);
  }

  // Refresh
  C.gridAccountRoles.VirtualDataRefresh(mRecord.ProductTypeAccountRoles);

  // Activate First Row
  C.gridAccountRoles.ActivateFirstDataRow();
}

function gridAccountRoles_InitialiseRow(e) {
  var item = mRecord.ProductTypeAccountRoles[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  
  // Default Column
  if (C.cboDefaultAccountRoleId.Text() == item.AccountRoleId) {
    e.row.cells.Default.value = true;
  }
  else {
    e.row.cells.Default.value = false;
  }
  
  // Styling
  e.row.cells.Available.readOnly = mRecord.ReadOnly;
  e.row.cells.Default.readOnly = mRecord.ReadOnly;
  e.row.cells.Active.readOnly = true;
  e.row.cells.AccountRoleId.readOnly = true;
  e.row.cells.Description.readOnly = true;
  
  // Hyperlinks
  e.row.cells.AccountRoleId.hyperlink = "app://FormShow?form=AccountRoles&amp;id=" + widget.UI.HtmlEncode(item.AccountRoleId);
}

function gridAccountRoles_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridAccountRoles.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord.ProductTypeAccountRoles.length; i++) {        
        if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
          indexes.push(i);
        }
        else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
          indexes.push(i);
        }
      }
      C.gridAccountRoles.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord.ProductTypeAccountRoles.length; i++) {
        indexes.push(i);
      }
      C.gridAccountRoles.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTNONE":
      C.gridAccountRoles.SetSelectedRowIndexes([], true);
      break;

    case "SELECTGROUP":
      var i = C.gridAccountRoles.ActiveDataRowListIndex();
      
      if (i != -1) {
        var item = mRecord.ProductTypeAccountRoles[i];
        
        if (item.RoleType) {
          var indexes = [];
          
          for(var j = 0; j &lt; mRecord.ProductTypeAccountRoles.length; j++) {        
            var item2 = mRecord.ProductTypeAccountRoles[j];
            
            if (item2.RoleType == item.RoleType) indexes.push(j);
          }          
          C.gridAccountRoles.SetSelectedRowIndexes(indexes, true);
        }
      }
      break;

    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridAccountRoles.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mRecord.ProductTypeAccountRoles[selectedItems[i]];
        item.Available = (actionId.toUpperCase() == "CHECK")
      }
      C.gridAccountRoles.VirtualDataRefresh(mRecord.ProductTypeAccountRoles, true, { retainSelectedRows: true });
      break;
  }
}

function gridAccountRoles_AfterRowActivate(e) {
  // Refresh Buttons
  gridAccountRoles_RefreshButtons();
}

function gridAccountRoles_RefreshButtons() {
  if (C.gridAccountRoles.ActiveDataRowListIndex() == -1) {
    C.gridAccountRoles.Actions().SetEnabled("SelectGroup", false);
  }
  else {
    C.gridAccountRoles.Actions().SetEnabled("SelectGroup", true);
  }

  C.gridAccountRoles.RefreshButtons();
}

function gridAccountRoles_BeforeCellUpdate(e) {
  var item = mRecord.ProductTypeAccountRoles[e.row.listIndex];
  
  switch(e.columnKey) {
    case "Available":
      item.Available = e.newValue;
      break;
      
    case "Default":
      if (item.AccountRoleId == C.cboDefaultAccountRoleId.Text()) {
        C.cboDefaultAccountRoleId.Text("");     
      }
      else {
        C.cboDefaultAccountRoleId.Text(item.AccountRoleId);
      }       
      cboDefaultAccountRoleId_Change();
      break;
  }
}

// =================
// gridSecurityTypes
// =================
function gridSecurityTypes_Refresh() {
  // Add Columns
  C.gridSecurityTypes.ClearColumns();
  C.gridSecurityTypes.AddColumnString("BaseType", { caption: "Base Type", visible: false });
  C.gridSecurityTypes.AddColumnBoolean("Available", { caption: "Available", allowEdit: !mRecord.ReadOnly });  
  C.gridSecurityTypes.AddColumnBoolean("Active", { caption: "Active" });
  C.gridSecurityTypes.AddColumnCode("SecurityTypeId", { caption: "Security Type", width: "10em" });
  C.gridSecurityTypes.AddColumnString("Description", { caption: "Description" });

  // Actions
  if (!mRecord.ReadOnly) {
    C.gridSecurityTypes.Actions().Define([{ actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                          { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                          { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                          { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },
                                          { actionId: "SelectGroup", tooltipText:"Select all rows in the current Group", icon: "Select_Same" },
                                          {},
                                          { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                          { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
                                         ]);
  }

  // Refresh
  C.gridSecurityTypes.VirtualDataRefresh(mRecord.ProductTypeSecurityTypes);

  // Activate First Row
  C.gridSecurityTypes.ActivateFirstDataRow();
}

function gridSecurityTypes_InitialiseRow(e) {
  var item = mRecord.ProductTypeSecurityTypes[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  
  // Styling
  e.row.cells.Available.readOnly = mRecord.ReadOnly;
  e.row.cells.Active.readOnly = true;
  e.row.cells.SecurityTypeId.readOnly = true;
  e.row.cells.Description.readOnly = true;
  
  // Hyperlinks
  e.row.cells.SecurityTypeId.hyperlink = "app://FormShow?form=SecurityTypes&amp;id=" + widget.UI.HtmlEncode(item.SecurityTypeId);
}

function gridSecurityTypes_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridSecurityTypes.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord.ProductTypeSecurityTypes.length; i++) {        
        if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
          indexes.push(i);
        }
        else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
          indexes.push(i);
        }
      }
      C.gridSecurityTypes.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord.ProductTypeSecurityTypes.length; i++) {
        indexes.push(i);
      }
      C.gridSecurityTypes.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTNONE":
      C.gridSecurityTypes.SetSelectedRowIndexes([], true);
      break;

    case "SELECTGROUP":
      var i = C.gridSecurityTypes.ActiveDataRowListIndex();
      
      if (i != -1) {
        var item = mRecord.ProductTypeSecurityTypes[i];
        
        if (item.BaseType) {
          var indexes = [];
          
          for(var j = 0; j &lt; mRecord.ProductTypeSecurityTypes.length; j++) {        
            var item2 = mRecord.ProductTypeSecurityTypes[j];
            
            if (item2.BaseType == item.BaseType) indexes.push(j);
          }          
          C.gridSecurityTypes.SetSelectedRowIndexes(indexes, true);
        }
      }
      break;

    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridSecurityTypes.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mRecord.ProductTypeSecurityTypes[selectedItems[i]];
        item.Available = (actionId.toUpperCase() == "CHECK")
      }
      C.gridSecurityTypes.VirtualDataRefresh(mRecord.ProductTypeSecurityTypes, true, { retainSelectedRows: true });
      break;
  }
}

function gridSecurityTypes_AfterRowActivate(e) {
  // Refresh Buttons
  gridSecurityTypes_RefreshButtons();
}

function gridSecurityTypes_RefreshButtons() {
  if (C.gridSecurityTypes.ActiveDataRowListIndex() == -1) {
    C.gridSecurityTypes.Actions().SetEnabled("SelectGroup", false);
  }
  else {
    C.gridSecurityTypes.Actions().SetEnabled("SelectGroup", true);
  }

  C.gridSecurityTypes.RefreshButtons();
}

function gridSecurityTypes_BeforeCellUpdate(e) {
  var item = mRecord.ProductTypeSecurityTypes[e.row.listIndex];
  
  switch(e.columnKey) {
    case "Available":
      item.Available = e.newValue;
      break;
  }
}

// =============
// gridDocuments
// =============
function gridDocuments_Refresh() {
  var showWarning = false;
  
  // Show Warning?
  for (var i = 0; i &lt; mRecord.ProductTypeDocuments.length; i++) {
    var item = mRecord.ProductTypeDocuments[i];
    
    if (item.Message) showWarning = true;
  }

  // Add Columns
  C.gridDocuments.ClearColumns();
  C.gridDocuments.AddColumnIcon("Warning", { visible: showWarning, allowDrilldown: true });
  C.gridDocuments.AddColumnString("Category", { caption: "Category", visible: false });
  C.gridDocuments.AddColumnBoolean("Available", { caption: "Available", allowEdit: !mRecord.ReadOnly });  
  C.gridDocuments.AddColumnBoolean("Active", { caption: "Active" });
  C.gridDocuments.AddColumnCode("DocumentId", { caption: "Document", width: "10em" });
  C.gridDocuments.AddColumnString("Description", { caption: "Description" });

  // Actions
  if (!mRecord.ReadOnly) {
    C.gridDocuments.Actions().Define([{ actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                      { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                      { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                      { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },
                                      { actionId: "SelectGroup", tooltipText:"Select all rows in the current Group", icon: "Select_Same" },
                                      {},
                                      { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                      { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
                                     ]);
  }

  // Refresh
  C.gridDocuments.VirtualDataRefresh(mRecord.ProductTypeDocuments);

  // Activate First Row
  C.gridDocuments.ActivateFirstDataRow();
}

function gridDocuments_InitialiseRow(e) {
  var item = mRecord.ProductTypeDocuments[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);

  // Warning Icon
  if (item.Message) {
    e.row.cells.Warning.value = "Warning";
    e.row.cells.Warning.tooltipText = item.Message;
  }
  else {
    e.row.cells.Warning.value = "Blank";
  }
  
  // Styling
  e.row.cells.Available.readOnly = mRecord.ReadOnly;
  e.row.cells.Active.readOnly = true;
  e.row.cells.DocumentId.readOnly = true;
  e.row.cells.Description.readOnly = true;
  
  // Hyperlinks
  e.row.cells.DocumentId.hyperlink = "app://FormShow?form=Documents&amp;id=" + widget.UI.HtmlEncode(item.DocumentId);
}

function gridDocuments_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridDocuments.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mRecord.ProductTypeDocuments.length; i++) {        
        if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
          indexes.push(i);
        }
        else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
          indexes.push(i);
        }
      }
      C.gridDocuments.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mRecord.ProductTypeDocuments.length; i++) {
        indexes.push(i);
      }
      C.gridDocuments.SetSelectedRowIndexes(indexes, true);
      break;

    case "SELECTNONE":
      C.gridDocuments.SetSelectedRowIndexes([], true);
      break;

    case "SELECTGROUP":
      var i = C.gridDocuments.ActiveDataRowListIndex();
      
      if (i != -1) {
        var item = mRecord.ProductTypeDocuments[i];
        
        if (item.Category) {
          var indexes = [];
          
          for(var j = 0; j &lt; mRecord.ProductTypeDocuments.length; j++) {        
            var item2 = mRecord.ProductTypeDocuments[j];
            
            if (item2.Category == item.Category) indexes.push(j);
          }          
          C.gridDocuments.SetSelectedRowIndexes(indexes, true);
        }
      }
      break;

    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridDocuments.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mRecord.ProductTypeDocuments[selectedItems[i]];
        item.Available = (actionId.toUpperCase() == "CHECK")
      }
      C.gridDocuments.VirtualDataRefresh(mRecord.ProductTypeDocuments, true, { retainSelectedRows: true });
      break;
  }
}

function gridDocuments_AfterRowActivate(e) {
  // Refresh Buttons
  gridDocuments_RefreshButtons();
}

function gridDocuments_RefreshButtons() {
  if (C.gridDocuments.ActiveDataRowListIndex() == -1) {
    C.gridDocuments.Actions().SetEnabled("SelectGroup", false);
  }
  else {
    C.gridDocuments.Actions().SetEnabled("SelectGroup", true);
  }

  C.gridDocuments.RefreshButtons();
}

function gridDocuments_BeforeCellUpdate(e) {
  var item = mRecord.ProductTypeDocuments[e.row.listIndex];
  
  switch(e.columnKey) {
    case "Available":
      item.Available = e.newValue;
      break;
  }
}

function gridDocuments_RowDrilldown(e) {
  var item = mRecord.ProductTypeDocuments[e.row.listIndex];
  
  switch(e.columnKey) {      
    case "Warning":            
      if (item.Message) {
        var message = "&lt;b&gt;" + widget.UI.HtmlEncode(item.DocumentId) + "&lt;/b&gt; (&lt;i&gt;" + widget.UI.HtmlEncode(item.Description) + "&lt;/i&gt;)&lt;/br&gt;&lt;/br&gt;";
        message += widget.UI.HtmlEncode(item.Message);
        
        widget.UI.MsgBoxAlert(message, { messageIsHtml: true, title: "Document Warning" });
      }
      break;
  }
}

// ================
// gridAccountTypes
// ================
function gridAccountTypes_Refresh() {
  // Add Columns
  C.gridAccountTypes.ClearColumns();
  C.gridAccountTypes.AddColumnBoolean("Default", { caption: "Default", allowEdit: !mRecord.ReadOnly });
  C.gridAccountTypes.AddColumnBoolean("Active", { caption: "Active" });
  C.gridAccountTypes.AddColumnCode("AccountTypeId", { caption: "Account Type", width: "10em" });
  C.gridAccountTypes.AddColumnString("Description", { caption: "Description" });

  // Refresh
  C.gridAccountTypes.VirtualDataRefresh(mRecord.ProductTypeAccountTypes);

  // Activate First Row
  C.gridAccountTypes.ActivateFirstDataRow();
}

function gridAccountTypes_InitialiseRow(e) {
  var item = mRecord.ProductTypeAccountTypes[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  
  // Default Column
  if (C.cboDefaultAccountTypeId.Text() == item.AccountTypeId) {
    e.row.cells.Default.value = true;
  }
  else {
    e.row.cells.Default.value = false;
  }
  
  // Styling
  e.row.cells.Default.readOnly = mRecord.ReadOnly;
  e.row.cells.Active.readOnly = true;
  e.row.cells.AccountTypeId.readOnly = true;
  e.row.cells.Description.readOnly = true;
  
  // Hyperlinks
  e.row.cells.AccountTypeId.hyperlink = "app://FormShow?form=AccountTypes&amp;id=" + widget.UI.HtmlEncode(item.AccountTypeId);
}

function gridAccountTypes_BeforeCellUpdate(e) {
  var item = mRecord.ProductTypeAccountTypes[e.row.listIndex];
  
  switch(e.columnKey) {      
    case "Default":
      if (item.AccountTypeId == C.cboDefaultAccountTypeId.Text()) {
        C.cboDefaultAccountTypeId.Text("");     
      }
      else {
        C.cboDefaultAccountTypeId.Text(item.AccountTypeId);
      }       
      cboDefaultAccountTypeId_Change();
      break;
  }
}

// ====================
// 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>iFKm39rrpUupHEHNH6DQBA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Product Type</Caption>
    <HtmlWidgetMaxHeight>800</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon>ProductType</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="ProductTypeId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>ProductTypes</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="DuplicateRecordId" 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.ProductTypes</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,Other</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>